<?php
ob_start();

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

$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

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

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

    if (empty($data['quote_id'])) {
        throw new Exception('ID REQUERIDO');
    }

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

    $pdo->beginTransaction();

    $stmt = $pdo->prepare("SELECT * FROM estimates WHERE id = ? FOR UPDATE"); 
    $stmt->execute([$estimate_id]);
    $estimate = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$estimate) {
        throw new Exception('ESTIMADO NO ENCONTRADO');
    }

    if (!is_null($estimate['converted_to_invoice_id'])) {
        throw new Exception('YA CONVERTIDO A FACTURA');
    }

    if (is_null($estimate['client_id'])) {
        throw new Exception('CONVERSION SOLO PARA CLIENTES');
    }

    $stmt_items = $pdo->prepare("SELECT * FROM estimate_items WHERE estimate_id = ?");
    $stmt_items->execute([$estimate_id]);
    $items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

    $external_id = 'inv-' . uniqid(); 
    $invoice_date = date('Y-m-d');
    $status = 'generada'; 

    $stmt_insert_invoice = $pdo->prepare(
        "INSERT INTO invoices (external_id, client_id, invoice_date, status, tax_rate, subtotal, total_amount, converted_from_estimate_id)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt_insert_invoice->execute([
        $external_id,
        (int)$estimate['client_id'], 
        $invoice_date,
        $status,
        (float)$estimate['tax_rate'], 
        (float)$estimate['subtotal'],
        (float)$estimate['total_amount'],
        $estimate_id
    ]);

    $new_invoice_id = $pdo->lastInsertId();

    if (!empty($items)) {
        $stmt_insert_item = $pdo->prepare(
            "INSERT INTO invoice_items (invoice_id, description, unit_price, quantity) VALUES (?, ?, ?, ?)"
        );
        foreach ($items as $item) {
            $description = filter_var($item['description'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
            $unit_price = filter_var($item['unit_price'], FILTER_VALIDATE_FLOAT);
            $quantity = filter_var($item['quantity'], FILTER_VALIDATE_INT);

            if ($unit_price === false || $quantity === false || $quantity <= 0) {
                throw new Exception('ITEM INVALIDO');
            }

            $stmt_insert_item->execute([
                $new_invoice_id,
                $description,
                $unit_price,
                $quantity
            ]);
        }
    } 

    $stmt_update_estimate = $pdo->prepare(
        "UPDATE estimates SET status = 'convertida', converted_to_invoice_id = ? WHERE id = ?"
    );
    $stmt_update_estimate->execute([$new_invoice_id, $estimate_id]);

    $pdo->commit();

    $response = [
        'success' => true,
        'message' => 'FACTURA CREADA',
        'new_invoice_id' => $new_invoice_id
    ];

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Error PDO en convert-quote-to-invoice.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Error general en convert-quote-to-invoice.php: " . $e->getMessage());
    $response['message'] = 'ERROR INESPERADO: ' . strtoupper($e->getMessage());
}

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