<?php 
ob_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../core/api.php';

$response = ['success' => false, 'message' => 'Error desconocido'];

try {
    $data = json_decode(file_get_contents('php://input'), true);
    
    if (empty($data['id']) || empty($data['client_id']) || empty($data['status']) || !isset($data['items'])) {
        throw new Exception('DATOS INCOMPLETOS');
    }
    if (!is_array($data['items'])) {
        throw new Exception('ITEMS REQUERIDOS');
    }

    $id = filter_var($data['id'], FILTER_VALIDATE_INT);
    if (!$id) throw new Exception('ID inv¨¢lido');

    $status = strtolower($data['status']);
    $valid_statuses = ['sent', 'paid', 'cancelled', 'overdue'];
    if (!in_array($status, $valid_statuses)) {
        throw new Exception('Estado de factura inv¨¢lido: ' . $data['status']);
    }

    // Rec¨¢lculo seguro del total
    $subtotal = 0;
    $items = $data['items'];
    foreach ($items as $item) {
        $price = filter_var($item[1], FILTER_VALIDATE_FLOAT);
        $qty = filter_var($item[2], FILTER_VALIDATE_INT);
        if ($price === false || $qty === false) continue; // Ignorar items inv¨¢lidos en rec¨¢lculo
        $subtotal += ($price * $qty);
    }
    $tax_rate = filter_var($data['tax_rate'] ?? 0, FILTER_VALIDATE_FLOAT);
    $total_amount = $subtotal + ($subtotal * ($tax_rate / 100));

    $pdo->beginTransaction();

    // Actualizar cabecera
    $stmt = $pdo->prepare("UPDATE invoices SET client_id=?, invoice_date=?, due_date=?, status=?, tax_rate=?, subtotal=?, total_amount=?, updated_at=NOW() WHERE id=?");
    $stmt->execute([
        $data['client_id'], 
        $data['invoice_date'], 
        $data['due_date'] ?? null, 
        $status, 
        $tax_rate, 
        $subtotal, 
        $total_amount, 
        $id
    ]);

    // Reemplazo at¨®mico de items
    $pdo->prepare("DELETE FROM invoice_items WHERE invoice_id = ?")->execute([$id]);
    
    if (!empty($items)) {
        $stmtInsert = $pdo->prepare("INSERT INTO invoice_items (invoice_id, description, unit_price, quantity) VALUES (?, ?, ?, ?)");
        foreach ($items as $item) {
            $stmtInsert->execute([$id, $item[0], $item[1], $item[2]]);
        }
    }

    // L¨®gica financiera: Si se actualiza el monto de una factura PAGADA, actualizar transactions
    if ($status === 'paid') {
        $extId = $pdo->query("SELECT external_id FROM invoices WHERE id = $id")->fetchColumn();
        $desc = "Ingreso por factura pagada #" . $extId;
        
        // Actualizar monto en transactions (Corregido de 'finances' a 'transactions')
        $stmtFin = $pdo->prepare("UPDATE transactions SET amount = ? WHERE description = ?");
        $stmtFin->execute([$total_amount, $desc]);
    }

    $pdo->commit();
    $response = ['success' => true, 'message' => 'Factura actualizada correctamente'];

} 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;
?>