<?php
// admin/zone_action.php — associe une image à une zone (protégé).
require_once dirname(__DIR__) . '/inc/schema.php';
require_once dirname(__DIR__) . '/inc/auth.php';
auth_require();
header('Content-Type: application/json; charset=utf-8');
init_schema();
db()->exec("CREATE TABLE IF NOT EXISTS zones_images (cle TEXT PRIMARY KEY, media_id INTEGER, alt TEXT DEFAULT '', maj_le TEXT DEFAULT (datetime('now')))");
// Colonnes forme/bordure (ajout idempotent)
$zc = array_column(db()->query("PRAGMA table_info(zones_images)")->fetchAll(PDO::FETCH_ASSOC),'name');
if (!in_array('forme',$zc))      db()->exec("ALTER TABLE zones_images ADD COLUMN forme TEXT DEFAULT 'rond'");
if (!in_array('bordure',$zc))    db()->exec("ALTER TABLE zones_images ADD COLUMN bordure INTEGER DEFAULT 0");
if (!in_array('ajustement',$zc)) db()->exec("ALTER TABLE zones_images ADD COLUMN ajustement TEXT DEFAULT 'cover'");
if (!in_array('zoom',$zc))       db()->exec("ALTER TABLE zones_images ADD COLUMN zoom INTEGER DEFAULT 100");

$zone = trim($_POST['zone'] ?? '');

// Suppression : vider la zone
if (($_POST['op'] ?? '') === 'clear') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    db()->prepare('DELETE FROM zones_images WHERE cle=?')->execute([$zone]);
    echo json_encode(['ok'=>true,'cleared'=>true,'zone'=>$zone]);
    exit;
}

// Réglage de taille (UPSERT : la zone peut ne pas encore exister)
if (($_POST['op'] ?? '') === 'size') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $taille = max(0, min(500, (int)($_POST['taille'] ?? 0)));
    db()->prepare("INSERT INTO zones_images (cle,taille,maj_le) VALUES (?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET taille=excluded.taille, maj_le=datetime('now')")->execute([$zone,$taille]);
    echo json_encode(['ok'=>true,'taille'=>$taille,'zone'=>$zone]);
    exit;
}

// Alignement horizontal du conteneur
if (($_POST['op'] ?? '') === 'align') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $al = $_POST['align'] ?? 'center';
    if (!in_array($al, ['left','center','right'], true)) $al = 'center';
    db()->prepare("INSERT INTO zones_images (cle,align,maj_le) VALUES (?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET align=excluded.align, maj_le=datetime('now')")->execute([$zone,$al]);
    echo json_encode(['ok'=>true,'align'=>$al,'zone'=>$zone]);
    exit;
}

// Position de l'image dans le cadre (object-position)
if (($_POST['op'] ?? '') === 'position') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $px = max(0, min(100, (int)($_POST['pos_x'] ?? 50)));
    $py = max(0, min(100, (int)($_POST['pos_y'] ?? 50)));
    db()->prepare("INSERT INTO zones_images (cle,pos_x,pos_y,maj_le) VALUES (?,?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET pos_x=excluded.pos_x, pos_y=excluded.pos_y, maj_le=datetime('now')")->execute([$zone,$px,$py]);
    echo json_encode(['ok'=>true,'pos_x'=>$px,'pos_y'=>$py,'zone'=>$zone]);
    exit;
}

// Ajustement : cover (remplit) ou contain (image entière)
if (($_POST['op'] ?? '') === 'ajustement') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $aj = $_POST['ajustement'] ?? 'cover';
    if (!in_array($aj, ['cover','contain'], true)) $aj = 'cover';
    db()->prepare("INSERT INTO zones_images (cle,ajustement,maj_le) VALUES (?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET ajustement=excluded.ajustement, maj_le=datetime('now')")->execute([$zone,$aj]);
    echo json_encode(['ok'=>true,'ajustement'=>$aj,'zone'=>$zone]);
    exit;
}

// Zoom de l'image dans le cadre (50–300 %)
if (($_POST['op'] ?? '') === 'zoom') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $zo = max(50, min(300, (int)($_POST['zoom'] ?? 100)));
    db()->prepare("INSERT INTO zones_images (cle,zoom,maj_le) VALUES (?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET zoom=excluded.zoom, maj_le=datetime('now')")->execute([$zone,$zo]);
    echo json_encode(['ok'=>true,'zoom'=>$zo,'zone'=>$zone]);
    exit;
}

// Forme : rond ou normal
if (($_POST['op'] ?? '') === 'forme') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $fo = $_POST['forme'] ?? 'rond';
    if (!in_array($fo, ['rond','normal'], true)) $fo = 'rond';
    db()->prepare("INSERT INTO zones_images (cle,forme,maj_le) VALUES (?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET forme=excluded.forme, maj_le=datetime('now')")->execute([$zone,$fo]);
    echo json_encode(['ok'=>true,'forme'=>$fo,'zone'=>$zone]);
    exit;
}

// Bordure : 1 (oui) ou 0 (non)
if (($_POST['op'] ?? '') === 'bordure') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $bo = ((int)($_POST['bordure'] ?? 0) === 1) ? 1 : 0;
    db()->prepare("INSERT INTO zones_images (cle,bordure,maj_le) VALUES (?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET bordure=excluded.bordure, maj_le=datetime('now')")->execute([$zone,$bo]);
    echo json_encode(['ok'=>true,'bordure'=>$bo,'zone'=>$zone]);
    exit;
}

// Réglage des marges (UPSERT)
if (($_POST['op'] ?? '') === 'marges') {
    if ($zone === '') { echo json_encode(['ok'=>false,'error'=>'Zone manquante']); exit; }
    $mh = max(-150, min(200, (int)($_POST['marge_haut'] ?? 0)));
    $mb = max(-150, min(200, (int)($_POST['marge_bas'] ?? 0)));
    db()->prepare("INSERT INTO zones_images (cle,marge_haut,marge_bas,maj_le) VALUES (?,?,?,datetime('now'))
        ON CONFLICT(cle) DO UPDATE SET marge_haut=excluded.marge_haut, marge_bas=excluded.marge_bas, maj_le=datetime('now')")->execute([$zone,$mh,$mb]);
    echo json_encode(['ok'=>true,'marge_haut'=>$mh,'marge_bas'=>$mb,'zone'=>$zone]);
    exit;
}

$mediaId = (int)($_POST['media_id'] ?? 0);
if ($zone === '' || $mediaId <= 0) { echo json_encode(['ok'=>false,'error'=>'Paramètres manquants']); exit; }

$st = db()->prepare('SELECT url FROM medias WHERE id=?');
$st->execute([$mediaId]);
$url = $st->fetchColumn();
if (!$url) { echo json_encode(['ok'=>false,'error'=>'Image introuvable']); exit; }

$up = db()->prepare("INSERT INTO zones_images (cle,media_id,maj_le) VALUES (?,?,datetime('now'))
    ON CONFLICT(cle) DO UPDATE SET media_id=excluded.media_id, maj_le=datetime('now')");
$up->execute([$zone,$mediaId]);

echo json_encode(['ok'=>true,'url'=>$url,'zone'=>$zone]);
