<?php
require_once __DIR__ . '/../includes/config.php';
requireLogin();
$db = getDB();

// SAVE
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRF($_POST['csrf_token'] ?? '')) {
    foreach ($_POST['contents'] as $key => $value) {
        list($pageKey, $sectionKey, $contentKey) = explode('|', $key);
        $type = strpos($contentKey, 'photo') !== false ? 'image' : (strpos($value, '<') !== false ? 'html' : 'text');
        setPageContent(trim($pageKey), trim($sectionKey), trim($contentKey), $value, $type);
    }

    // Handle founder photo upload
    if (!empty($_FILES['founder_photo']['name'])) {
        $path = handleUpload('founder_photo', 'pages');
        if ($path) setPageContent('about', 'founder', 'photo', $path, 'image');
    }

    // Save values
    if (!empty($_POST['values'])) {
        foreach ($_POST['values'] as $id => $val) {
            $db->prepare("UPDATE values_cms SET titre=?, texte=? WHERE id=?")
               ->execute([sanitize($val['titre']), sanitize($val['texte']), (int)$id]);
        }
    }

    // Save services
    if (!empty($_POST['services'])) {
        foreach ($_POST['services'] as $id => $svc) {
            $imgPath = !empty($_FILES['service_images']['name'][$id]) ?
                handleUpload_indexed('service_images', $id, 'services') : null;
            $stmt = $imgPath ?
                $db->prepare("UPDATE services_cms SET titre=?, texte=?, image_path=? WHERE id=?") :
                $db->prepare("UPDATE services_cms SET titre=?, texte=? WHERE id=?");
            $params = [sanitize($svc['titre']), sanitize($svc['texte'])];
            if ($imgPath) $params[] = $imgPath;
            $params[] = (int)$id;
            $stmt->execute($params);
        }
    }

    setFlash('success', 'Contenu mis à jour.');
    redirect(SITE_URL . '/admin/page_contents');
}

function handleUpload_indexed(string $inputName, $index, string $subDir = ''): ?string {
    if (!isset($_FILES[$inputName]['tmp_name'][$index]) || $_FILES[$inputName]['error'][$index] !== UPLOAD_ERR_OK) return null;
    $ext = strtolower(pathinfo($_FILES[$inputName]['name'][$index], PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','webp','gif'])) return null;
    $targetDir = __DIR__ . '/../assets/uploads/' . ($subDir ? $subDir . '/' : '');
    if (!is_dir($targetDir)) mkdir($targetDir, 0755, true);
    $filename = uniqid('img_') . '.' . $ext;
    if (move_uploaded_file($_FILES[$inputName]['tmp_name'][$index], $targetDir . $filename)) {
        return 'assets/uploads/' . ($subDir ? $subDir . '/' : '') . $filename;
    }
    return null;
}

// Load content
$pages = [
    'about|agency|title'    => getPageContent('about','agency','title'),
    'about|agency|content'  => getPageContent('about','agency','content'),
    'about|founder|name'    => getPageContent('about','founder','name'),
    'about|founder|title'   => getPageContent('about','founder','title'),
    'about|founder|bio'     => getPageContent('about','founder','bio'),
    'estimation|intro|title'=> getPageContent('estimation','intro','title'),
    'estimation|intro|content'=> getPageContent('estimation','intro','content'),
    'rdv|intro|title'       => getPageContent('rdv','intro','title'),
    'rdv|intro|content'     => getPageContent('rdv','intro','content'),
    'services|intro|title'  => getPageContent('services','intro','title'),
    'services|intro|content'=> getPageContent('services','intro','content'),
];
$founderPhoto = getPageContent('about','founder','photo','assets/hind-ajouamai.jpg');
$values = $db->query("SELECT * FROM values_cms ORDER BY ordre ASC")->fetchAll();
$services = $db->query("SELECT * FROM services_cms ORDER BY ordre ASC")->fetchAll();

$pageTitle = 'Contenu des pages'; $activeNav = 'page_contents';
include __DIR__ . '/layout.php';
?>

<form method="POST" enctype="multipart/form-data" class="max-w-4xl space-y-10">
  <input type="hidden" name="csrf_token" value="<?=generateCSRF()?>"/>

  <!-- ══ À PROPOS ══ -->
  <div class="bg-white border border-gray-200 p-8">
    <h2 class="font-serif text-xl font-light text-black mb-6">Page "À Propos"</h2>

    <div class="space-y-6">
      <div>
        <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Titre — Vision de l'agence</label>
        <input type="text" name="contents[about|agency|title]" value="<?=htmlspecialchars($pages['about|agency|title'])?>" class="input-underline"/>
      </div>
      <div>
        <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Texte — Présentation de l'agence</label>
        <div id="agency-content-editor" class="quill-editor min-h-[150px]"><?=$pages['about|agency|content']?></div>
        <input type="hidden" name="contents[about|agency|content]" id="agency-content-editor_value" value="<?=htmlspecialchars($pages['about|agency|content'])?>"/>
      </div>
    </div>

    <hr class="my-8 border-gray-100"/>
    <h3 class="font-serif text-lg font-light text-black mb-6">Portrait de la Fondatrice</h3>
    <div class="grid md:grid-cols-2 gap-6">
      <div class="space-y-4">
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Nom</label>
          <input type="text" name="contents[about|founder|name]" value="<?=htmlspecialchars($pages['about|founder|name'])?>" class="input-underline"/>
        </div>
        <div>
          <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Titre / Fonction</label>
          <input type="text" name="contents[about|founder|title]" value="<?=htmlspecialchars($pages['about|founder|title'])?>" class="input-underline"/>
        </div>
      </div>
      <div>
        <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Photo</label>
        <?php if($founderPhoto): ?>
        <img src="/<?=htmlspecialchars($founderPhoto)?>" class="w-32 h-40 object-cover mb-3 object-top"/>
        <?php endif; ?>
        <input type="file" name="founder_photo" accept="image/*" class="text-sm font-sans text-gray-600 file:mr-4 file:py-2 file:px-4 file:border file:border-gray-200 file:text-xs file:font-sans file:tracking-[0.1em] file:uppercase file:cursor-pointer hover:file:border-black"/>
      </div>
    </div>
    <div class="mt-6">
      <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Biographie</label>
      <div id="founder-bio-editor" class="quill-editor min-h-[150px]"><?=$pages['about|founder|bio']?></div>
      <input type="hidden" name="contents[about|founder|bio]" id="founder-bio-editor_value" value="<?=htmlspecialchars($pages['about|founder|bio'])?>"/>
    </div>
  </div>

  <!-- ══ NOS VALEURS ══ -->
  <div class="bg-white border border-gray-200 p-8">
    <h2 class="font-serif text-xl font-light text-black mb-6">Nos Valeurs (3 piliers)</h2>
    <div class="space-y-6">
      <?php foreach($values as $v): ?>
      <div class="border border-gray-100 p-6">
        <div class="grid md:grid-cols-3 gap-4">
          <div>
            <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Titre</label>
            <input type="text" name="values[<?=$v['id']?>][titre]" value="<?=htmlspecialchars($v['titre'])?>" class="input-underline"/>
          </div>
          <div class="md:col-span-2">
            <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Texte</label>
            <textarea name="values[<?=$v['id']?>][texte]" rows="2" class="w-full border-b border-gray-200 focus:border-black outline-none py-2 text-sm font-sans resize-none"><?=htmlspecialchars($v['texte'])?></textarea>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- ══ NOS SERVICES ══ -->
  <div class="bg-white border border-gray-200 p-8">
    <h2 class="font-serif text-xl font-light text-black mb-6">Nos Services (3 services)</h2>
    <div class="space-y-8">
      <?php foreach($services as $svc): ?>
      <div class="border border-gray-100 p-6">
        <div class="grid md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <div>
              <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Titre</label>
              <input type="text" name="services[<?=$svc['id']?>][titre]" value="<?=htmlspecialchars($svc['titre'])?>" class="input-underline"/>
            </div>
            <div>
              <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Texte</label>
              <textarea name="services[<?=$svc['id']?>][texte]" rows="4" class="w-full border-b border-gray-200 focus:border-black outline-none py-2 text-sm font-sans resize-none"><?=htmlspecialchars($svc['texte'])?></textarea>
            </div>
          </div>
          <div>
            <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Image</label>
            <?php if($svc['image_path']): ?>
            <img src="/<?=htmlspecialchars($svc['image_path'])?>" class="w-full h-32 object-cover mb-3"/>
            <?php endif; ?>
            <input type="file" name="service_images[<?=$svc['id']?>]" accept="image/*" class="text-sm font-sans text-gray-600 file:mr-4 file:py-2 file:px-4 file:border file:border-gray-200 file:text-xs file:font-sans file:tracking-[0.1em] file:uppercase file:cursor-pointer hover:file:border-black"/>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- ══ AUTRES PAGES ══ -->
  <?php foreach([
    ['estimation','intro','Estimation','Texte d\'intro de la page Estimation'],
    ['rdv','intro','RDV','Texte d\'intro de la page Prendre RDV'],
    ['services','intro','Services','Texte d\'intro de la page Services'],
  ] as [$pk,$sk,$label,$desc]): ?>
  <div class="bg-white border border-gray-200 p-8">
    <h2 class="font-serif text-xl font-light text-black mb-2">Page "<?=$label?>"</h2>
    <p class="text-xs text-gray-400 font-sans mb-6"><?=$desc?></p>
    <div class="space-y-4">
      <div>
        <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Titre</label>
        <input type="text" name="contents[<?=$pk?>|<?=$sk?>|title]" value="<?=htmlspecialchars($pages["$pk|$sk|title"]??'')?>" class="input-underline"/>
      </div>
      <div>
        <label class="block text-[11px] tracking-[0.15em] uppercase text-gray-400 font-sans mb-2">Texte</label>
        <?php $eid = "$pk-$sk-content-editor"; ?>
        <div id="<?=$eid?>" class="quill-editor min-h-[120px]"><?=$pages["$pk|$sk|content"]??''?></div>
        <input type="hidden" name="contents[<?=$pk?>|<?=$sk?>|content]" id="<?=$eid?>_value" value="<?=htmlspecialchars($pages["$pk|$sk|content"]??"")?>"/>
      </div>
    </div>
  </div>
  <?php endforeach; ?>

  <button type="submit" class="bg-black text-white text-xs tracking-[0.15em] uppercase px-8 py-4 font-sans hover:bg-gray-900 transition-colors">Enregistrer tous les changements</button>
</form>

<?php include __DIR__ . '/layout_footer.php'; ?>
