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

try {
    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

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

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

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Error al decodificar JSON en invoice-create.php: " . json_last_error_msg());
        throw new Exception('ERROR AL PROCESAR DATOS');
    }

    if (empty($data['invoice_date']) || empty($data['client_id']) || !isset($data['items'])) {
        throw new Exception('DATOS INCOMPLETOS');
    }
    if (!is_array($data['items']) || empty($data['items'])) {
        throw new Exception('ITEMS REQUERIDOS');
    }

    $client_id = filter_var($data['client_id'], FILTER_VALIDATE_INT);
    if ($client_id === false) {
        throw new Exception('ID DE CLIENTE INVALIDO');
    }

    $invoice_date = filter_var($data['invoice_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $due_date = !empty($data['due_date']) ? filter_var($data['due_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $status_input = filter_var(trim($data['status']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    
    // Estados válidos para creación: sent, paid, cancelled, overdue
    $valid_statuses = ['sent', 'paid', 'cancelled', 'overdue'];
    
    $status = 'sent'; 
    if (!empty($data['id']) && in_array(strtolower($status_input), $valid_statuses)) {
        $status = strtolower($status_input);
    } elseif (empty($data['id'])) {
        $status = 'sent';
    }

    $tax_rate = filter_var($data['tax_rate'] ?? 0.00, FILTER_VALIDATE_FLOAT);
    $items = $data['items']; 

    $subtotal = 0;
    foreach ($items as $item) {
        if (!isset($item[0], $item[1], $item[2])) {
            throw new Exception('FORMATO DE ITEM INVALIDO');
        }
        $item_description = filter_var($item[0], FILTER_SANITIZE_FULL_SPECIAL_CHARS); 
        $item_price = filter_var($item[1], FILTER_VALIDATE_FLOAT);
        $item_quantity = filter_var($item[2], FILTER_VALIDATE_INT);
        if ($item_price === false || $item_quantity === false || $item_quantity <= 0) {
            throw new Exception('PRECIO O CANTIDAD INVALIDA');
        }
        $subtotal += ($item_price * $item_quantity);
    }
    $total_amount = $subtotal + ($subtotal * ($tax_rate / 100));

    $pdo->beginTransaction();

    $external_id = 'fac-' . uniqid();
    $user_id = $_SESSION['user_id'] ?? 1;

    $stmt = $pdo->prepare(
        "INSERT INTO invoices (user_id, external_id, client_id, invoice_date, due_date, status, tax_rate, subtotal, total_amount)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->execute([
        $user_id,
        $external_id,
        $client_id,
        $invoice_date,
        $due_date,
        $status,
        $tax_rate,
        $subtotal,
        $total_amount
    ]);

    $invoice_id = $pdo->lastInsertId();

    $stmt_items = $pdo->prepare(
        "INSERT INTO invoice_items (invoice_id, description, unit_price, quantity)
         VALUES (?, ?, ?, ?)"
    );
    foreach ($items as $item) {
        $item_description = filter_var($item[0], FILTER_SANITIZE_FULL_SPECIAL_CHARS); 
        $item_price = filter_var($item[1], FILTER_VALIDATE_FLOAT);
        $item_quantity = filter_var($item[2], FILTER_VALIDATE_INT);

        $stmt_items->execute([
            $invoice_id,
            $item_description,
            $item_price,
            $item_quantity
        ]);
    }

    $pdo->commit();

    $response = [
        'success' => true,
        'message' => 'FACTURA CREADA',
        'id' => $invoice_id,
        'external_id' => $external_id
    ];

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("PDO Error en invoice-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => 'ERROR DE BASE DE DATOS'];
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("General Error en invoice-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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