<?php
// admin/pages_action.php - actions pages en base (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; }

function slugifie_page(string $s): string {
    $t=@iconv('UTF-8','ASCII//TRANSLIT',$s); if($t!==false)$s=$t;
    $s=strtolower($s); $s=preg_replace('/[^a-z0-9]+/','-',$s);
    return trim($s,'-') ?: 'page';
}

switch ($action) {

  case 'list': {
    $rows = $db->query("SELECT id,titre,slug,statut,maj_le FROM pages ORDER BY maj_le DESC")->fetchAll(PDO::FETCH_ASSOC);
    out(['ok'=>true,'pages'=>$rows]);
  }

  case 'create': {
    $titre = trim($_POST['titre'] ?? '');
    if ($titre === '') out(['ok'=>false,'error'=>'Titre requis']);
    $racine = slugifie_page($titre); $slug=$racine; $i=2;
    $chk=$db->prepare("SELECT COUNT(*) FROM pages WHERE slug=?");
    while(true){ $chk->execute([$slug]); if((int)$chk->fetchColumn()===0) break; $slug=$racine.'-'.$i++; }
    $db->prepare("INSERT INTO pages(titre,slug,statut) VALUES(?,?,'brouillon')")->execute([$titre,$slug]);
    out(['ok'=>true,'id'=>$db->lastInsertId(),'slug'=>$slug]);
  }

  case 'statut': {
    $id=(int)($_POST['id']??0); $s=($_POST['statut']??'')==='publie'?'publie':'brouillon';
    if(!$id) out(['ok'=>false,'error'=>'id manquant']);
    $db->prepare("UPDATE pages SET statut=?,maj_le=datetime('now') WHERE id=?")->execute([$s,$id]);
    out(['ok'=>true]);
  }

  case 'rename': {
    $id=(int)($_POST['id']??0); $titre=trim($_POST['titre']??'');
    if(!$id||$titre==='') out(['ok'=>false,'error'=>'parametres manquants']);
    $db->prepare("UPDATE pages SET titre=?,maj_le=datetime('now') WHERE id=?")->execute([$titre,$id]);
    out(['ok'=>true]);
  }

  case 'delete': {
    $id=(int)($_POST['id']??0);
    $slug=$db->prepare("SELECT slug FROM pages WHERE id=?"); $slug->execute([$id]); $slug=$slug->fetchColumn();
    if($slug){
      $hote='page:'.$slug;
      // supprimer sections + blocs + zones associees
      $secs=$db->prepare("SELECT id FROM page_sections WHERE page_hote=?"); $secs->execute([$hote]);
      foreach($secs->fetchAll(PDO::FETCH_COLUMN) as $sid){
        $bl=$db->prepare("SELECT type,cle FROM section_blocs WHERE section_id=?"); $bl->execute([$sid]);
        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([$sid]);
      }
      $db->prepare("DELETE FROM page_sections WHERE page_hote=?")->execute([$hote]);
      $db->prepare("DELETE FROM pages WHERE id=?")->execute([$id]);
    }
    out(['ok'=>true]);
  }
}
out(['ok'=>false,'error'=>'action inconnue']);
