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

try {
    require_once '../core/api.php';

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

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

    // Validaciones básicas
    if (empty($input['estimate_date']) || (!isset($input['client_id']) && !isset($input['lead_id']))) {
        throw new Exception('Faltan datos obligatorios (Fecha o Contacto)');
    }

    // 1. CALCULAR TOTALES
    $items = $input['items'] ?? [];
    $subtotal = 0;
    foreach ($items as $item) {
        $price = floatval($item[1]);
        $qty = intval($item[2]);
        $subtotal += ($price * $qty);
    }
    $tax_rate = floatval($input['tax_rate'] ?? 0);
    $total_amount = $subtotal + ($subtotal * ($tax_rate / 100));

    // 2. PREPARAR DATOS
    $client_id = !empty($input['client_id']) ? $input['client_id'] : null;
    $lead_id = !empty($input['lead_id']) ? $input['lead_id'] : null;
    $external_id = uniqid('est-');
    
    // ESTADO INICIAL: Generado (Borrador). 
    $status = 'generated'; 
    $status_seguimiento = null; 

    $pdo->beginTransaction();

    // 3. INSERTAR EN QUOTES (Usando tabla quotes)
    $sql = "INSERT INTO quotes (
        external_id, client_id, lead_id, estimate_date, 
        status, status_seguimiento, 
        tax_rate, subtotal, total_amount, created_at
    ) VALUES (
        ?, ?, ?, ?, 
        ?, ?, 
        ?, ?, ?, NOW()
    )";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $external_id, $client_id, $lead_id, $input['estimate_date'],
        $status, $status_seguimiento,
        $tax_rate, $subtotal, $total_amount
    ]);

    $estimate_id = $pdo->lastInsertId();

    // 4. INSERTAR ITEMS (Usando tabla quotes_items)
    if (!empty($items)) {
        $sql_items = "INSERT INTO quotes_items (quote_id, description, unit_price, quantity) VALUES (?, ?, ?, ?)";
        $stmt_items = $pdo->prepare($sql_items);
        foreach ($items as $item) {
            $stmt_items->execute([$estimate_id, $item[0], $item[1], $item[2]]);
        }
    }

    $pdo->commit();
    $response = ['success' => true, 'message' => 'ESTIMADO CREADO', 'external_id' => $external_id];

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

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