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

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(array('success' => false, 'message' => 'Método no permitido.'));
    exit;
}

$allowedStatuses = array('Borrador', 'Enviada', 'Aceptada', 'Rechazada', 'Vencida', 'Anulada');

function qs_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 qs_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 qs_date($date)
{
    return $date ? date('d-m-Y', strtotime($date)) : '-';
}

function qs_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 qs_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;
    return $item;
}

function qs_load_quote(PDO $pdo, $id)
{
    $hasInvoiceIssueDate = qs_col_exists($pdo, 'crm_quotes', 'invoice_issue_date');
    $hasInvoiceNumber = qs_col_exists($pdo, 'crm_quotes', 'invoice_number');
    $hasPaymentDate = qs_col_exists($pdo, 'crm_quotes', 'payment_date');
    $hasDeletedAt = qs_col_exists($pdo, 'crm_quotes', 'deleted_at');
    $hasDeletedBy = qs_col_exists($pdo, 'crm_quotes', 'deleted_by');
    $hasDeletedReason = qs_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,
            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[] = qs_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' => qs_date($quote['invoice_issue_date'] ?? null),
        'invoice_issue_date_raw' => $quote['invoice_issue_date'] ?? '',
        'invoice_number' => $quote['invoice_number'] ?? '',
        'payment_date' => qs_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' => qs_display_customer($quote),
        'customer_tax_id' => $quote['customer_tax_id'] ?? '',
        'email' => $quote['email'] ?? '',
        'phone' => $quote['phone'] ?? '',
        'whatsapp_phone' => qs_phone($quote['phone'] ?? ''),
        'address' => $quote['address'] ?? '',
        'district' => $quote['district'] ?? '',
        'city' => $quote['city'] ?? '',
        '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($_POST['id']) ? (int)$_POST['id'] : 0;
$status = trim($_POST['status'] ?? '');

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

if (!in_array($status, $allowedStatuses, true)) {
    echo json_encode(array('success' => false, 'message' => 'Estado inválido.'));
    exit;
}

try {
    $pdo = db();
    $lifecycle = new QuoteLifecycleService($pdo);

    $sessionUser = current_user();
    $ownerName = !empty($sessionUser['name']) ? $sessionUser['name'] : (!empty($sessionUser['email']) ? $sessionUser['email'] : 'Sistema');

    $result = $lifecycle->changeStatus($id, $status, array(
        'owner_name' => $ownerName,
        'record_activity' => true
    ));

    $quote = qs_load_quote($pdo, $id);

    echo json_encode(array(
        'success' => true,
        'message' => $result['status_changed'] ? 'Estado actualizado correctamente.' : 'Estado sin cambios.',
        'quote' => $quote,
        'lifecycle' => $result
    ), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

    echo json_encode(array('success' => false, 'message' => $e->getMessage()));
}
