<?php
include($_SERVER['DOCUMENT_ROOT'] . "/admin/pdo.inc");
include($_SERVER['DOCUMENT_ROOT'] . "/includes/functions.inc");

// Authenticate
if (!isset($_COOKIE['SIM_id']) || !$SIMinfo = get_user_code()) exit("You need to log in.");
$user_code 		= $SIMinfo['user_code'];

$template_id 	= (int)($_GET['template_id'] ?? 0);
$menu_id    	= (int)($_GET['menu_id'] ?? 0);
$page_id 		= $_GET['page_id'] ?? 0;
if (!$page_id) exit("Page ID is required.");

// Fetch page info
$stmt = $pdo->prepare("SELECT * FROM simeya_template_pages WHERE page_id = ?");
$stmt->execute([$page_id]);
$page = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$page) exit("Page not found");

// Fetch blocks for this page
$stmt = $pdo->prepare("
    SELECT b.block_id, b.block_content, b.block_type, pb.sort_order
    FROM simeya_template_page_blocks pb
    JOIN simeya_section_blocks b ON pb.block_id = b.block_id
    WHERE pb.page_id = ?
    ORDER BY pb.sort_order ASC
");
$stmt->execute([$page_id]);
$blocks = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
  <title>Edit Page: <?= htmlspecialchars($page['page_title']) ?></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.0/Sortable.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@ckeditor/ckeditor5-build-inline/build/ckeditor.js"></script>
  <style>
    body { background: #f8f9fa; }
    .block-edit { border: 1px dashed #ccc; padding: 15px; margin-bottom: 15px; background: #fff; position: relative; }
    .block-toolbar { position: absolute; top: 5px; right: 5px; z-index: 10; }
    .block-toolbar button { margin-left: 3px; }
  </style>
</head>
<body>
	
<?php
$is_modal = isset($_GET['in_modal']);
if (!$is_modal) {
  include($_SERVER['DOCUMENT_ROOT']."/templates/header.php");
}
?>

<div class="container py-4">
  <h3 class="mb-4">Editing Page: <?= htmlspecialchars($page['page_title']) ?></h3>

  <div id="page-blocks">
    <?php foreach ($blocks as $block): ?>
      
       <div class="text-center">
        <a href="/templates/pages/edit-block.php?template_id=<?= $template_id ?>&menu_id=<?= $menu_id ?>&page_id=<?= $page_id ?>" class="btn btn-primary btn-outline-secondary btn-sm text-white">Edit This Block</a>
       </div>
       
      <div class="block-edit" data-block-id="<?= $block['block_id'] ?>">
        <div class="block-toolbar">
          <button class="btn btn-sm btn-outline-secondary bg-primary edit-text">✏️ Text</button>
          <button class="btn btn-sm btn-outline-primary bg-info change-image">🖼️ Image</button>
          <button class="btn btn-sm btn-outline-danger bg-warning delete-block">🗑️ Delete</button>
        </div>
        <div class="block-content">
          <?= $block['block_content'] ?>
        </div>
      </div>
    <?php endforeach; ?>
  </div>

  <div class="mt-4">
  <button id="saveOrder" class="btn btn-success">Save Order</button>
  <button id="previewPage" class="btn btn-secondary">Preview Draft</button>
  <button id="publishPage" class="btn btn-primary">Publish Page</button>
</div>

</div>

<input type="file" id="imageUpload" accept="image/*" style="display:none;">

<?php
if (!$is_modal) {
  include($_SERVER['DOCUMENT_ROOT']."/includes/footer.php");
}
?>

<script>
const pageId = <?= $page_id ?>;
document.addEventListener("DOMContentLoaded", () => {
  new Sortable(document.getElementById('page-blocks'), {
    animation: 150
  });

  // Inline text edit
  document.querySelectorAll('.edit-text').forEach(btn => {
    btn.addEventListener('click', function() {
      const block = this.closest('.block-edit');
      const contentDiv = block.querySelector('.block-content');
      InlineEditor.create(contentDiv).then(editor => {
        editor.model.document.on('change:data', () => {
          fetch('/templates/pages/ajax_update_block.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `block_id=${block.dataset.blockId}&content=${encodeURIComponent(editor.getData())}`
          });
        });
      });
    });
  });

  // Image edit
  let activeBlock = null;
  document.querySelectorAll('.change-image').forEach(btn => {
    btn.addEventListener('click', function() {
      activeBlock = this.closest('.block-edit');
      document.getElementById('imageUpload').click();
    });
  });

  document.getElementById('imageUpload').addEventListener('change', function() {
    const file = this.files[0];
    if (!file || !activeBlock) return;
    const formData = new FormData();
    formData.append('block_id', activeBlock.dataset.blockId);
    formData.append('image', file);

    fetch('/templates/pages/ajax_update_image.php', {
      method: 'POST', body: formData
    }).then(res => res.text()).then(resp => {
      if (resp.trim().startsWith('<img')) {
        activeBlock.querySelector('.block-content').innerHTML = resp;
      }
    });
  });

  // Save order
  document.getElementById('saveOrder').addEventListener('click', () => {
    const order = [...document.querySelectorAll('#page-blocks .block-edit')]
      .map((b,i) => ({ id: b.dataset.blockId, pos: i+1 }));
    fetch('/templates/pages/ajax_update_order.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ page_id: pageId, order })
    }).then(r => r.text()).then(r => {
      if (r.trim() === 'success') alert('Order saved');
    });
  });

  // Preview
  document.getElementById('previewPage').addEventListener('click', () => {
    fetch('/templates/pages/ajax_preview_page.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: `page_id=${pageId}`
    }).then(res => res.text()).then(html => {
      const win = window.open('', 'Preview', 'width=1200,height=900');
      win.document.open();
      win.document.write(html);
      win.document.close();
    });
  });

  // Publish
  document.getElementById('publishPage').addEventListener('click', () => {
    fetch('/templates/pages/ajax_publish_page.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      body: `page_id=${pageId}`
    }).then(r => r.text()).then(r => {
      if (r.trim() === 'success') alert('Page published!');
    });
  });
});
</script>
</body>
</html>
