<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../core/api.php';
global $pdo;

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Sesión expirada']);
    exit;
}

$user_id = $_SESSION['user_id'];

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

try {
    $client_id = $input['client_id'] ?? 0;
    $items = $input['items'] ?? [];
    $token = bin2hex(random_bytes(16)); 

    if (empty($client_id) || empty($items)) {
        throw new Exception("Debe seleccionar un cliente y agregar al menos un ítem.");
    }

    $subtotal = 0;
    foreach ($items as $item) {
        $qty = floatval($item['quantity'] ?? 1);
        $price = floatval($item['price'] ?? 0);
        if ($qty <= 0 || $price < 0) {
             throw new Exception("Cantidad o precio de ítem inválido.");
        }
        $subtotal += ($qty * $price);
    }
    
    if ($subtotal <= 0) {
         throw new Exception("El estimado no puede ser cero o negativo.");
    }

    $pdo->beginTransaction();

    $stmt = $pdo->prepare("INSERT INTO quotes 
        (user_id, client_id, estimate_date, status, external_id, subtotal, tax_rate, total_amount, created_at) 
        VALUES (?, ?, CURDATE(), 'sent', ?, ?, 0, ?, NOW())");
    $stmt->execute([$user_id, $client_id, $token, $subtotal, $subtotal]);
    $doc_id = $pdo->lastInsertId();

    $stmtItem = $pdo->prepare("
        INSERT INTO quotes_items (quote_id, description, quantity, unit_price) 
        VALUES (?, ?, ?, ?)
    ");

    foreach ($items as $item) {
        $qty = floatval($item['quantity'] ?? 1);
        $price = floatval($item['price'] ?? 0);
        $description = $item['description'] ?? 'Concepto';
        
        $stmtItem->execute([$doc_id, $description, $qty, $price]);
    }

    $pdo->commit();

    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? ''; 

    if (empty($host)) {
        throw new Exception("No se pudo determinar el dominio del servidor (HTTP_HOST).");
    }
    
    $full_link = "$protocol://$host/quote-view.php?token=" . $token;

    $wa_text = "Hello! Your new Estimate (#{$doc_id}) is ready for review. Total amount: $" . number_format($subtotal, 2) . ". Please click the link to view the details: " . $full_link;
    
    echo json_encode([
        'success' => true, 
        'link' => $full_link,
        'wa_text' => $wa_text
    ]);

} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
    http_response_code(400);
    error_log("Error Quick Create Estimado: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error al crear estimado: ' . $e->getMessage()]);
}
?>