<?php
session_start();
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/db.php';
if (empty($_SESSION['admin_id'])) { echo json_encode(['ok'=>false,'error'=>'auth']); exit; }

$raw = file_get_contents('php://input');
$in  = json_decode($raw,true);
$landing_id = (int)($in['landing_id'] ?? 0);
$items = $in['items'] ?? [];

if ($landing_id<=0 || !is_array($items)) { echo json_encode(['ok'=>false,'error'=>'input']); exit; }

$conn->begin_transaction();
try{
  $map_ids = []; // devolver ids para chips nuevos

  foreach($items as $it){
    $assign_id = isset($it['assign_id']) ? (int)$it['assign_id'] : 0;
    $block_id  = (int)$it['block_id'];
    $zona      = substr(trim($it['zona'] ?? 'main'), 0, 40);
    $posicion  = (int)($it['posicion'] ?? 1);

    if($assign_id>0){
      $st=$conn->prepare("UPDATE landing_page_blocks SET zona=?, posicion=? WHERE id=? AND landing_id=?");
      $st->bind_param('siii', $zona, $posicion, $assign_id, $landing_id);
      $st->execute();
    }else{
      // crear nueva asignación
      $st=$conn->prepare("INSERT INTO landing_page_blocks (landing_id, block_id, zona, posicion) VALUES (?,?,?,?)");
      $st->bind_param('iisi', $landing_id, $block_id, $zona, $posicion);
      $st->execute();
      // clave aproximada para mapear chip -> asignación creada
      $map_ids[$block_id.'@'.$zona] = $conn->insert_id;
    }
  }

  $conn->commit();
  echo json_encode(['ok'=>true,'map_ids'=>$map_ids]);
}catch(Throwable $e){
  $conn->rollback();
  echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
}
