<?php
include '../conexion.php';

// Verificar que la solicitud sea POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método no permitido.']);
    exit();
}

// Validar el ID recibido
$id = isset($_POST['id']) ? trim($_POST['id']) : null;
if (!is_numeric($id) || $id <= 0) {
    echo json_encode(['success' => false, 'message' => 'ID inválido.']);
    exit();
}

if ($connection->connect_error) {
    echo json_encode(['success' => false, 'message' => 'Error al conectar a la base de datos.']);
    exit();
}

// Iniciar transacción
$connection->begin_transaction();

try {
    
    // obtener sucursal
    $query = "
        SELECT sucursal
        from datos_facturas
        WHERE uni_movimientos_idmovimientosUni = ?
    ";

    $stmt = $connection->prepare($query);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

    $suc =null;;
    while ($row = $result->fetch_assoc()) {
        $suc = $row['sucursal'];
    }
    $inv=null;
    if($suc=='1'){
        $inv="inv1";
    } else if($suc=='2'){
        $inv="inv2";
    }else if($suc=='3'){
        $inv="inv3";
    }

    $xx = 0;
    $response = ['success' => true];

    // Consultar los movimientos y calcular los totales
    $query = "
        SELECT d.uni_uniforme_iduniforme, d.cant, u.".$inv."
        FROM uni_detmovimiento d
        INNER JOIN uni_uniforme u ON d.uni_uniforme_iduniforme = u.iduniforme
        WHERE d.uni_movimientos_idmovimientosUni = ?
    ";

    $stmt = $connection->prepare($query);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

    $updates = [];
    while ($row = $result->fetch_assoc()) {
        $total = $row[$inv] - $row['cant'];
        if ($total < 0) {
            $xx++;
        }
        $updates[] = ['iduniforme' => $row['uni_uniforme_iduniforme'], 'total' => $total];
    }

    if ($xx > 0) {
        $connection->rollback();
        echo json_encode(['success' => false, 'message' => 'No puede haber inventario negativo.']);
        exit();
    }

    // Actualizar inventarios
    $updateStmt = $connection->prepare("UPDATE uni_uniforme SET ".$inv." = ? WHERE iduniforme = ?");
    foreach ($updates as $update) {
        $updateStmt->bind_param("ii", $update['total'], $update['iduniforme']);
        $updateStmt->execute();
    }

    // Eliminar movimientos
    $deleteStmt = $connection->prepare("DELETE FROM uni_detmovimiento WHERE uni_movimientos_idmovimientosUni = ?");
    $deleteStmt->bind_param("i", $id);
    $deleteStmt->execute();

    $deleteStmt = $connection->prepare("DELETE FROM uni_movimientos WHERE idmovimientosUni = ?");
    $deleteStmt->bind_param("i", $id);
    $deleteStmt->execute();

    // Confirmar transacción
    $connection->commit();

    echo json_encode(['success' => true, 'message' => 'Operación completada exitosamente.']);
} catch (Exception $e) {
    $connection->rollback();
    error_log("Error: " . $e->getMessage()); // Registrar error
    echo json_encode(['success' => false, 'message' => 'Ocurrió un error durante la operación.']);
} finally {
    $connection->close();
}
?>
