<?php
/**
 * POST /api/iva/actualizar.php
 * Toggle IVA exemption for a product
 */
require_once '../../config/database.php';
require_once '../../includes/helpers.php';

require_post();
$data = json_input();

$id = $data['id'] ?? $data['id_producto'] ?? null;
$exentoIva = $data['exento_iva'] ?? null;

if ($id === null || $exentoIva === null) {
    json_error('Datos incompletos: id y exento_iva son requeridos', 400);
}

$pdo = getConnection();
$id = (int)$id;
$val = $exentoIva ? 1 : 0;

try {
    $pdo->beginTransaction();
    
    // 1. Update master product reference
    $stmt1 = $pdo->prepare("UPDATE productos SET exento_iva = ? WHERE id = ?");
    $stmt1->execute([$val, $id]);
    
    // 2. Synchronize all batches/locations for this product (ensure global consistency)
    $stmt2 = $pdo->prepare("UPDATE producto_lugares_compra SET exento_iva = ? WHERE producto_id = ?");
    $stmt2->execute([$val, $id]);
    
    $pdo->commit();
    json_success([], 'IVA actualizado globalmente');
} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    json_error('Error: ' . $e->getMessage());
}
