<?php
ob_start();
require_once __DIR__ . '/../core/api.php';

ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);

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

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

    if (empty($data['id']) || empty($data['status'])) {
        throw new Exception('Faltan datos requeridos (ID o Estado).');
    }

    $invoice_id = filter_var($data['id'], FILTER_VALIDATE_INT);
    $new_status = filter_var(trim($data['status']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    
    if (!$invoice_id) throw new Exception('ID de factura inv¨˘lido.');

    $allowed_statuses = ['sent', 'paid', 'cancelled', 'overdue'];
    if (!in_array(strtolower($new_status), $allowed_statuses)) {
        throw new Exception("Estado no permitido: $new_status");
    }
    $new_status_db = strtolower($new_status);

    $pdo->beginTransaction();

    $stmtInfo = $pdo->prepare("SELECT id, external_id, client_id, total_amount, status FROM invoices WHERE id = ? FOR UPDATE");
    $stmtInfo->execute([$invoice_id]);
    $invoice = $stmtInfo->fetch(PDO::FETCH_ASSOC);

    if (!$invoice) throw new Exception('Factura no encontrada.');

    $stmtUpdate = $pdo->prepare("UPDATE invoices SET status = ?, updated_at = NOW() WHERE id = ?");
    $stmtUpdate->execute([$new_status_db, $invoice_id]);

    // L¨®gica Financiera: Corregido a 'transactions' y 'income'
    if ($new_status_db === 'paid') {
        $desc_search = "Ingreso por factura pagada #" . $invoice['external_id'];
        
        $stmtCheck = $pdo->prepare("SELECT id FROM transactions WHERE description = ? AND client_id = ? LIMIT 1");
        $stmtCheck->execute([$desc_search, $invoice['client_id']]);
        
        if (!$stmtCheck->fetch()) {
            $stmtFin = $pdo->prepare("INSERT INTO transactions (transaction_type, description, amount, transaction_date, client_id, created_at) VALUES ('income', ?, ?, CURDATE(), ?, NOW())");
            $stmtFin->execute([
                $desc_search,
                $invoice['total_amount'],
                $invoice['client_id']
            ]);
        }
    } 

    $pdo->commit();
    $response = ['success' => true, 'message' => 'Estado actualizado correctamente.'];

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

ob_end_clean();
header('Content-Type: application/json');
echo json_encode($response);
exit;
?>