<?php
// api/modelo_toggle.php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

session_start();
require_once __DIR__ . '/../conex.php';
mysqli_set_charset($conn,'utf8mb4');

$in = json_decode(file_get_contents('php://input'), true);
$id = (int)($in['id_modelo'] ?? 0);
if ($id <= 0) { echo json_encode(['success'=>false,'message'=>'ID inválido']); exit; }

$sql = "UPDATE tb_inv_modelo SET condicion = 1 - IFNULL(condicion,0) WHERE id_modelo=?";
$stmt = mysqli_prepare($conn,$sql);
mysqli_stmt_bind_param($stmt,'i',$id);
$ok = mysqli_stmt_execute($stmt);

if (!$ok) { echo json_encode(['success'=>false,'message'=>'No se pudo cambiar estado']); exit; }
if (mysqli_affected_rows($conn) === 0) { echo json_encode(['success'=>false,'message'=>'No se encontró el registro']); exit; }

$sel = mysqli_prepare($conn,"SELECT id_modelo, IFNULL(condicion,0) AS condicion FROM tb_inv_modelo WHERE id_modelo=?");
mysqli_stmt_bind_param($sel,'i',$id);
mysqli_stmt_execute($sel);
$res = mysqli_stmt_get_result($sel);
$row = mysqli_fetch_assoc($res);

echo json_encode(['success'=>true,'message'=>'Estado actualizado','data'=>$row]);
