<?php
@session_start();
// ini_set('display_errors',1); error_reporting(E_ALL);

header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: same-origin');
header('Permissions-Policy: fullscreen=(), geolocation=(), microphone=()');

if (!file_exists(__DIR__.'/db.php')) { http_response_code(500); echo "Falta db.php"; exit; }
require __DIR__.'/db.php';
if (!function_exists('pdo')) { http_response_code(500); echo "db.php sin pdo()"; exit; }
$pdo = pdo();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$UPLOAD_DIR = __DIR__.'/uploads/publicidad';
$UPLOAD_URL = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/').'/uploads/publicidad';
if (!is_dir($UPLOAD_DIR)) @mkdir($UPLOAD_DIR, 0775, true);

function json_out($ok,$data=[],$code=200){ http_response_code($code); header('Content-Type: application/json; charset=utf-8'); echo json_encode(['ok'=>$ok]+$data); exit; }

$action = $_GET['action'] ?? $_POST['action'] ?? '';

if ($action==='list') {
  $page = $_GET['page'] ?? 'index';
  $st = $pdo->prepare("SELECT * FROM ad_items WHERE page_slug=? ORDER BY zindex ASC, id ASC");
  $st->execute([$page]);
  $rows=$st->fetchAll(PDO::FETCH_ASSOC);
  json_out(true, ['items'=>$rows]);
}

if ($action==='save') {
  $payload = json_decode($_POST['payload'] ?? '[]', true);
  if (!is_array($payload)) $payload=[];
  $now = date('Y-m-d H:i:s');

  $pdo->beginTransaction();
  try{
    foreach($payload as $it){
      $id=(int)($it['id']??0);
      $page=(string)($it['page_slug']??'index');
      $type=(string)($it['type']??'image');
      $title=(string)($it['title']??'');
      $media=(string)($it['media_url']??'');
      $link=(string)($it['link_url']??'');
      $html=(string)($it['html']??'');
      $x=(float)($it['x_pct']??10);
      $y=(float)($it['y_pct']??10);
      $w=(float)($it['w_pct']??30);
      $h=(isset($it['h_pct']) && $it['h_pct']!=='')? (float)$it['h_pct'] : null;
      $z=(int)($it['zindex']??10);
      $en=(int)($it['is_active']??1);

      if ($id>0){
        $st=$pdo->prepare("UPDATE ad_items
          SET page_slug=?,type=?,title=?,media_url=?,link_url=?,html=?,x_pct=?,y_pct=?,w_pct=?,h_pct=?,zindex=?,is_active=?,updated_at=?
          WHERE id=?");
        $st->execute([$page,$type,$title,$media,$link,$html,$x,$y,$w,$h,$z,$en,$now,$id]);
        if ($st->rowCount()===0){
          $st=$pdo->prepare("INSERT INTO ad_items
           (page_slug,type,title,media_url,link_url,html,x_pct,y_pct,w_pct,h_pct,zindex,is_active,created_at,updated_at)
           VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
          $st->execute([$page,$type,$title,$media,$link,$html,$x,$y,$w,$h,$z,$en,$now,$now]);
        }
      } else {
        $st=$pdo->prepare("INSERT INTO ad_items
         (page_slug,type,title,media_url,link_url,html,x_pct,y_pct,w_pct,h_pct,zindex,is_active,created_at,updated_at)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        $st->execute([$page,$type,$title,$media,$link,$html,$x,$y,$w,$h,$z,$en,$now,$now]);
      }
    }
    $pdo->commit();
    json_out(true, ['saved'=>count($payload)]);
  } catch(Throwable $e){
    $pdo->rollBack(); json_out(false, ['error'=>$e->getMessage()], 500);
  }
}

if ($action==='delete') {
  $id=(int)($_POST['id']??0);
  if ($id<=0) json_out(false, ['error'=>'ID inválido'], 400);
  $pdo->prepare("DELETE FROM ad_items WHERE id=?")->execute([$id]);
  json_out(true, ['deleted'=>$id]);
}

if ($action==='toggle') {
  $id=(int)($_POST['id']??0);
  if ($id<=0) json_out(false, ['error'=>'ID inválido'], 400);
  $pdo->prepare("UPDATE ad_items SET is_active=1-is_active, updated_at=? WHERE id=?")->execute([date('Y-m-d H:i:s'),$id]);
  json_out(true, ['id'=>$id]);
}

if ($action==='upload') {
  if (!isset($_FILES['file'])) json_out(false, ['error'=>'Sin archivo'], 400);
  $f=$_FILES['file']; if ($f['error']!==UPLOAD_ERR_OK) json_out(false, ['error'=>'Error de subida'], 400);
  $ext=strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
  $base=preg_replace('/[^a-zA-Z0-9_\.-]/','_', pathinfo($f['name'], PATHINFO_FILENAME));
  $name=$base.'_'.date('Ymd_His').'.'.$ext;
  $dest=$UPLOAD_DIR.'/'.$name;
  if (!move_uploaded_file($f['tmp_name'], $dest)) json_out(false, ['error'=>'No se pudo guardar'], 500);
  json_out(true, ['url'=>$UPLOAD_URL.'/'.$name]);
}

json_out(false, ['error'=>'acción inválida'], 400);
