<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/format.php';
require_once '../../core/permissions.php';

require_login();
require_permission('module.crm');

header('Content-Type: application/json; charset=utf-8');

function q_ajax_col_exists(PDO $pdo, $table, $column)
{
    static $cache = array();
    $key = $table . '.' . $column;

    if (array_key_exists($key, $cache)) {
        return $cache[$key];
    }

    $stmt = $pdo->prepare("SHOW COLUMNS FROM `" . str_replace('`', '', $table) . "` LIKE ?");
    $stmt->execute(array($column));
    $cache[$key] = (bool)$stmt->fetch(PDO::FETCH_ASSOC);

    return $cache[$key];
}

function q_ajax_phone($phone)
{
    $phone = preg_replace('/[^0-9]/', '', (string)$phone);
    if ($phone === '') return '';
    if (strlen($phone) === 9) return '56' . $phone;
    if (strlen($phone) === 8) return '569' . $phone;
    return $phone;
}

function q_ajax_date($date)
{
    return $date ? date('d-m-Y', strtotime($date)) : '-';
}

function q_ajax_allowed_units()
{
    return array('unidad', 'mL', 'L', 'g', 'kg', 'pack', 'caja', 'servicio');
}

function q_ajax_clean_unit($unit)
{
    $unit = trim((string)$unit);
    return in_array($unit, q_ajax_allowed_units(), true) ? $unit : 'unidad';
}

function q_ajax_display_customer($row)
{
    if (!empty($row['legal_name'])) return $row['legal_name'];
    if (!empty($row['commercial_name'])) return $row['commercial_name'];
    return $row['customer_name'] ?? '';
}

function q_ajax_split_item($item)
{
    $name = (string)($item['name'] ?? '');
    $sku = '';

    if (preg_match('/\s*\(SKU:\s*([^)]+)\)\s*$/i', $name, $m)) {
        $sku = trim($m[1]);
        $name = preg_replace('/\s*\(SKU:\s*([^)]+)\)\s*$/i', '', $name);
    }

    if ($sku === '' && !empty($item['description'])) {
        if (preg_match('/SKU:\s*(.+)$/i', (string)$item['description'], $m)) {
            $sku = trim($m[1]);
        } else {
            $sku = trim((string)$item['description']);
        }
    }

    $item['display_name'] = trim($name);
    $item['sku'] = $sku;
    $item['unit'] = q_ajax_clean_unit($item['unit'] ?? 'unidad');
    return $item;
}

function q_ajax_load_quote(PDO $pdo, $id)
{
    $hasInvoiceIssueDate = q_ajax_col_exists($pdo, 'crm_quotes', 'invoice_issue_date');
    $hasInvoiceNumber = q_ajax_col_exists($pdo, 'crm_quotes', 'invoice_number');
    $hasPaymentDate = q_ajax_col_exists($pdo, 'crm_quotes', 'payment_date');
    $hasDeletedAt = q_ajax_col_exists($pdo, 'crm_quotes', 'deleted_at');
    $hasDeletedBy = q_ajax_col_exists($pdo, 'crm_quotes', 'deleted_by');
    $hasDeletedReason = q_ajax_col_exists($pdo, 'crm_quotes', 'deleted_reason');

    $stmt = $pdo->prepare("
        SELECT
            q.*,
            " . ($hasInvoiceIssueDate ? "q.invoice_issue_date" : "NULL AS invoice_issue_date") . ",
            " . ($hasInvoiceNumber ? "q.invoice_number" : "NULL AS invoice_number") . ",
            " . ($hasPaymentDate ? "q.payment_date" : "NULL AS payment_date") . ",
            c.customer_name,
            c.commercial_name,
            c.legal_name,
            c.customer_tax_id,
            c.email,
            c.phone,
            c.address,
            c.district,
            c.city,
            c.region,
            c.payment_terms,
            c.facto_payment_term,
            o.title AS opportunity_title,
            " . ($hasDeletedAt ? "q.deleted_at" : "NULL AS deleted_at") . ",
            " . ($hasDeletedBy ? "q.deleted_by" : "NULL AS deleted_by") . ",
            " . ($hasDeletedReason ? "q.deleted_reason" : "NULL AS deleted_reason") . "
        FROM crm_quotes q
        JOIN crm_customers c ON q.customer_id = c.id
        LEFT JOIN crm_opportunities o ON q.opportunity_id = o.id
        WHERE q.id = ?
          " . ($hasDeletedAt ? "AND q.deleted_at IS NULL" : "") . "
        LIMIT 1
    ");
    $stmt->execute(array($id));
    $quote = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$quote) {
        return null;
    }

    $stmtItems = $pdo->prepare("SELECT * FROM crm_quote_items WHERE quote_id = ? ORDER BY id ASC");
    $stmtItems->execute(array($id));

    $items = array();
    foreach ($stmtItems->fetchAll(PDO::FETCH_ASSOC) as $item) {
        $items[] = q_ajax_split_item($item);
    }

    return array(
        'id' => (int)$quote['id'],
        'opportunity_id' => (int)($quote['opportunity_id'] ?? 0),
        'customer_id' => (int)$quote['customer_id'],
        'quote_number' => $quote['quote_number'],
        'subtotal' => (float)$quote['subtotal'],
        'discount_percent' => (float)$quote['discount_percent'],
        'discount_amount' => (float)$quote['discount_amount'],
        'iva' => (float)$quote['iva'],
        'total' => (float)$quote['total'],
        'notes' => $quote['notes'] ?? '',
        'status' => $quote['status'],
        'invoice_issue_date' => q_ajax_date($quote['invoice_issue_date'] ?? null),
        'invoice_issue_date_raw' => $quote['invoice_issue_date'] ?? '',
        'invoice_number' => $quote['invoice_number'] ?? '',
        'payment_date' => q_ajax_date($quote['payment_date'] ?? null),
        'payment_date_raw' => $quote['payment_date'] ?? '',
        'created_at' => !empty($quote['created_at']) ? date('d-m-Y', strtotime($quote['created_at'])) : '-',
        'created_at_raw' => $quote['created_at'],
        'customer_name' => q_ajax_display_customer($quote),
        'customer_tax_id' => $quote['customer_tax_id'] ?? '',
        'email' => $quote['email'] ?? '',
        'phone' => $quote['phone'] ?? '',
        'whatsapp_phone' => q_ajax_phone($quote['phone'] ?? ''),
        'address' => $quote['address'] ?? '',
        'district' => $quote['district'] ?? '',
        'city' => $quote['city'] ?? '',
        'region' => $quote['region'] ?? '',
        'payment_terms' => icylab_normalize_payment_terms($quote['payment_terms'] ?? ($quote['facto_payment_term'] ?? 'contado')),
        'payment_terms_label' => icylab_payment_terms_label($quote['payment_terms'] ?? ($quote['facto_payment_term'] ?? 'contado')),
        'opportunity_title' => !empty($quote['opportunity_title']) ? $quote['opportunity_title'] : 'Venta directa',
        'deleted_at' => $quote['deleted_at'] ?? '',
        'deleted_by' => $quote['deleted_by'] ?? '',
        'deleted_reason' => $quote['deleted_reason'] ?? '',
        'is_deleted' => !empty($quote['deleted_at']),
        'items' => $items
    );
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    echo json_encode(array('success' => false, 'message' => 'ID inválido.'));
    exit;
}

try {
    $pdo = db();
    $quote = q_ajax_load_quote($pdo, $id);

    if (!$quote) {
        echo json_encode(array('success' => false, 'message' => 'Cotización no encontrada.'));
        exit;
    }

    echo json_encode(array('success' => true, 'quote' => $quote), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    echo json_encode(array('success' => false, 'message' => $e->getMessage()));
}
