<?php 
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    ini_set('display_errors', 0);
    error_reporting(E_ALL);

    require_once __DIR__ . '/../core/api.php';

    $data = json_decode(file_get_contents('php://input'), true);

    if (empty($data['id'])) throw new Exception('ID REQUERIDO');
    $id = filter_var($data['id'], FILTER_VALIDATE_INT);
    if (!$id) throw new Exception('ID INVALIDO');

    $pdo->beginTransaction();

    $stmtGet = $pdo->prepare("SELECT external_id FROM invoices WHERE id = ?");
    $stmtGet->execute([$id]);
    $external_id = $stmtGet->fetchColumn();

    $pdo->prepare("DELETE FROM invoice_items WHERE invoice_id = ?")->execute([$id]);
    $stmtDel = $pdo->prepare("DELETE FROM invoices WHERE id = ?");
    $stmtDel->execute([$id]);

    if ($stmtDel->rowCount() > 0) {
        // Borrar registro financiero asociado (TRANSACTIONS)
        if ($external_id) {
            $desc_search = "Ingreso por factura pagada #" . $external_id;
            // Corregido a 'transactions'
            $pdo->prepare("DELETE FROM transactions WHERE description = ?")->execute([$desc_search]);
        }
        
        $pdo->commit();
        $response = ['success' => true, 'message' => 'FACTURA Y REGISTROS ASOCIADOS ELIMINADOS'];
    } else {
        $pdo->rollBack();
        $response['message'] = 'FACTURA NO ENCONTRADA';
    }

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    $response['message'] = $e->getMessage();
}

if (ob_get_level() > 0) ob_end_clean();
echo json_encode($response);
exit;
?>