<?php
// admin/section_builder.php - actions du constructeur de sections (JSON). Protege par login.
require_once dirname(__DIR__) . '/inc/schema.php';
require_once dirname(__DIR__) . '/inc/auth.php';
auth_require();
header('Content-Type: application/json; charset=utf-8');
header('X-LiteSpeed-Cache-Control: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
init_schema();
$db = db();
$action = $_POST['action'] ?? $_GET['action'] ?? '';
function out($a){ echo json_encode($a); exit; }

switch ($action) {

  case 'add_section': {
    $hote = trim($_POST['hote'] ?? '');
    $n = max(1, min(3, (int)($_POST['n'] ?? 1)));
    if ($hote === '') out(['ok'=>false,'error'=>'hote manquant']);
    $pos = $db->prepare("SELECT COALESCE(MAX(position),-1)+1 FROM page_sections WHERE page_hote=?");
    $pos->execute([$hote]); $pos = $pos->fetchColumn();
    $st = $db->prepare("INSERT INTO page_sections(page_hote,disposition,position) VALUES(?,?,?)");
    $st->execute([$hote,(string)$n,$pos]);
    out(['ok'=>true,'id'=>$db->lastInsertId()]);
  }

  case 'set_disposition': {
    $sec = (int)($_POST['sec'] ?? 0);
    $n = max(1, min(3, (int)($_POST['n'] ?? 1)));
    if (!$sec) out(['ok'=>false,'error'=>'sec manquant']);
    // si on reduit le nb de colonnes, ramener les blocs des colonnes supprimees vers la derniere colonne valide
    $db->prepare("UPDATE section_blocs SET colonne=? WHERE section_id=? AND colonne>?")->execute([$n-1,$sec,$n-1]);
    $db->prepare("UPDATE page_sections SET disposition=?,maj_le=datetime('now') WHERE id=?")->execute([(string)$n,$sec]);
    out(['ok'=>true]);
  }

  case 'move_section': {
    $sec = (int)($_POST['sec'] ?? 0);
    $dir = $_POST['dir'] ?? '';
    $row = $db->prepare("SELECT page_hote,position FROM page_sections WHERE id=?");
    $row->execute([$sec]); $row = $row->fetch(PDO::FETCH_ASSOC);
    if (!$row) out(['ok'=>false,'error'=>'introuvable']);
    $op = $dir === 'up' ? '<' : '>';
    $ord = $dir === 'up' ? 'DESC' : 'ASC';
    $vois = $db->prepare("SELECT id,position FROM page_sections WHERE page_hote=? AND position $op ? ORDER BY position $ord LIMIT 1");
    $vois->execute([$row['page_hote'],$row['position']]);
    $vois = $vois->fetch(PDO::FETCH_ASSOC);
    if ($vois) {
      $db->prepare("UPDATE page_sections SET position=? WHERE id=?")->execute([$vois['position'],$sec]);
      $db->prepare("UPDATE page_sections SET position=? WHERE id=?")->execute([$row['position'],$vois['id']]);
    }
    out(['ok'=>true]);
  }

  case 'del_section': {
    $sec = (int)($_POST['sec'] ?? 0);
    // supprime aussi les zones (textes/images) des blocs de la section
    $bl = $db->prepare("SELECT type,cle FROM section_blocs WHERE section_id=?");
    $bl->execute([$sec]);
    foreach ($bl->fetchAll(PDO::FETCH_ASSOC) as $b) {
      if ($b['type']==='image') $db->prepare("DELETE FROM zones_images WHERE cle=?")->execute([$b['cle']]);
      else $db->prepare("DELETE FROM zones_textes WHERE cle=?")->execute([$b['cle']]);
    }
    $db->prepare("DELETE FROM section_blocs WHERE section_id=?")->execute([$sec]);
    $db->prepare("DELETE FROM page_sections WHERE id=?")->execute([$sec]);
    out(['ok'=>true]);
  }

  case 'add_bloc': {
    $sec = (int)($_POST['sec'] ?? 0);
    $col = max(0, min(2, (int)($_POST['col'] ?? 0)));
    $type = in_array($_POST['type'] ?? '', ['titre','texte','image'], true) ? $_POST['type'] : '';
    if (!$sec || !$type) out(['ok'=>false,'error'=>'parametres manquants']);
    $pos = $db->prepare("SELECT COALESCE(MAX(position),-1)+1 FROM section_blocs WHERE section_id=? AND colonne=?");
    $pos->execute([$sec,$col]); $pos = $pos->fetchColumn();
    // cle de zone unique et stable
    $cle = 'sx.'.$sec.'.'.$col.'.'.$type.'.'.substr(md5(uniqid('',true)),0,6);
    $db->prepare("INSERT INTO section_blocs(section_id,colonne,type,position,cle) VALUES(?,?,?,?,?)")
       ->execute([$sec,$col,$type,$pos,$cle]);
    out(['ok'=>true,'id'=>$db->lastInsertId(),'cle'=>$cle]);
  }

  case 'del_bloc': {
    $bloc = (int)($_POST['bloc'] ?? 0);
    $b = $db->prepare("SELECT type,cle FROM section_blocs WHERE id=?");
    $b->execute([$bloc]); $b = $b->fetch(PDO::FETCH_ASSOC);
    if ($b) {
      if ($b['type']==='image') $db->prepare("DELETE FROM zones_images WHERE cle=?")->execute([$b['cle']]);
      else $db->prepare("DELETE FROM zones_textes WHERE cle=?")->execute([$b['cle']]);
      $db->prepare("DELETE FROM section_blocs WHERE id=?")->execute([$bloc]);
    }
    out(['ok'=>true]);
  }
}
out(['ok'=>false,'error'=>'action inconnue']);
