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

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

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

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

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

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

    $client_id = isset($data['client_id']) ? filter_var($data['client_id'], FILTER_VALIDATE_INT) : null;
    $lead_id = !empty($data['lead_id']) ? filter_var(trim($data['lead_id']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    
    if ($client_id === false && $lead_id === false) { 
        throw new Exception('ID DE CONTACTO INVALIDO');
    }

    $estimate_date = filter_var($data['estimate_date'], FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $status = filter_var(trim($data['status']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    if (empty($data['id'])) { 
        $status = 'generado'; 
    }

    $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 = 'est-' . uniqid();

    $stmt = $pdo->prepare(
        "INSERT INTO estimates (external_id, client_id, lead_id, estimate_date, status, tax_rate, subtotal, total_amount)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
    );
    $stmt->execute([
        $external_id,
        $client_id,
        $lead_id,
        $estimate_date,
        $status, 
        $tax_rate,
        $subtotal,
        $total_amount
    ]);

    $estimate_id = $pdo->lastInsertId();

    $stmt_items = $pdo->prepare(
        "INSERT INTO estimate_items (estimate_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([
            $estimate_id,
            $item_description,
            $item_price,
            $item_quantity
        ]);
    }

    $pdo->commit();

    $response = [
        'success' => true,
        'message' => 'ESTIMADO CREADO',
        'id' => (int)$estimate_id,
        'external_id' => $external_id
    ];

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    error_log("PDO Error en quote-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 quote-create.php: " . $e->getMessage());
    $response = ['success' => false, 'message' => strtoupper($e->getMessage())];
}

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