<?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 {
    require_once __DIR__ . '/../core/api.php';
    global $pdo;

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

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

    $quote_id = filter_var($data['quote_id'], FILTER_VALIDATE_INT);
    if (!$quote_id) {
        throw new Exception('ID INVÁLIDO');
    }

    // INICIO TRANSACCIÓN
    $pdo->beginTransaction();

    // 1. Bloquear la fila de la cotización (Mapeado de 'estimates' a 'quotes')
    $stmt = $pdo->prepare("SELECT * FROM quotes WHERE id = ? FOR UPDATE");
    $stmt->execute([$quote_id]);
    $quote = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$quote) throw new Exception('COTIZACIÓN NO ENCONTRADA');
    if ($quote['converted_to_invoice_id']) throw new Exception('ESTA COTIZACIÓN YA FUE CONVERTIDA');
    if (!$quote['client_id']) throw new Exception('SOLO SE PUEDEN FACTURAR COTIZACIONES DE CLIENTES (NO PROSPECTOS)');

    // 2. Verificar existencia del cliente
    $stmtClient = $pdo->prepare("SELECT id FROM clients WHERE id = ?");
    $stmtClient->execute([$quote['client_id']]);
    if (!$stmtClient->fetch()) throw new Exception('EL CLIENTE ASOCIADO NO EXISTE');

    // 3. Obtener Items (Mapeado de 'estimate_items' a 'quotes_items')
    $stmt_items = $pdo->prepare("SELECT * FROM quotes_items WHERE quote_id = ?");
    $stmt_items->execute([$quote_id]);
    $items = $stmt_items->fetchAll(PDO::FETCH_ASSOC);

    if (empty($items)) throw new Exception('LA COTIZACIÓN NO TIENE ÍTEMS');

    // 4. Crear Factura
    $external_id = 'inv-' . bin2hex(random_bytes(8)); 
    $invoice_date = date('Y-m-d');
    $status = 'enviado'; // Usamos 'enviado' o 'pendiente' de acuerdo a ENUMS

    $stmt_inv = $pdo->prepare("
        INSERT INTO invoices (
            external_id, client_id, invoice_date, status, 
            tax_rate, subtotal, total_amount, converted_from_quote_id, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    // Mapeado de 'converted_from_estimate_id' a 'converted_from_quote_id'
    $stmt_inv->execute([
        $external_id,
        $quote['client_id'],
        $invoice_date,
        $status,
        $quote['tax_rate'],
        $quote['subtotal'],
        $quote['total_amount'],
        $quote_id
    ]);
    
    $new_invoice_id = $pdo->lastInsertId();

    // 5. Copiar Items
    $stmt_insert_item = $pdo->prepare("
        INSERT INTO invoice_items (invoice_id, description, unit_price, quantity) 
        VALUES (?, ?, ?, ?)
    ");

    foreach ($items as $item) {
        $stmt_insert_item->execute([
            $new_invoice_id,
            $item['description'],
            $item['unit_price'],
            $item['quantity']
        ]);
    }

    // 6. Marcar cotización como convertida
    $stmt_update = $pdo->prepare("UPDATE quotes SET status = 'converted', converted_to_invoice_id = ? WHERE id = ?");
    $stmt_update->execute([$new_invoice_id, $quote_id]);

    $pdo->commit();

    $response = [
        'success' => true, 
        'message' => 'FACTURA GENERADA CORRECTAMENTE',
        'invoice_id' => $new_invoice_id
    ];

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log("Error convert-quote: " . $e->getMessage());
    $response['message'] = $e->getMessage();
}

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