<?php
// views/pages/raspadita/api/entrega_delete.php
// ✅ Revertir entrega real (BD)
// POST JSON: { "id": 123 }  (id de tbr_raspadita)

declare(strict_types=1);

session_start();
date_default_timezone_set('America/Guayaquil');

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'OPTIONS') { http_response_code(204); exit; }
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
  http_response_code(405);
  echo json_encode(['success'=>false,'message'=>'Use POST'], JSON_UNESCAPED_UNICODE);
  exit;
}

function jexit(array $p, int $c=200): void {
  http_response_code($c);
  echo json_encode($p, JSON_UNESCAPED_UNICODE);
  exit;
}
function read_json(): array {
  $raw = file_get_contents('php://input');
  $j = $raw ? json_decode($raw, true) : [];
  return is_array($j) ? $j : [];
}

if (!isset($_SESSION['idusuario'])) jexit(['success'=>false,'message'=>'Sesión no iniciada'], 401);
$id_usuario = (int)$_SESSION['idusuario'];

$in = read_json();
$id = (int)($in['id'] ?? 0);
if ($id <= 0) jexit(['success'=>false,'message'=>'ID inválido'], 400);

require_once __DIR__ . '/../../conex.php';
$db = $conn ?? ($conex ?? null);
if (!$db instanceof mysqli) jexit(['success'=>false,'message'=>'Sin conexión BD'], 500);
mysqli_set_charset($db, 'utf8mb4');
@mysqli_query($db, "SET time_zone='-05:00'");

try {
  $db->begin_transaction();

  // Solo permite revertir si pertenece al usuario, no anulado, estado=2
  $sql = "UPDATE tbr_raspadita
          SET id_canillita = NULL,
              estado = 1
          WHERE id = ?
            AND id_usuario = ?
            AND anulado = 0
            AND estado = 2
          LIMIT 1";
  $st = $db->prepare($sql);
  if (!$st) throw new RuntimeException($db->error);

  $st->bind_param('ii', $id, $id_usuario);
  $st->execute();
  $aff = $st->affected_rows;
  $st->close();

  if ($aff !== 1) {
    $db->rollback();
    jexit(['success'=>false,'message'=>'No se pudo revertir (no cumple condiciones).'], 409);
  }

  $db->commit();
  jexit(['success'=>true,'message'=>'✅ Entrega revertida.'], 200);

} catch (Throwable $e) {
  try { $db->rollback(); } catch (Throwable $x) {}
  jexit(['success'=>false,'message'=>'Error interno','detail'=>$e->getMessage()], 500);
}
