<?php
// === CORRECCIÓN: INICIO DE SESIÓN EXPLÍCITO ===
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
    require_once(__DIR__ . '/db/db_connection.php');
    require_once(__DIR__ . '/core/business-information.php');
    include_once(__DIR__ . '/core/branding.php');
    include_once(__DIR__ . '/files/timezone.php');

// 1. Inicializar sesión
$user_id = $_SESSION['user_id'] ?? null;

// Redirigir al login si no hay user_id
if (!$user_id) {
    header("Location: app.php");
    exit();
}

// 4. Inicialización (Tu lógica de inicialización ORIGINAL)
$staffMembers = [];
$todayAppointments = [];
$pendingAppointments = [];
$leads = [];
$services = [];
$complaints = [];
$reviews = [];
$pendingInvoices = []; // Incluida en la inicialización
    
try {
    // A. STAFF
    $stmtStaff = $pdo->prepare("
        SELECT s.*, 
                (SELECT clock_in FROM work_logs WHERE staff_id = s.id AND clock_out IS NULL ORDER BY clock_in DESC LIMIT 1) as current_session,
                (SELECT COALESCE(c.first_name, l.first_name) 
                FROM unique_appointments ua
                LEFT JOIN clients c ON ua.client_id = c.id
                LEFT JOIN leads l ON ua.lead_id = l.id
                WHERE ua.staff_id = s.id 
                AND ua.status = 'confirmed'
                AND ua.appointment_date = CURDATE()
                AND ua.appointment_time <= CURTIME() 
                AND ADDTIME(ua.appointment_time, '01:30:00') >= CURTIME()
                LIMIT 1
                ) as current_client_name
        FROM staff s 
        WHERE s.user_id = ? AND s.status='activo' 
        ORDER BY s.first_name ASC
    ");
    $stmtStaff->execute([$user_id]);
    $staffMembers = $stmtStaff->fetchAll(PDO::FETCH_ASSOC);

    // B. AGENDA DEL DÍA
    $stmtToday = $pdo->prepare("
        SELECT ua.*, 
                COALESCE(CONCAT(c.first_name, ' ', c.last_name), CONCAT(l.first_name, ' ', l.last_name), 'Cliente Desconocido') as display_name,
                COALESCE(c.street_address, l.street_address, 'Dirección no disponible') as display_address,
                s.name as service_name, 
                st.first_name as staff_name
        FROM unique_appointments ua 
        LEFT JOIN clients c ON ua.client_id = c.id 
        LEFT JOIN leads l ON ua.lead_id = l.id
        LEFT JOIN services s ON ua.service_id = s.id
        LEFT JOIN staff st ON ua.staff_id = st.id
        WHERE ua.user_id = ? 
        AND ua.status IN ('confirmed', 'completed') 
        AND ua.appointment_date = CURDATE()
        ORDER BY ua.appointment_time ASC
    ");
    $stmtToday->execute([$user_id]);
    $todayAppointments = $stmtToday->fetchAll(PDO::FETCH_ASSOC);

    // C. SOLICITUDES DE CITAS
    $stmtPending = $pdo->prepare("
        SELECT ua.*, 
                COALESCE(CONCAT(c.first_name, ' ', c.last_name), CONCAT(l.first_name, ' ', l.last_name), 'Solicitante Desconocido') as display_name,
                COALESCE(c.email, l.email, 'Sin Email') as display_email,
                COALESCE(c.phone, l.phone, 'Sin Teléfono') as display_phone,
                COALESCE(c.street_address, l.street_address, '') as display_address,
                COALESCE(c.city, l.city, '') as display_city,
                s.name as service_name 
        FROM unique_appointments ua 
        LEFT JOIN clients c ON ua.client_id = c.id 
        LEFT JOIN leads l ON ua.lead_id = l.id
        LEFT JOIN services s ON ua.service_id = s.id
        WHERE ua.user_id = ? AND ua.status = 'pending' 
        ORDER BY ua.created_at DESC
    ");
    $stmtPending->execute([$user_id]);
    $pendingAppointments = $stmtPending->fetchAll(PDO::FETCH_ASSOC);

    // D. LEADS 
    $stmtLeads = $pdo->prepare("
        SELECT * FROM leads 
        WHERE user_id = ? 
        AND status NOT IN ('Contactado', 'Convertido', 'Lead Archivado') 
        ORDER BY FIELD(status, 'Entrante', 'Nuevo'), created_at DESC 
        LIMIT 30
    ");
    $stmtLeads->execute([$user_id]);
    $leads = $stmtLeads->fetchAll(PDO::FETCH_ASSOC);

    // E. SERVICIOS
    $stmtServices = $pdo->prepare("SELECT * FROM services WHERE user_id = ? ORDER BY name ASC");
    $stmtServices->execute([$user_id]);
    $services = $stmtServices->fetchAll(PDO::FETCH_ASSOC);

    // F. QUEJAS
    $stmtComplaints = $pdo->prepare("
        SELECT cp.*, c.first_name, c.last_name 
        FROM complaints cp 
        LEFT JOIN clients c ON cp.client_id = c.id 
        WHERE cp.user_id = ? AND cp.status NOT IN ('Archivado', 'Resuelto')
        ORDER BY cp.created_at DESC
    ");
    $stmtComplaints->execute([$user_id]);
    $complaints = $stmtComplaints->fetchAll(PDO::FETCH_ASSOC);

    // G. RESEÑAS
    try {
        $stmtReviews = $pdo->prepare("
            SELECT r.review_name, r.review_rating, r.review_text, r.created_at, sp.source
            FROM cms_reviews r
            JOIN cms_social_proof sp ON r.social_proof_id = sp.id
            WHERE sp.user_id = ?
            ORDER BY r.id DESC LIMIT 6
        ");
        $stmtReviews->execute([$user_id]);
        $reviews = $stmtReviews->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        // Silenciar
    }

    // --- H. FACTURAS POR COBRAR (NUEVO) ---
    try {
        $stmtInvoices = $pdo->prepare("
            SELECT id, external_id, total_amount, invoice_date, due_date, status, 
                    COALESCE(c.first_name, l.first_name) as client_name
            FROM invoices i
            LEFT JOIN clients c ON i.client_id = c.id
            LEFT JOIN leads l ON i.lead_id = l.id
            WHERE i.user_id = ? 
            AND i.status NOT IN ('pagada', 'paid', 'cancelled', 'anulada')
            ORDER BY i.due_date ASC
            LIMIT 20
        ");
        $stmtInvoices->execute([$user_id]);
        $pendingInvoices = $stmtInvoices->fetchAll(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        error_log("Error Facturas Pendientes: " . $e->getMessage());
    }

} catch (PDOException $e) {
    error_log("Error Base de Datos Dashboard: " . $e->getMessage());
    // Mantendremos el die() original si ocurre un error de DB con un usuario autenticado.
    die("Ha ocurrido un error cargando el panel de control.");
}
?>


<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="csrf-token" content="<?php echo htmlspecialchars($_SESSION['csrf_token'] ?? ''); ?>">
    
    <title>Live Ops Center <?php echo htmlspecialchars($client_info['business_name'] ?? 'FlowCRM'); ?> <?php echo htmlspecialchars($branding['full_title'] ?? ''); ?></title>
    <meta name="robots" content="noindex, nofollow">
    <link rel="manifest" href="manifest.php">
    
    <link rel="icon" type="image/png" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    <link rel="apple-touch-icon" href="<?php echo htmlspecialchars($branding['favicon'] ?? '/core/img/favicon.png'); ?>">
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($google_font_url ?? ''); ?>">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <link rel="stylesheet" href="style.css">

    <link rel="manifest" href="manifest.php">
    <meta name="theme-color" content="#ef4444">
    <meta name="apple-mobile-web-app-capable" content="yes">

    <style>
        /* Touch improvements */
        * { -webkit-tap-highlight-color: transparent; }
        body { touch-action: manipulation; }

         .tab-content { display: none; }
        .tab-content.active { display: block; }
        .tab-btn.active { border-bottom-color: var(--color-highlight); color: var(--color-primary); }
        
        .live-indicator {
            width: 12px;
            height: 12px;
            background: var(--color-success);
            border-radius: 50%;
            animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: .5; }
        }
        
        @keyframes slide-in {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .animate-slide-in { animation: slide-in 0.3s ease-out; }
        
        .custom-scrollbar::-webkit-scrollbar { width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: #f1f1f1; border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #888; border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: #555; }
        
        /* INICIO DE ESTILOS FBI (Replicados del primer archivo) */
    #search-modal {
        position: fixed;
        inset: 0; /* Ocupa toda la pantalla */
        background: rgba(var(--color-primary-rgb, 20, 20, 20), 0.95); /* Fondo oscuro semitransparente con color primario */
        z-index: 60;
        display: flex;
        align-items: center; /* Centra verticalmente */
        justify-content: center; /* Centra horizontalmente */
        backdrop-filter: blur(8px);
    }
    #search-modal-content-wrapper {
        background-color: white;
        width: 90%;
        max-width: 6xl; /* Más ancho para mostrar mejor los resultados */
        border-radius: 1.5rem;
        box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5);
        padding: 2.5rem;
        max-height: 95vh;
        display: flex;
        flex-direction: column;
        animation: slide-in 0.3s ease-out;
    }
    
    /* Estilos FBI (ya deben estar) */
    .fbi-overlay {
        position: fixed; inset: 0; 
        background: var(--color-primary); 
        z-index: 9999;
        display: flex; flex-direction: column; align-items: center; justify-content: center;
    }
    .radar {
        width: 100%; height: 100%;
        border: 2px solid rgba(158,20,40,0.2);
        border-top: 4px solid var(--color-secondary);
        border-radius: 50%;
        animation: spin 1s linear infinite;
        box-shadow: 0 0 15px rgba(158,20,40,0.5);
        position: absolute;
        top: 0; left: 0;
    }
    .logo-center {
        position: absolute;
        top: 50%; left: 50%;
        transform: translate(-50%, -50%);
        width: 70%;
        height: 70%;
        border-radius: 50%;
        background-color: white;
        padding: 5px;
        object-fit: contain;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
    .blink { animation: blinker 1s linear infinite; }
    @keyframes blinker { 50% { opacity: 0; } }

    #results-dropdown-modal {
        position: absolute; width: 100%; bg: white; z-index: 50;
        max-height: 300px; overflow-y: auto; border: 1px solid #e2e8f0;
        border-radius: 0.5rem; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.1);
        top: calc(100% + 4px); /* Posicionarlo debajo del input */
    }
    .result-item-modal:hover { background-color: #f1f5f9; cursor: pointer; }

    /* FIN DE ESTILOS FBI */
    </style>
</head>
<body class="flex flex-col bg-gray-50">

<audio id="notification-sound" src="core/notification.mp3"></audio>

<div class="hidden lg:flex fixed inset-0 z-[100] bg-[var(--color-primary)]/95 backdrop-blur-sm flex-col items-center justify-center p-8">
    
    <div class="bg-white max-w-5xl w-full rounded-3xl shadow-2xl overflow-hidden animate-slide-in flex h-[550px] border-4 border-[var(--color-highlight)]">
        
                <div class="w-1/2 bg-gray-900 flex items-center justify-center relative bg-cover bg-center" 
             style="background-image: url('https://www.free-mockup.com/wp-content/uploads/edd/2024/08/floating-iphone-app-screens-mockup.jpg?q=80&w=1974&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D');">
            
                        <div class="absolute inset-0 bg-black/30 flex items-center justify-center">
            </div>
        </div>

        <div class="w-1/2 p-10 flex flex-col items-center justify-center text-center">
            
            <h2 class="text-4xl font-black text-[var(--color-primary)] mb-2 uppercase tracking-tight">
                Acceso Exclusivo Móvil
            </h2>
            <p class="text-lg text-gray-600 mb-8 font-semibold">
                Esta es la experiencia de uso definitiva. Escanea y accede al Live Ops Center desde tu dispositivo móvil
            </p>
            
            <div class="bg-gray-50 p-6 rounded-2xl shadow-inner border border-gray-200 inline-block mb-6 relative">
                <img id="desktop-qr-code" src="" alt="QR Acceso Móvil" class="w-56 h-56 object-contain">
                <div class="absolute -bottom-3 -right-3 bg-[var(--color-secondary)] text-white p-2 rounded-full shadow-lg border-4 border-white">
                    <i data-lucide="scan-line" class="w-6 h-6"></i>
                </div>
            </div>
            
            <p class="text-md text-gray-400 font-mono break-all opacity-70" id="page-url-display"></p>
            
        </div>
        
    </div>
</div>

    <header class="bg-white shadow-sm sticky top-0 z-40 border-b-2 border-[var(--color-highlight)]">
        <div class="max-w-7xl mx-auto px-3 py-3 flex justify-between items-center">
            <div class="flex items-center gap-3">
                <?php if(!empty($client_info['logo_url'])): ?>
                    <img src="<?php echo htmlspecialchars($client_info['logo_url']); ?>" class="h-8 md:h-12 object-contain">
                <?php endif; ?>
                
                <div class="pl-3 border-l-2 border-gray-200">
                    <h1 class="text-lg md:text-3xl font-black text-[var(--color-primary)] uppercase tracking-tight leading-none">
                        Live OPS Center
                    </h1>
                    <div class="flex items-center gap-1.5 text-[10px] md:text-xs font-black text-[var(--color-secondary)] uppercase tracking-wider">
                        <div class="live-indicator"></div> <span class="sm:inline">Conexión </span>En Vivo
                    </div>
                </div>
            </div>
            
            <div class="flex items-center gap-2">
                <button onclick="openSearchModal()" 
                        class="bg-[var(--color-secondary)] active:bg-[var(--color-primary)] text-white border border-gray-200 px-3 py-2 rounded-full flex items-center gap-2 transition touch-manipulation">
                    <i data-lucide="search" class="w-5 h-5 text-white"></i> 
                    <span class="hidden md:inline font-bold uppercase text-sm">Buscar</span> 
                </button>
                
        </div>
        </div>
        
        <div class="bg-gray-800 border-t border-gray-700 overflow-x-auto tabs-container sticky top-[60px] z-30 shadow-sm">
            <div class="max-w-7xl mx-auto px-2">
                <nav class="flex flex-row justify-around w-full px-2 py-1" aria-label="Tabs">
                    
                    <button onclick="switchTab('empleados')" id="btn-empleados" 
                        class="tab-btn active w-1/4 py-3 border-b-4 
                                border-yellow-400 font-black text-xs 
                                text-white rounded-t-lg transition-all flex flex-col items-center 
                                gap-1 uppercase" 
                        style="color: white;"> 
                        <i data-lucide="users" class="w-6 h-6 mb-1 text-yellow-400"></i> Equipo
                    </button>
                    
                    <button onclick="switchTab('citas')" id="btn-citas" 
                        class="tab-btn w-1/4 py-3 border-b-4 border-transparent 
                                font-black text-xs text-white rounded-t-lg transition-all 
                                flex flex-col items-center gap-1 uppercase relative">
                        <i data-lucide="calendar" class="w-6 h-6 mb-1 text-yellow-400"></i> Citas
                        <?php if(count($pendingAppointments) > 0): ?>
                        <span class="absolute top-2 right-4 bg-red-500 text-white text-[10px] w-5 h-5 flex items-center justify-center rounded-full border-2 border-gray-800"><?php echo count($pendingAppointments); ?></span>
                        <?php endif; ?>
                    </button>
                    
                    <button onclick="switchTab('marketing')" id="btn-marketing" 
                        class="tab-btn w-1/4 py-3 border-b-4 border-transparent 
                                font-black text-xs text-white rounded-t-lg transition-all 
                                flex flex-col items-center gap-1 uppercase relative">
                        <i data-lucide="megaphone" class="w-6 h-6 mb-1 text-yellow-400"></i> Leads
                        <?php if(count($leads) > 0): ?>
                        <span class="absolute top-2 right-4 bg-red-500 text-white text-[10px] w-5 h-5 flex items-center justify-center rounded-full border-2 border-gray-800"><?php echo count($leads); ?></span>
                        <?php endif; ?>
                    </button>
                    
                    <button onclick="switchTab('clientes')" id="btn-clientes" 
                        class="tab-btn w-1/4 py-3 border-b-4 border-transparent 
                                font-black text-xs text-white rounded-t-lg transition-all 
                                flex flex-col items-center gap-1 uppercase relative">
                        <i data-lucide="briefcase" class="w-6 h-6 mb-1 text-yellow-400"></i> Clientes
                        <?php if(count($complaints) > 0): ?>
                        <span class="absolute top-2 right-4 bg-red-500 text-white text-[10px] w-5 h-5 flex items-center justify-center rounded-full border-2 border-gray-800"><?php echo count($complaints); ?></span>
                        <?php endif; ?>
                    </button>
                </nav>
            </div>
        </div>
    </header>

    <main class="flex-grow p-3 md:p-6 max-w-7xl mx-auto w-full">
        <div id="tab-empleados" class="tab-content active animate-slide-in">
            <div class="mb-6 text-center mt-2">
                <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                    <i data-lucide="users" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-4xl font-black text-gray-800"> EQUIPO DE TRABAJO</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">MONITOREO DE STAFF Y CLIENTES</p>
            </div>

            <div id="staff-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-20">
    <?php if(empty($staffMembers)): ?>
        <div class="col-span-full flex flex-col items-center justify-center py-12 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
            <svg class="w-12 h-12 mb-3 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
            <span class="font-bold text-lg uppercase">No hay personal activo</span>
        </div>
    <?php else: ?>
        <?php foreach($staffMembers as $staff): 
            $photo = !empty($staff['profile_photo_url']) ? $staff['profile_photo_url'] : 'core/img/Placeholder.webp';
            $isOnline = !empty($staff['current_session']);
            $currentClient = $staff['current_client_name'];
            // Colores dinámicos basados en el estado
            $ringColor = $isOnline ? 'ring-green-500' : 'ring-gray-300';
            $statusBg = $isOnline ? 'bg-green-50' : 'bg-gray-100';
            $statusBorder = $isOnline ? 'border-green-200' : 'border-gray-200';
        ?>
        
        <div class="group bg-white rounded-3xl p-5 shadow-[0_3px_10px_rgb(0,0,0,0.08)] hover:shadow-xl border border-gray-100 transition-all duration-300 transform hover:-translate-y-1 relative overflow-hidden">
            
            <div class="absolute top-0 left-0 w-full h-1.5 <?php echo $isOnline ? 'bg-gradient-to-r from-green-400 to-emerald-600' : 'bg-gray-200'; ?>"></div>

            <div class="flex items-start gap-4 mb-4 pt-2">
                <div class="relative flex-shrink-0">
                    <img src="<?php echo htmlspecialchars($photo); ?>" 
                         class="w-20 h-20 rounded-full object-cover border-4 border-white shadow-md ring-4 <?php echo $ringColor; ?> ring-offset-2">
                         
                    <?php if($isOnline): ?>
                        <div class="absolute bottom-1 right-1 bg-green-500 w-5 h-5 rounded-full border-2 border-white shadow-sm flex items-center justify-center">
                            <div class="w-2 h-2 bg-white rounded-full animate-pulse"></div>
                        </div>
                    <?php endif; ?>
                </div>

                <div class="flex-1 min-w-0 flex flex-col justify-center h-20">
                    <h2 class="text-xl font-black text-gray-800 uppercase leading-tight truncate group-hover:text-[var(--color-primary)] transition-colors">
                        <?php echo htmlspecialchars(($staff['first_name']??'') . ' ' . ($staff['last_name']??'')); ?>
                    </h2>
                    <p class="text-sm text-gray-500 font-bold uppercase tracking-wide mt-1 truncate">
                        <?php echo htmlspecialchars($staff['job_title'] ?? 'Staff'); ?>
                    </p>
                </div>
            </div>

            <div class="<?php echo $statusBg; ?> rounded-2xl p-4 border <?php echo $statusBorder; ?>">
                <?php if($isOnline): ?>
                    <div class="flex justify-between items-center mb-2 pb-2 border-b border-green-200/60">
                        <span class="flex items-center gap-2 text-lg font-black uppercase text-green-700">
                            <span class="w-2 h-2 rounded-full bg-green-500"></span>
                            Trabajando
                        </span>
                        <span class="text-sm font-bold text-green-800 font-black bg-white px-2 py-0.5 rounded-lg shadow-sm border border-green-100">
                            <?php echo date('H:i', strtotime($staff['current_session'])); ?>
                        </span>
                    </div>
                    
                    <?php if(!empty($currentClient)): ?>
                        <div class="mt-1">
                            <p class="text-xs text-green-600 font-bold uppercase mb-0.5">Atendiendo a:</p>
                            <p class="text-base font-black text-gray-800 uppercase truncate leading-tight">
                                <?php echo htmlspecialchars($currentClient); ?>
                            </p>
                        </div>
                    <?php else: ?>
                        <div class="flex items-center gap-2 mt-1">
                            <svg class="w-5 h-5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                            <p class="text-sm text-green-600 font-bold uppercase">Disponible para asignar</p>
                        </div>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="flex items-center justify-center gap-2 py-1 opacity-70">
                        <div class="w-2 h-2 rounded-full bg-gray-400"></div>
                        <p class="text-sm text-gray-500 font-bold uppercase">Fuera de Turno</p>
                    </div>
                <?php endif; ?>
            </div>
            
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
 </div>
</div>
        <div id="tab-citas" class="tab-content animate-slide-in">
            <div class="mb-8 text-center mt-2">
                <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                    <i data-lucide="calendar-check" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-4xl font-black text-gray-800"> AGENDA DE CITAS</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">CLIENTES QUE SE ATIENDEN HOY</p>
            </div>
                
            <?php if(empty($todayAppointments)): ?>
    <div class="col-span-full flex flex-col items-center justify-center py-10 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
        <svg class="w-12 h-12 mb-2 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
        <span class="font-bold text-lg uppercase text-gray-500">Sin citas programadas hoy</span>
    </div>
<?php else: ?>
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <?php foreach($todayAppointments as $appt): 
            $time = date('H:i', strtotime($appt['appointment_time']));
            // Opcional: Calcular AM/PM si lo prefieres, o dejar formato 24h
            $period = date('A', strtotime($appt['appointment_time'])); 
        ?>
        
        <div class="group bg-white rounded-3xl p-4 shadow-[0_3px_10px_rgb(0,0,0,0.08)] hover:shadow-xl border border-gray-100 transition-all duration-300 transform hover:-translate-y-1 relative overflow-hidden flex items-stretch gap-4">
            
            <div class="flex flex-col items-center justify-center bg-[var(--color-secondary)]/10 rounded-2xl w-20 flex-shrink-0 border border-[var(--color-secondary)]/20">
                <span class="text-xl font-black text-[var(--color-primary)] tracking-tighter">
                    <?php echo $time; ?>
                </span>
                <span class="text-[10px] font-bold text-[var(--color-secondary)] uppercase tracking-widest">
                    <?php echo $period; ?>
                </span>
            </div>

            <div class="flex-1 min-w-0 flex flex-col justify-center py-1">
                
                <h2 class="text-lg font-black text-[var(--color-primary)] uppercase truncate leading-tight mb-1 group-hover:text-[var(--color-secondary)] transition-colors">
                    <?php echo htmlspecialchars($appt['display_name'] ?? 'Cliente'); ?>
                </h2>

                <div class="mb-2">
                    <span class="inline-block px-2.5 py-1 rounded-lg bg-gray-100 text-xs font-bold text-gray-600 uppercase tracking-wide border border-gray-200 truncate max-w-full">
                        <?php echo htmlspecialchars($appt['service_name'] ?? 'Servicio General'); ?>
                    </span>
                </div>

                <div class="flex items-center gap-1.5 text-gray-500 mt-auto pt-2 border-t border-gray-50">
                    <div class="bg-gray-100 p-1 rounded-full">
                        <i data-lucide="user" class="w-3.5 h-3.5 text-gray-600"></i> 
                    </div>
                    <span class="text-sm font-semibold truncate text-gray-600">
                        <?php echo htmlspecialchars($appt['staff_name'] ?? 'Sin asignar'); ?>
                    </span>
                </div>
            </div>

            <div class="absolute right-0 top-4 bottom-4 w-1 bg-[var(--color-secondary)] rounded-l-full opacity-20"></div>

        </div>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

            <div class="mb-20">
                <div class="mb-8 mt-10 text-center border-t border-dashed border-gray-300 pt-6">
                     <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                         <i data-lucide="calendar-plus" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                         <h3 class="text-4xl font-black text-gray-800"> SOLICITUDES</h3>
                     </div>
                    <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">CITAS SOLICITADAS POR CLIENTES</p>
                    <?php if(count($pendingAppointments) > 0): ?>
                        <div class="mt-2"><span class="bg-[var(--color-secondary)] text-white text-xs font-black px-2.5 py-1 rounded-full animate-pulse"><?php echo count($pendingAppointments); ?> pendientes</span></div>
                    <?php endif; ?>
                </div>

                <div id="booking-requests-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
    <?php if(empty($pendingAppointments)): ?>
        <div class="col-span-full flex flex-col items-center justify-center py-10 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
            <svg class="w-12 h-12 mb-2 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
            <span class="font-bold text-lg uppercase text-gray-500">Todo al día. No hay solicitudes.</span>
        </div>
    <?php else: ?>
        <?php foreach($pendingAppointments as $req): 
            $fullAddress = trim(($req['display_address'] ?? '') . ' ' . ($req['display_city'] ?? ''));
            // Si no hay dirección, ponemos un texto por defecto
            $displayAddress = !empty($fullAddress) ? $fullAddress : 'Dirección no especificada';
            $mapLink = "https://www.google.com/maps/search/?api=1&query=" . urlencode($fullAddress);
        ?>
        
        <div class="bg-white rounded-3xl p-5 shadow-[0_3px_10px_rgb(0,0,0,0.08)] border border-gray-100 relative overflow-hidden flex flex-col h-full" id="card-appt-<?php echo $req['id']; ?>">
            
            <div class="absolute top-0 left-0 w-full h-1.5 bg-[var(--color-highlight)]"></div>

            <div class="flex justify-between items-start mb-4 pt-2">
                <div>
                    <h2 class="text-xl font-black text-[var(--color-primary)] uppercase leading-tight">
                        <?php echo htmlspecialchars($req['display_name'] ?? 'Cliente'); ?>
                    </h2>
                    <p class="text-sm text-gray-500 font-bold uppercase mt-1">
                        <?php echo htmlspecialchars($req['service_name'] ?? 'General'); ?>
                    </p>
                </div>
                <div class="flex flex-col items-center bg-gray-50 border border-gray-200 rounded-lg px-3 py-1.5">
                    <span class="text-xs font-bold text-red-500 uppercase"><?php echo date('M', strtotime($req['appointment_date'])); ?></span>
                    <span class="text-xl font-black text-gray-800 leading-none"><?php echo date('d', strtotime($req['appointment_date'])); ?></span>
                </div>
            </div>
            
            <div class="flex items-center gap-2 mb-4">
                <div class="bg-blue-50 text-blue-700 px-4 py-2 rounded-xl font-black text-lg border border-blue-100 flex items-center gap-2 w-full">
                    <i data-lucide="clock" class="w-5 h-5"></i>
                    <?php echo date('H:i', strtotime($req['appointment_time'])); ?> 
                    <span class="text-xs font-bold opacity-60 ml-auto uppercase">Hora solicitada</span>
                </div>
            </div>

            <div class="bg-gray-50 rounded-2xl p-3 border border-gray-200 mb-5 flex-1">
                <div class="flex items-start gap-3">
                    <div class="mt-1 bg-white p-1.5 rounded-full shadow-sm text-red-500 border border-gray-100">
                        <i data-lucide="map-pin" class="w-4 h-4"></i>
                    </div>
                    <div class="overflow-hidden">
                        <p class="text-xs font-bold text-gray-400 uppercase mb-0.5">Ubicación para validar:</p>
                        <p class="text-sm font-semibold text-gray-800 leading-snug break-words">
                            <?php echo htmlspecialchars($displayAddress); ?>
                        </p>
                        
                        <?php if(!empty($fullAddress)): ?>
                        <a href="<?php echo $mapLink; ?>" target="_blank" class="inline-flex items-center gap-1 text-xs font-bold text-blue-600 mt-2 hover:underline">
                            Ver en Google Maps 
                            <i data-lucide="external-link" class="w-3 h-3"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
                
                <?php if(!empty($req['display_phone'])): ?>
                <div class="mt-3 pt-3 border-t border-gray-200 flex items-center gap-2">
                    <i data-lucide="phone" class="w-3 h-3 text-gray-400"></i>
                    <a href="tel:<?php echo htmlspecialchars($req['display_phone']); ?>" class="text-xs font-bold text-gray-600 hover:text-[var(--color-primary)]">
                        <?php echo htmlspecialchars($req['display_phone']); ?>
                    </a>
                </div>
                <?php endif; ?>
            </div>

            <div class="grid grid-cols-2 gap-3 mt-auto">
                <button onclick="performAction('reject_appointment', <?php echo (int)$req['id']; ?>)" 
                        class="flex flex-col items-center justify-center py-3 px-4 rounded-xl border-2 border-red-50 bg-white text-red-500 hover:bg-red-50 active:scale-95 transition-all">
                    <span class="text-xs font-black uppercase">Rechazar</span>
                </button>
                
                <button onclick="performAction('approve_appointment', <?php echo (int)$req['id']; ?>)" 
                        class="flex flex-col items-center justify-center py-3 px-4 rounded-xl bg-[var(--color-primary)] text-white shadow-lg shadow-indigo-200 hover:brightness-110 active:scale-95 transition-all">
                    <span class="text-xs font-black uppercase tracking-wide">Aprobar Cita</span>
                </button>
            </div>
            
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
            </div>
        </div>
        <div id="tab-marketing" class="tab-content animate-slide-in">
            <div class="mb-8 mt-2 text-center">
                <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                    <i data-lucide="megaphone" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-4xl font-black text-gray-800"> PROSPECTOS</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">LEADS PARA SEGUIMIENTO</p>
                <div class="mt-2"><span class="bg-[var(--color-secondary)] text-white text-xs font-black px-3 py-1 rounded-full"><?php echo count($leads); ?> nuevos</span></div>
            </div>

            <div id="leads-requests-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
    <?php if(empty($leads)): ?>
        <div class="col-span-full flex flex-col items-center justify-center py-12 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
            <svg class="w-12 h-12 mb-3 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
            <span class="font-bold text-lg uppercase text-gray-500">Sin nuevos leads por gestionar</span>
        </div>
    <?php else: ?>
        <?php foreach($leads as $lead): 
            $status = $lead['status'] ?? 'Entrante';
            $isEntrante = ($status === 'Entrante');
            $fullName = trim(($lead['first_name']??'') . ' ' . ($lead['last_name']??''));
            $initials = substr($lead['first_name'] ?? 'L', 0, 1) . substr($lead['last_name'] ?? '', 0, 1);
            $cleanPhone = preg_replace('/[^0-9]/', '', $lead['phone'] ?? '');
            
            $sourceColor = match($lead['source'] ?? '') {
                'Facebook' => 'bg-[var(--color-primary)] text-white',
                'Instagram' => 'bg-[var(--color-primary)]  text-white',
                'Web' => 'bg-[var(--color-primary)]  text--white',
                default => 'bg-gray-100 text-gray-700'
            };
        ?>
        
        <div class="bg-white rounded-3xl p-5 shadow-[0_3px_10px_rgb(0,0,0,0.08)] hover:shadow-xl border border-gray-100 transition-all duration-300 relative overflow-hidden flex flex-col h-full" id="card-lead-<?php echo $lead['id']; ?>">
            
            <div class="absolute top-4 right-4">
                <span class="<?php echo $sourceColor; ?> text-[10px] px-2.5 py-1 rounded-full font-black uppercase tracking-wide border border-black/5">
                    <?php echo htmlspecialchars($lead['source'] ?? 'Desconocido'); ?>
                </span>
            </div>

            <div class="flex items-center gap-4 mb-4 pr-16"> <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-[var(--color-primary)] to-[var(--color-secondary)] flex items-center justify-center text-white shadow-md transform rotate-3">
                    <span class="text-xl font-black uppercase tracking-wider"><?php echo htmlspecialchars($initials); ?></span>
                </div>
                <div>
                    <h2 class="text-xl font-black text-gray-800 uppercase leading-none mb-1 truncate">
                        <?php echo htmlspecialchars($fullName); ?>
                    </h2>
                    <p class="text-xs text-gray-400 font-bold uppercase">Nuevo Prospecto</p>
                </div>
            </div>

            <div class="bg-gray-50 rounded-2xl p-3 border border-gray-200 mb-4">
                <div class="flex items-center gap-3 mb-2">
                    <div class="bg-white p-1.5 rounded-lg text-gray-400 shadow-sm">
                        <i data-lucide="phone" class="w-4 h-4"></i>
                    </div>
                    <span class="text-2xl font-black text-gray-700 tracking-wide">
                        <?php echo htmlspecialchars($lead['phone'] ?? 'Sin número'); ?>
                    </span>
                </div>
                <div class="flex gap-2 mt-2">
                    <a href="tel:<?php echo htmlspecialchars($lead['phone'] ?? ''); ?>" 
                       class="flex-1 bg-white hover:bg-gray-100 border border-gray-200 text-gray-700 py-2 rounded-xl flex items-center justify-center gap-2 text-xs font-bold uppercase transition-colors">
                        Llamar
                    </a>
                    <a href="https://wa.me/<?php echo htmlspecialchars($cleanPhone); ?>" target="_blank" 
                       class="flex-1 bg-green-500 hover:bg-green-600 border border-green-600 text-white py-2 rounded-xl flex items-center justify-center gap-2 text-xs font-bold uppercase shadow-sm transition-colors">
                        <i data-lucide="message-circle" class="w-4 h-4"></i> WhatsApp
                    </a>
                </div>
            </div>

            <div class="mt-auto grid grid-cols-[1fr_2fr] gap-3">
                <button onclick="performAction('dismiss_lead', <?php echo (int)$lead['id']; ?>)" 
                        class="bg-white border-2 border-gray-100 text-gray-400 hover:text-red-500 hover:border-red-100 hover:bg-red-50 py-3 rounded-xl text-xs font-black uppercase transition-all">
                    Ignorar
                </button>
                
                <?php if($isEntrante): ?>
                    <button onclick="performAction('approve_lead', <?php echo (int)$lead['id']; ?>)" 
                            class="bg-[var(--color-secondary)] hover:brightness-110 text-white py-3 rounded-xl text-xs font-black uppercase shadow-lg shadow-purple-200 active:scale-95 transition-all flex items-center justify-center gap-2">
                        <span>Aprobar Lead</span>
                        <i data-lucide="check" class="w-4 h-4"></i>
                    </button>
                <?php else: ?>
                    <button onclick="performAction('contact_lead', <?php echo (int)$lead['id']; ?>)" 
                            class="bg-[var(--color-primary)] hover:brightness-110 text-white py-3 rounded-xl text-xs font-black uppercase shadow-lg shadow-indigo-200 active:scale-95 transition-all flex items-center justify-center gap-2">
                        <span>Marcar Contactado</span>
                        <i data-lucide="user-check" class="w-4 h-4"></i>
                    </button>
                <?php endif; ?>
            </div>

        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

            <div class="border-t border-dashed border-gray-200 pt-8 mb-10">
    <div class="mb-6 px-1 text-center">
        <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
            <i data-lucide="file-text" class="w-8 h-8 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
            <h3 class="text-4xl lg:text-5xl font-black text-[var(--color-primary)] uppercase">Estimados</h3>
        </div>
        <p class="text-base uppercase font-bold text-gray-500 mt-1">
            CREACIÓN DE COTIZACIONES
        </p>
    </div>

    <div onclick="openDocModal('quote')" class="bg-white rounded-3xl p-5 border-l-8 border-[var(--color-primary)] shadow-xl flex items-center justify-between cursor-pointer hover:shadow-2xl active:scale-[0.99] transition-all duration-200 touch-manipulation">
        <div class="flex items-center gap-4">
            <div class="bg-blue-50 text-[var(--color-primary)] w-14 h-14 rounded-full flex items-center justify-center flex-shrink-0">
                <i data-lucide="plus" class="w-7 h-7 font-black"></i>
            </div>
            <div>
                <h3 class="text-xl font-black text-gray-800 uppercase leading-tight">
                    Crear Nuevo
                </h3>
                <p class="text-sm text-gray-500 font-semibold uppercase mt-1">
                    Generar y enviar link 
                </p>
            </div>
        </div>
        <i data-lucide="chevron-right" class="w-6 h-6 text-gray-400"></i>
    </div>
</div>

<div class="mt-8 mb-20">
    <div class="mb-6 px-1">
        <h3 class="text-2xl font-black text-gray-800 uppercase leading-tight border-b-2 border-dashed border-gray-200 pb-2">
            Historial de Cotizaciones
        </h3>
        <p class="text-sm text-gray-500 mt-1">Estimados Enviados: 
            <?php 
                echo isset($estimates) ? count($estimates) : '0'; 
            ?>
        </p>
    </div>

    <?php if(empty($estimates)): ?>
        <div class="flex flex-col items-center justify-center py-10 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
            <i data-lucide="mail-check" class="w-12 h-12 mb-3 opacity-50"></i>
            <span class="font-bold text-lg uppercase text-gray-500">No hay estimados recientes</span>
        </div>
    <?php else: ?>
        <div class="grid grid-cols-1 gap-4">
            <?php foreach($estimates as $est): 
                $statusSeguimiento = $est['status_seguimiento'] ?? 'Cotización Enviada';
                $statusText = $statusSeguimiento;
                $statusColor = 'border-gray-300 bg-gray-50/50';
                $statusTextColor = 'text-gray-600';

                if (str_contains($statusSeguimiento, 'Ganada')) {
                    $statusColor = 'border-green-400 bg-green-50/50';
                    $statusTextColor = 'text-green-800';
                } elseif (str_contains($statusSeguimiento, 'Perdida') || str_contains($statusSeguimiento, 'Descartado')) {
                    $statusColor = 'border-red-400 bg-red-50/50';
                    $statusTextColor = 'text-red-800';
                } elseif (str_contains($statusSeguimiento, 'Negociación')) {
                    $statusColor = 'border-blue-400 bg-blue-50/50';
                    $statusTextColor = 'text-blue-800';
                } elseif (str_contains($statusSeguimiento, 'Enviada')) {
                    $statusColor = 'border-yellow-400 bg-yellow-50/50';
                    $statusTextColor = 'text-yellow-800';
                }
            ?>
            
            <div onclick="openEstimate('<?php echo htmlspecialchars($est['external_id']); ?>')" 
                 class="bg-white rounded-3xl p-5 shadow-lg border-l-4 <?php echo $statusColor; ?> flex items-center justify-between cursor-pointer hover:shadow-xl active:scale-[0.99] transition-all duration-200">
                
                <div class="flex items-center gap-4 flex-1 min-w-0">
                    <div class="flex flex-col items-center justify-center flex-shrink-0">
                        <span class="text-sm font-black text-gray-400 leading-none">#</span>
                        <span class="text-lg font-black text-gray-800 leading-none">
                            <?php echo substr(htmlspecialchars($est['external_id'] ?? 'N/A'), 4); ?>
                        </span>
                    </div>

                    <div class="flex-1 min-w-0">
                        <h4 class="text-lg font-black text-[var(--color-primary)] uppercase truncate leading-tight">
                            <?php echo htmlspecialchars($est['client_name'] ?? $est['lead_name'] ?? 'Cliente Desconocido'); ?>
                        </h4>
                        <p class="text-sm font-bold text-gray-500 mt-1">
                            Monto Total: 
                            <span class="text-lg font-black text-green-600 ml-1">
                                $<?php echo number_format((float)($est['total_amount'] ?? 0), 2); ?>
                            </span>
                        </p>
                    </div>
                </div>
                
                <div class="text-right flex-shrink-0">
                    <span class="text-xs font-black uppercase px-2 py-0.5 rounded-full border-2 <?php echo $statusColor; ?> <?php echo $statusTextColor; ?>">
                        <?php echo htmlspecialchars($statusText); ?>
                    </span>
                    <p class="text-xs text-gray-400 font-semibold mt-2">
                        <?php echo date('d M Y', strtotime($est['estimate_date'] ?? 'now')); ?>
                    </p>
                </div>

            </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

<div class="border-t border-dashed border-gray-200 pt-8 mt-8 mb-20">
    <div class="mb-6 px-1 text-center">
        <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
            <i data-lucide="share-2" class="w-8 h-8 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
            <h3 class="text-4xl lg:text-5xl font-black text-[var(--color-primary)] uppercase">Servicios</h3>
        </div>
        <p class="text-base uppercase font-bold text-gray-500 mt-1">
            Servicios para compartir
        </p>
    </div>
    </div>

                <div id="services-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
    <?php if(empty($services)): ?>
        <div class="col-span-full flex flex-col items-center justify-center py-10 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
            <svg class="w-12 h-12 mb-2 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path></svg>
            <span class="font-bold text-lg uppercase text-gray-500">Lista de servicios vacía</span>
        </div>
    <?php else: ?>
        <?php foreach($services as $srv): 
            $msg = "Check out this service: " . ($srv['name']??'') . " - $" . ($srv['price']??'');
            $url = $srv['link'] ?? '#'; 
        ?>
        <div class="bg-white rounded-3xl p-5 shadow-[0_3px_10px_rgb(0,0,0,0.08)] hover:shadow-xl border border-gray-100 transition-all duration-300 flex flex-col h-full relative overflow-hidden group">
            
            <div class="absolute right-0 top-0 w-24 h-24 bg-[var(--color-secondary)] opacity-5 rounded-bl-full -mr-4 -mt-2 transition-transform group-hover:scale-110"></div>

            <div class="flex-1 mb-4">
                <div class="mb-2">
                    <span class="text-2xl font-black text-[var(--color-secondary)] tracking-tight">
                        $<?php echo number_format((float)($srv['price']??0), 2); ?>
                    </span>
                </div>

                <h3 class="text-lg font-black text-[var(--color-primary)] uppercase leading-tight">
                    <?php echo htmlspecialchars($srv['name'] ?? 'Servicio'); ?>
                </h3>
            </div>

            <div class="mt-auto pt-0 border-t border-gray-100">
                <div class="flex gap-2">
                    <a href="https://wa.me/?text=<?php echo urlencode($msg . ' ' . $url); ?>" target="_blank" 
                       class="flex-1 bg-[var(--color-primary)] hover:bg-[var(--color-secondary)] text-white py-2.5 rounded-xl flex items-center justify-center transition-colors">
                        <i data-lucide="message-circle" class="w-5 h-5"></i>
                    </a>
                    
                    <a href="fb-messenger://share/?link=<?php echo urlencode($url); ?>" 
                       class="flex-1 bg-[var(--color-primary)] hover:bg-[var(--color-secondary)] text-white py-2.5 rounded-xl flex items-center justify-center transition-colors">
                        <i data-lucide="facebook" class="w-5 h-5"></i>
                    </a>
                    
                    <button onclick="copyLink(<?php echo (int)$srv['id']; ?>)" 
                            class="flex-1 bg-[var(--color-primary)] hover:bg-[var(--color-secondary)] text-white py-2.5 rounded-xl flex items-center justify-center transition-colors" title="Copy Link">
                        <i data-lucide="link" class="w-5 h-5"></i>
                    </button>
                </div>
            </div>
            
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
            </div>
        </div>
        <div id="tab-clientes" class="tab-content animate-slide-in">
            
            <div class="mb-8 mt-2 text-center">
                <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                    <i data-lucide="credit-card" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-4xl font-black text-gray-800"> FACTURACIÓN</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">COBROS PENDIENTES</p>
            </div>

<div class="pt-8 mb-8">
    <h4 class="text-center text-base font-black uppercase text-gray-500 mb-4">
        Facturas Por Cobrar 
        <span class="text-xl font-black text-[var(--color-secondary)]">(<?php echo count($pendingInvoices); ?>)</span>
    </h4>
    
    <div id="pending-invoices-list" class="space-y-4 mb-6">
        <?php if(empty($pendingInvoices)): ?>
            <div class="col-span-full flex flex-col items-center justify-center py-10 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
                <i data-lucide="sun" class="w-12 h-12 mb-3 opacity-50"></i>
                <span class="font-bold text-lg uppercase text-gray-500">No hay facturas pendientes</span>
            </div>
        <?php else: ?>
            <?php foreach($pendingInvoices as $inv): 
                $status = strtolower($inv['status']);
                $statusColor = 'border-yellow-500'; 
                $statusTextColor = 'text-yellow-700';
                $statusBg = 'bg-yellow-50';
                $statusText = 'ENVIADA';

                if ($status === 'atrasada') {
                    $statusColor = 'border-red-600'; 
                    $statusTextColor = 'text-red-700';
                    $statusBg = 'bg-red-50';
                    $statusText = '¡ATRASADA!';
                } elseif ($status === 'enviado') {
                    $statusColor = 'border-blue-500';
                    $statusTextColor = 'text-blue-700';
                    $statusBg = 'bg-blue-50';
                    $statusText = 'ENVIADA';
                }
            ?>
            <a href="invoice-view.php?token=<?php echo htmlspecialchars($inv['external_id']); ?>" target="_blank"
               class="bg-white rounded-3xl p-5 border-l-8 <?php echo $statusColor; ?> shadow-lg flex items-center justify-between cursor-pointer hover:shadow-xl active:scale-[0.99] transition-all duration-200 touch-manipulation">
                
                <div class="flex-1 overflow-hidden">
                    <h3 class="text-lg font-black text-gray-800 uppercase leading-tight truncate">
                        #<?php echo htmlspecialchars($inv['external_id']); ?> - <?php echo htmlspecialchars($inv['client_name'] ?? 'Cliente'); ?>
                    </h3>
                    
                    <p class="text-sm font-bold text-gray-500 mt-1">
                        Vence: <span class="text-base font-black text-gray-700 ml-1"><?php echo date('d/m/Y', strtotime($inv['due_date'])); ?></span>
                    </p>
                </div>
                
                <div class="text-right flex-shrink-0 ml-4">
                    <p class="text-2xl font-black <?php echo $statusTextColor; ?> tracking-tight">
                        $<?php echo number_format((float)$inv['total_amount'], 2); ?>
                    </p>
                    <span class="text-xs font-black uppercase px-2 py-0.5 rounded-full <?php echo $statusBg; ?> <?php echo $statusTextColor; ?> mt-1 border border-black/5">
                        <?php echo $statusText; ?>
                    </span>
                </div>
            </a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<div onclick="openDocModal('invoice')" 
     class="bg-white rounded-3xl p-5 border-l-8 border-[var(--color-secondary)] shadow-xl flex items-center justify-between cursor-pointer hover:shadow-2xl active:scale-[0.99] transition-all duration-200 mb-10 touch-manipulation">
    <div class="flex items-center gap-4">
        <div class="bg-[var(--color-secondary)] text-white w-14 h-14 rounded-full flex items-center justify-center flex-shrink-0">
            <i data-lucide="plus" class="w-7 h-7"></i>
        </div>
        <div>
            <h3 class="text-xl font-black text-gray-800 uppercase leading-tight">Factura </h3>
            <p class="text-sm text-gray-500 font-semibold uppercase mt-1">Crear un link de invoice</p>
        </div>
    </div>
    <i data-lucide="chevron-right" class="w-6 h-6 text-gray-400"></i>
</div>

             <div class="border-t border-dashed border-gray-300 pt-6 mb-8 text-center">
                <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                    <i data-lucide="message-square-warning" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                    <h3 class="text-4xl font-black text-gray-800"> QUEJAS</h3>
                </div>
                <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">SEGUIMIENTO DE CASOS ABIERTOS</p>
                <div class="mt-2"><span class="bg-red-100 text-red-600 text-xs font-black px-3 py-1 rounded-full border border-red-200"><?php echo count($complaints); ?> activas</span></div>
            </div>

            <div id="complaints-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-10">
    <?php if(empty($complaints)): ?>
        <div class="col-span-full flex flex-col items-center justify-center py-10 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
            <svg class="w-12 h-12 mb-3 opacity-50 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
            <span class="font-bold text-lg uppercase text-gray-500">Sin quejas pendientes. ¡Todo bien!</span>
        </div>
    <?php else: ?>
        <?php foreach($complaints as $item): 
            $status = $item['status'] ?? 'Recibido'; 
            $title = $item['title'] ?? 'Queja Sin Título';
            $clientName = $item['first_name'] ?? $item['client_name'] ?? 'Anónimo';
            $description = $item['description'] ?? '';

            $statusColor = 'border-gray-300';
            $badgeBg = 'bg-gray-400';
            $actionText = 'Resolver';

            if ($status === 'Recibido') {
                $statusColor = 'border-red-600'; 
                $badgeBg = 'bg-red-600';
                $actionText = 'Tomar Acción';
            } elseif ($status === 'Resolviendo') {
                $statusColor = 'border-yellow-500'; 
                $badgeBg = 'bg-yellow-500';
            } elseif ($status === 'Acción Requerida') {
                $statusColor = 'border-orange-500'; 
                $badgeBg = 'bg-orange-500';
            } elseif ($status === 'Resuelto' || $status === 'Archivado') {
                $statusColor = 'border-green-500'; 
                $badgeBg = 'bg-green-500';
            }

        ?>
        <div class="bg-white rounded-3xl p-5 border-l-8 <?php echo $statusColor; ?> shadow-xl hover:shadow-2xl transition-all duration-200 cursor-pointer">
            
            <div class="flex justify-between items-start mb-3">
                <span class="text-sm font-black uppercase text-white <?php echo $badgeBg; ?> px-3 py-1 rounded-full shadow-sm">
                    <?php echo htmlspecialchars($status); ?>
                </span>
                
                <div class="text-right">
                    <span class="text-xs text-gray-400 font-bold uppercase">Reporte:</span>
                    <p class="text-sm text-gray-500 font-mono leading-none"><?php echo date('d/m/Y', strtotime($item['created_at'])); ?></p>
                </div>
            </div>

            <h3 class="text-lg font-black text-[var(--color-primary)] uppercase mb-2 leading-tight">
                <?php echo htmlspecialchars($title); ?>
            </h3>
            
            <div class="bg-gray-50 p-3 rounded-xl mb-4 border border-gray-100 h-24 overflow-hidden">
                <p class="text-sm text-gray-700 line-clamp-3 italic">
                    "<?php echo htmlspecialchars($description); ?>"
                </p>
            </div>
            
            <div class="flex justify-between items-center mt-auto">
                <p class="text-xs text-gray-500 font-bold uppercase">
                    Cliente: 
                    <span class="text-sm font-black text-gray-800 ml-1"><?php echo htmlspecialchars($clientName); ?></span>
                </p>
                
                <button onclick="performAction('resolve_complaint', <?php echo (int)$item['id']; ?>)" 
                        class="bg-[var(--color-secondary)] text-white py-2 px-4 rounded-xl text-xs font-black uppercase active:scale-95 shadow-md shadow-indigo-200 hover:brightness-110 transition-transform">
                    <?php echo $actionText; ?>
                </button>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

            <div class="border-t border-dashed border-gray-300 pt-6 mt-6 mb-20">
                <div class="mb-4 px-1 text-center">
                    <div class="flex flex-col items-center justify-center md:flex-row md:gap-2"> 
                        <i data-lucide="star" class="w-6 h-6 text-[var(--color-secondary)] mb-2 md:mb-0"></i>
                        <h3 class="text-4xl font-black text-gray-800"> RESEÑAS</h3>
                    </div>
                    <p class="text-lg uppercase font-bold text-[var(--color-secondary)]">RESEÑAS DEJADAS A CLIENTES</p>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
    <?php if(empty($reviews)): ?>
        <div class="col-span-full flex flex-col items-center justify-center py-10 text-gray-400 border-2 border-dashed border-gray-300 rounded-3xl bg-gray-50">
            <svg class="w-12 h-12 mb-3 opacity-50 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 15l-2 5L9 9l11 4-5 2zm0 0v5h5"></path></svg>
            <span class="font-bold text-lg uppercase text-gray-500">Sin reseñas recientes</span>
        </div>
    <?php else: ?>
        <?php foreach($reviews as $rev): 
            $rating = (int)($rev['review_rating'] ?? 5);
            $emptyStars = 5 - $rating;
        ?>
        <div class="bg-white rounded-3xl p-5 shadow-xl border-t-8 border-yellow-400/50 hover:shadow-2xl transition-all duration-200 flex flex-col h-full">
            
            <div class="flex justify-between items-center mb-3">
                <div class="flex text-yellow-500">
                    <?php for($i=0; $i<$rating; $i++): ?>
                        <i data-lucide="star" class="w-5 h-5 fill-current"></i>
                    <?php endfor; ?>
                    <?php for($i=0; $i<$emptyStars; $i++): ?>
                        <i data-lucide="star" class="w-5 h-5 text-gray-200"></i>
                    <?php endfor; ?>
                </div>
                
                <span class="text-xs font-bold text-white uppercase bg-[var(--color-secondary)] px-3 py-1 rounded-full shadow-sm">
                    <?php echo htmlspecialchars($rev['source'] ?? 'Web'); ?>
                </span>
            </div>
            
            <p class="text-base text-gray-700 italic mb-4 flex-1 line-clamp-4">
                "<?php echo htmlspecialchars($rev['review_text'] ?? 'Excelente servicio, muy recomendado.'); ?>"
            </p>
            
            <div class="flex justify-between items-center border-t border-gray-100 pt-3 mt-auto">
                <span class="text-sm font-black text-[var(--color-primary)] uppercase">
                    <?php echo htmlspecialchars($rev['review_name'] ?? 'Cliente Anónimo'); ?>
                </span>
                <span class="text-xs text-gray-400 font-semibold">
                    <?php echo date('d M Y', strtotime($rev['created_at'] ?? 'now')); ?>
                </span>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>
            </div>
        </div>
        <button onclick="openExpenseModal()" 
                class="fixed bottom-6 right-6 bg-black text-white w-14 h-14 rounded-full shadow-2xl hover:scale-110 transition z-50 flex items-center justify-center border-4 border-white active:scale-90 touch-manipulation">
            <i data-lucide="camera" class="w-6 h-6"></i>
        </button>

        <div id="expense-modal" class="fixed inset-0 bg-black/90 hidden z-[70] flex items-end md:items-center justify-center backdrop-blur-sm transition-opacity opacity-0">
    <div class="bg-white w-full md:max-w-sm rounded-t-3xl md:rounded-3xl shadow-2xl overflow-hidden transform translate-y-full md:translate-y-0 transition-transform duration-300" id="expense-modal-content">
        
        <div class="bg-gray-50 p-5 flex justify-between items-center border-b border-gray-100">
            <div class="flex-1 min-w-0">
                <div class="flex items-center gap-3"> 
                    <i data-lucide="receipt" class="w-6 h-6 text-[var(--color-secondary)] flex-shrink-0"></i>
                    <h3 class="text-3xl font-black text-gray-800 uppercase leading-tight truncate">
                         Gasto
                    </h3>
                </div>
                <p class="text-sm uppercase font-bold text-gray-500 mt-1">
                    REGISTRO DE TRANSACCIÓN
                </p>
            </div>
            <button onclick="closeExpenseModal()" class="text-gray-400 hover:text-red-500 bg-white rounded-full p-2.5 shadow-md flex-shrink-0">
                <i data-lucide="x" class="w-6 h-6"></i>
            </button>
        </div>
        
        <form id="expense-form" class="p-6 space-y-6" enctype="multipart/form-data">
            <input type="hidden" name="transaction_date" value="<?php echo date('Y-m-d'); ?>">

            <div>
                <label class="block text-xs font-black text-gray-400 uppercase mb-2 tracking-wider">Monto ($)</label>
                <div class="relative">
                    <span class="absolute left-0 top-1.5 text-gray-800 font-bold text-2xl">$</span>
                    <input type="number" step="0.01" name="amount" required 
                            class="w-full pl-6 text-4xl font-black text-gray-900 border-b-4 border-[var(--color-secondary)]/50 focus:border-black outline-none py-1 placeholder-gray-300 bg-transparent transition" 
                            placeholder="0.00" inputmode="decimal">
                </div>
            </div>
            
            <div>
                <label class="block text-xs font-black text-gray-400 uppercase mb-2 tracking-wider">Concepto del Gasto</label>
                <input type="text" name="description" required 
                        class="w-full bg-gray-50 border border-gray-200 rounded-xl p-4 text-base font-bold text-gray-700 uppercase focus:ring-2 focus:ring-[var(--color-secondary)]/30 focus:border-[var(--color-secondary)] outline-none transition" 
                        placeholder="Ej: Gasolina, Insumos, Publicidad">
            </div>

            <div>
                <label class="block text-xs font-black text-gray-400 uppercase mb-2 tracking-wider">Foto del Recibo (Opcional)</label>
                <label class="flex flex-col items-center justify-center w-full h-28 border-2 border-dashed border-gray-300 rounded-2xl cursor-pointer bg-gray-50 hover:bg-gray-100 transition group relative overflow-hidden">
                    <div class="flex flex-col items-center justify-center pt-5 pb-6" id="upload-placeholder">
                        <i data-lucide="camera" class="w-8 h-8 text-gray-400 mb-1"></i>
                        <p class="text-xs text-gray-400 font-bold uppercase mt-1">Tocar para Tomar Foto</p>
                    </div>
                    <img id="preview-image" class="absolute inset-0 w-full h-full object-cover hidden">
                    <input type="file" name="receipt" id="receipt-input" accept="image/*" capture="environment" class="hidden">
                </label>
            </div>

            <button type="submit" id="btn-save-expense" 
                    class="w-full bg-[var(--color-primary)] text-white font-black uppercase py-4 rounded-xl shadow-lg shadow-indigo-200 hover:bg-black active:scale-[0.98] transition-all flex justify-center items-center gap-2">
                <span>Guardar Gasto</span>
                <i data-lucide="send" class="w-5 h-5"></i>
            </button>
        </form>
    </div>
</div>
        
        <div id="doc-modal" class="fixed inset-0 bg-black/90 hidden z-[80] flex items-end md:items-center justify-center backdrop-blur-sm transition-opacity opacity-0">
    <div class="bg-white w-full md:max-w-md rounded-t-3xl md:rounded-3xl shadow-2xl overflow-hidden transform translate-y-full md:translate-y-0 transition-transform duration-300" id="doc-modal-content">
        
        <div id="doc-header" class="bg-[var(--color-primary)] p-5 flex justify-between items-center text-white">
            <div>
                <h3 class="text-2xl font-black uppercase" id="doc-title">NUEVO ESTIMADO</h3>
                <p class="text-sm uppercase font-semibold opacity-80" id="doc-subtitle">Creación y Envío Rápido</p>
            </div>
            <button onclick="closeDocModal()" class="bg-white/20 rounded-full p-2.5 hover:bg-white/30 transition">
                <i data-lucide="x" class="w-6 h-6"></i>
            </button>
        </div>

        <form id="doc-form" class="p-6 bg-gray-50 space-y-6">
            <input type="hidden" name="type" id="doc-type">
            
            <div class="relative z-50 p-3 bg-white rounded-2xl border-2 border-gray-100 shadow-inner">
                <label class="block text-lg font-black text-gray-500 uppercase mb-2">Buscar Cliente o Lead</label>
                <input type="text" id="doc-client-search" placeholder="Escribe el nombre aquí..." autocomplete="off"
                    class="w-full text-base border-b-2 border-gray-200 focus:border-[var(--color-primary)] outline-none py-2 px-0 font-bold uppercase bg-transparent transition"
                    aria-label="Buscar cliente">
                <input type="hidden" name="client_id" id="doc-client-id" required>
                <div id="doc-search-results" class="absolute left-0 w-full bg-white shadow-2xl rounded-b-2xl border border-gray-200 max-h-48 overflow-y-auto hidden mt-0 pt-2">
                    </div>
            </div>

            <div id="quote-items-container" class="space-y-4 p-4 bg-white rounded-2xl border border-gray-200 shadow-md">
                <h4 class="text-base font-black uppercase text-gray-700 flex items-center gap-2">
                    <i data-lucide="list-checks" class="w-5 h-5 text-gray-400"></i> Conceptos y Servicios
                </h4>
                
                <div id="items-list" class="space-y-3">
                    </div>
                
                <button type="button" onclick="addItemRow()" class="w-full bg-gray-100 hover:bg-gray-200 text-gray-600 font-bold py-3 rounded-xl text-sm uppercase flex items-center justify-center gap-2 transition">
                    <i data-lucide="plus" class="w-4 h-4"></i> Añadir Ítem
                </button>
                
                <div class="pt-4 border-t-2 border-dashed border-gray-200 flex justify-between items-center">
                    <span class="text-lg font-black uppercase text-gray-800">TOTAL ESTIMADO:</span>
                    <span id="doc-total-display" class="text-3xl font-black text-blue-600">$0.00</span>
                </div>
            </div>
            
            <div id="invoice-simple-container" class="space-y-4 p-4 bg-white rounded-2xl border border-gray-200 shadow-md hidden">
                <h4 class="text-base font-black uppercase text-gray-700 flex items-center gap-2">
                    <i data-lucide="zap" class="w-5 h-5 text-gray-400"></i> Factura Rápida
                </h4>
                <div>
                    <label class="block text-xs font-black text-gray-500 uppercase mb-2">Concepto Único</label>
                    <input type="text" name="description" placeholder="Ej: Pago de Instalación"
                        class="w-full border border-gray-300 rounded-xl p-3 text-base font-semibold uppercase focus:ring-2 focus:ring-[var(--color-secondary)] outline-none transition">
                </div>
                <div>
                    <label class="block text-xs font-black text-gray-500 uppercase mb-2">Monto Total ($)</label>
                    <input type="number" step="0.01" name="amount" placeholder="0.00" inputmode="decimal"
                        class="w-full border-2 border-gray-300 rounded-xl p-3 text-2xl font-black focus:ring-2 focus:ring-[var(--color-secondary)] outline-none transition">
                </div>
            </div>
            
            <button type="submit" id="btn-create-doc" 
                    class="w-full bg-[var(--color-primary)] text-white font-black uppercase py-4 rounded-xl shadow-lg shadow-indigo-200 active:scale-[0.98] transition-all flex justify-center items-center gap-2">
                <span>Generar Enlace único</span> 
                <i data-lucide="send" class="w-5 h-5"></i>
            </button>
        </form>
    </div>
</div>

        <div id="share-modal" class="fixed inset-0 bg-black/90 hidden z-[90] flex items-center justify-center backdrop-blur-sm opacity-0 transition-opacity">
    <div class="bg-white w-[90%] max-w-sm rounded-3xl p-8 text-center shadow-2xl transform scale-90 transition-transform" id="share-modal-content">
        
        <div class="w-16 h-16 bg-green-500 text-white rounded-full flex items-center justify-center mx-auto mb-5 shadow-lg shadow-green-200">
            <i data-lucide="check" class="w-8 h-8 font-black"></i>
        </div>
        
        <h3 class="text-3xl font-black text-gray-800 uppercase mb-2">¡Documento Listo!</h3>
        <p class="text-base text-gray-600 mb-6 font-medium">El enlace está creado y listo para enviarse al cliente.</p>
        
        <a id="wa-share-btn" href="#" target="_blank" 
           class="w-full bg-[#25D366] text-white font-black py-4 rounded-xl uppercase shadow-xl shadow-green-200 flex items-center justify-center gap-2 mb-4 active:scale-[0.98] transition-all duration-150 hover:bg-[#128C7E]">
            <i data-lucide="send" class="w-5 h-5"></i> Enviar por WhatsApp
        </a>
        
        <button onclick="closeShareModal()" class="text-sm text-gray-500 font-bold uppercase hover:text-gray-700 transition">
            Cerrar Ventana
        </button>
        
    </div>
</div>
        
    </main>
    
    <div id="fbi-screen" class="fbi-overlay hidden">
        <div class="loading-container">
            <div class="radar"></div>
            <img src="<?php echo htmlspecialchars($client_info['logo_url'] ?? ''); ?>" alt="Logo" class="logo-center">
        </div>
        <div id="fbi-text" class="text-2xl font-bold uppercase tracking-widest mb-2 text-white">INICIANDO...</div>
        <div id="fbi-subtext" class="text-md uppercase font-semibold text-gray-400 ">Esperando conexión segura</div>
    </div>
    
                    <a href="app-logout.php" 
                   class="w-full bg-[var(--color-secondary)] hover:opacity-90 text-white font-black py-2.5 px-4 uppercase sm:w-auto flex items-center justify-center gap-2">
                    <i data-lucide="log-out" class="w-5 h-5"></i> Salir Del Live OPS Center
                </a>

    <?php @include 'core/page-footer.php'; ?>

<div id="search-panel" 
     class="fixed inset-0 z-[60] bg-black/80 hidden 
            backdrop-blur-sm transition-opacity opacity-0 
            flex justify-end pointer-events-none touch-none 
            transform translate-x-full duration-300">
    
    <div id="search-panel-content-wrapper" 
         class="bg-white w-full h-full md:w-[450px] max-w-full 
                flex flex-col flex-shrink-0 
                pointer-events-auto shadow-2xl overflow-y-auto">
        
        <div class="bg-[var(--color-primary)] text-white text-center py-3 w-full flex-shrink-0 relative">
            <h3 class="text-2xl font-black uppercase tracking-wider">
                BÚSQUEDA AVANZADA
            </h3>
            <button onclick="closeSearchModal()" class="absolute top-1/2 right-4 transform -translate-y-1/2 text-white hover:text-red-300 p-2">
                <i data-lucide="x" class="w-6 h-6"></i>
            </button>
        </div>

        <div class="w-full h-full flex flex-col justify-center items-center p-6">
            
            <div class="flex flex-col items-center text-center mb-8 flex-shrink-0 relative w-full">
                <?php if(!empty($client_info['logo_url'])): ?>
                    <img src="<?php echo htmlspecialchars($client_info['logo_url']); ?>" class="h-20 md:h-14 object-contain mb-3">
                <?php endif; ?>
                <h1 class="text-4xl font-black uppercase text-[var(--color-primary)] mb-1">
                    CONTACTOS
                </h1>
                </div>

            <div class="relative max-w-full mx-auto mb-6 w-full flex-shrink-0">
                <div class="flex flex-col md:flex-row w-full shadow-lg rounded-2xl overflow-hidden border-2 border-gray-200 focus-within:border-[var(--color-secondary)] transition-all duration-300">
                    
                    <div class="relative flex-grow">
                        <input
                            type="text"
                            id="client-search-input"
                            class="w-full h-14 p-4 pl-14 pr-4 bg-white
                                    focus:outline-none 
                                    text-base font-semibold text-gray-700 placeholder-gray-500
                                    border-none ring-0
                                    "
                            placeholder="Buscar Cliente o Prospecto..."
                            autocomplete="off"
                            onkeyup="performSearch(this.value)"
                        >
                        <i data-lucide="search" class="absolute left-4 top-1/2 transform -translate-y-1/2 w-6 h-6 text-gray-400 pointer-events-none"></i>
                        
                        <div id="input-loading" class="absolute right-4 top-1/2 transform -translate-y-1/2 hidden">
                            <i data-lucide="loader-2" class="w-6 h-6 animate-spin text-indigo-500"></i>
                        </div>
                    </div>

                    <button
                        id="trigger-search-button"
                        class="flex items-center justify-center h-14 px-6 bg-[var(--color-secondary)] uppercase text-white
                                font-bold hover:bg-opacity-90 transition-all duration-300 whitespace-nowrap
                                focus:outline-none w-full md:w-auto"
                        title="Buscar Cliente"
                    >
                        <i data-lucide="user-search" class="w-5 h-5 mr-2"></i> Abrir Perfil
                    </button>
                </div>

                <div id="results-dropdown-modal" class="bg-white hidden mt-1 absolute w-full rounded-xl shadow-xl border border-gray-200 max-h-48 overflow-y-auto">
                </div>
            </div>

        </div>
        </div>
</div>

    <div id="native-notification-modal" class="fixed inset-0 bg-black/50 hidden z-[200] flex items-center justify-center backdrop-blur-sm transition-opacity opacity-0">
        <div class="bg-white p-6 rounded-2xl shadow-2xl max-w-sm w-full mx-4 text-center transform scale-95 transition-transform duration-200">
            <div class="mb-4 flex justify-center">
                <div class="bg-[var(--color-highlight)] p-3 rounded-full text-[var(--color-primary)]">
                    <i data-lucide="bell" class="w-8 h-8"></i>
                </div>
            </div>
            <h3 id="modal-notif-title" class="text-xl font-black text-gray-800 uppercase mb-2">Notificación</h3>
            <p id="modal-notif-message" class="text-gray-600 mb-6 font-medium">Mensaje del sistema...</p>
            <button onclick="document.getElementById('native-notification-modal').classList.add('hidden')" class="w-full bg-[var(--color-primary)] text-white py-3 rounded-xl font-bold uppercase shadow-lg">Entendido</button>
        </div>
    </div>
</body>

<script>
    lucide.createIcons();
    document.addEventListener('DOMContentLoaded', () => {
        const qrImg = document.getElementById('desktop-qr-code');
        const urlDisplay = document.getElementById('page-url-display');
        const currentUrl = window.location.href;
        
        if(qrImg) {
            qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${encodeURIComponent(currentUrl)}`;
        }
        if(urlDisplay) {
            urlDisplay.innerText = currentUrl;
        }
        
        // Inicializar la pestaña Clientes (antes quejas)
        if (window.location.hash.includes('clientes')) {
             switchTab('clientes');
        }
    });

    // --- LÓGICA DE PESTAÑAS (TABS) ---
    function switchTab(tabId) {
        document.querySelectorAll('.tab-content').forEach(el => {
            el.classList.remove('active');
            el.classList.remove('animate-slide-in'); 
        });

        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('active');
            btn.style.borderBottomColor = 'transparent';
        });

        const selectedContent = document.getElementById('tab-' + tabId);
        if(selectedContent) {
            selectedContent.classList.add('active');
            void selectedContent.offsetWidth; // trigger reflow
            selectedContent.classList.add('animate-slide-in');
        }

        const selectedBtn = document.getElementById('btn-' + tabId);
        if(selectedBtn) {
            selectedBtn.classList.add('active');
            selectedBtn.style.borderBottomColor = 'var(--color-highlight)';
            selectedBtn.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
        }
        lucide.createIcons();
    }

    function getCsrfToken() {
        return document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    }

    function escapeHtml(unsafe) {
        if (unsafe === null || unsafe === undefined) return '';
        return String(unsafe)
             .replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
    }

    function copyLink(id) {
        const url = `${window.location.origin}/services-offered.php?id=${id}`;
        navigator.clipboard.writeText(url);
        if(navigator.vibrate) navigator.vibrate(50);
        // Usar toast o notificación aquí, pero mantendremos alert() para evitar dependencia
        alert('Link Copiado'); 
    }

    function playNotificationSound() {
        const audio = document.getElementById('notification-sound');
        if(audio) {
            audio.play().catch(e => console.log("Audio autoplay blocked by browser policy"));
        }
    }

    // Acción rápida para Leads/Citas/Quejas
    async function performAction(action, id) {
        if(!confirm('¿Estás seguro de realizar esta acción?')) return;
        
        if(navigator.vibrate) navigator.vibrate(20);
        
        let prefix = '';
        if(action.includes('appointment')) prefix = 'card-appt-';
        if(action.includes('lead')) prefix = 'card-lead-';
        const el = document.getElementById(prefix + id);
        
        if(el) el.style.opacity = '0.5';

        try {
            const res = await fetch('db/live-business-actions.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-Token': getCsrfToken() 
                },
                body: JSON.stringify({ action, id })
            });
            const data = await res.json();
            
            if(data.success) {
                if(action === 'approve_appointment' || action === 'approve_lead') {
                    location.reload();
                } else {
                    if(el) {
                        el.style.transform = 'scale(0.9)';
                        setTimeout(() => el.remove(), 300);
                    } else {
                        location.reload();
                    }
                }
            } else {
                if(el) el.style.opacity = '1';
                alert('Error: ' + data.message);
            }
        } catch(e) {
            console.error(e);
            if(el) el.style.opacity = '1';
            alert('Error de conexión');
        }
    }

// Lógica Panel Lateral Búsqueda de Contacto 
    const panel = document.getElementById('search-panel'); // ID corregido
    const searchInput = document.getElementById('client-search-input');
    const resultsDropdown = document.getElementById('results-dropdown-modal');
    const inputLoading = document.getElementById('input-loading'); 
    let debounceTimer;

    function openSearchModal() {
        panel.classList.remove('hidden', 'pointer-events-none');
        
        setTimeout(() => {
            panel.classList.remove('opacity-0');
            panel.classList.remove('translate-x-full'); 
        }, 10); 
        
        searchInput.value = ''; 
        resultsDropdown.innerHTML = '';
        resultsDropdown.classList.add('hidden');
        document.getElementById('search-placeholder-text').classList.remove('hidden'); 
        searchInput.focus();
    }

    function closeSearchModal() {
        // Cerrar con transición, moviéndose hacia la derecha
        panel.classList.add('opacity-0');
        panel.classList.add('translate-x-full'); 
        panel.classList.add('pointer-events-none');
        
        // Ocultar completamente después de la transición
        setTimeout(() => panel.classList.add('hidden'), 300);
    }

searchInput.addEventListener('input', (e) => {
    clearTimeout(debounceTimer);
    const term = e.target.value.trim();
    resultsDropdown.innerHTML = '';
    resultsDropdown.classList.add('hidden');
    document.getElementById('search-placeholder-text').classList.remove('hidden');

    if(term.length < 2) return;

    document.getElementById('search-placeholder-text').classList.add('hidden');
    inputLoading.classList.remove('hidden');

    debounceTimer = setTimeout(async () => {
        try {
            const res = await fetch(`db/contact-search.php?q=${encodeURIComponent(term)}`);
            const data = await res.json();
            const results = Array.isArray(data) ? data : (data.results || []);

            inputLoading.classList.add('hidden');
            
            if(results.length > 0) {
                resultsDropdown.classList.remove('hidden');
                results.forEach(item => {
                    const div = document.createElement('div');
                    div.className = "result-item-modal p-3 border-b border-gray-100 flex justify-between items-center";
                    
                    const fullName = item.full_data.first_name ? `${item.full_data.first_name || ''} ${item.full_data.last_name || ''}`.trim() : item.full_data.company || 'Cliente';
                    const type = item.type === 'client' ? 'client' : 'lead'; 
                    const typeLabel = item.type === 'client' ? 'CLIENTE' : 'LEAD';

                    // Usamos colores de variables si están definidas
                    const typeColor = item.type === 'client' ? 'bg-[var(--color-success)] text-white' : 'bg-[var(--color-highlight)] text-white';

                    div.innerHTML = `
                        <div>
                            <div class="font-bold text-gray-800 uppercase">${fullName}</div>
                            <div class="text-md text-gray-500">${item.full_data.company || 'Residencial'} </div>
                        </div>
                        <span class="text-sm font-black px-2 py-1 rounded ${typeColor}">${typeLabel}</span>
                    `;

                    // Al seleccionar, se inicia la animación FBI y luego se redirige.
                    div.addEventListener('click', () => {
                        resultsDropdown.classList.add('hidden');
                        searchInput.value = fullName; 
                        startFBILoadingVisual(item.id, type); // ID real del cliente/lead
                    });
                    resultsDropdown.appendChild(div);
                });
            } else {
                resultsDropdown.innerHTML = '<div class="p-3 text-center text-gray-400 italic text-sm">Sin resultados.</div>';
                resultsDropdown.classList.remove('hidden');
            }
            lucide.createIcons();
        } catch(err) {
            inputLoading.classList.add('hidden');
            resultsDropdown.innerHTML = '<div class="p-3 text-center text-red-400 italic text-sm">Error en la búsqueda.</div>';
            resultsDropdown.classList.remove('hidden');
        }
    }, 300);
});

// FUNCIÓN DE ANIMACIÓN FBI Y REDIRECCIÓN AL PERFIL COMPLETO
function startFBILoadingVisual(id, type) {
    const fbiScreen = document.getElementById('fbi-screen');
    const fbiText = document.getElementById('fbi-text');
    const fbiSub = document.getElementById('fbi-subtext');

    closeSearchModal(); 
    fbiScreen.classList.remove('hidden');

    const steps = [
        { t: "ESTABLECIENDO ENLACE...", s: "Verificando Credenciales De Seguridad" },
        { t: "BUSCANDO EN LA BASE DE DATOS...", s: "Escaneando Todo El Sistema" },
        { t: "RECOPILANDO REGISTROS...", s: "Unificando Historial Y Actividad" },
        { t: "ACCESO CONCEDIDO", s: "Desencriptando Perfil del Cliente" }
    ];

    let step = 0;
    
    // Iniciar la animación de texto
    const interval = setInterval(() => {
        if(step < steps.length) {
            fbiText.innerText = steps[step].t;
            fbiSub.innerText = steps[step].s;
            step++;
        }
    }, 600);

    // Redirección después de la animación
    setTimeout(() => {
        clearInterval(interval);
        
        // Redirigir al archivo full-clients-profile.php con el ID y Tipo
        window.location.href = `full-clients-profile.php?id=${id}&type=${type}`;
        
    }, 3000); // 3.0 segundos para ver la animación completa
}

// AÑADE ESTA FUNCIÓN para manejar la animación visual
function startFBILoadingVisual(id, type) {
    const fbiScreen = document.getElementById('fbi-screen');
    const fbiText = document.getElementById('fbi-text');
    const fbiSub = document.getElementById('fbi-subtext');

    // Cerrar el modal de búsqueda primero
    closeSearchModal(); 
    
    // Mostrar la pantalla de carga FBI
    fbiScreen.classList.remove('hidden');

    const steps = [
        { t: "ESTABLECIENDO ENLACE...", s: "Verificando Credenciales De Seguridad" },
        { t: "BUSCANDO EN LA BASE DE DATOS...", s: "Escaneando Todo El Sistema" },
        { t: "RECOPILANDO REGISTROS...", s: "Unificando Historial Y Actividad" },
        { t: "ACCESO CONCEDIDO", s: "Perfil del Contacto Cargado" }
    ];

    let step = 0;
    
    // Iniciar la animación de texto
    const interval = setInterval(() => {
        if(step < steps.length) {
            fbiText.innerText = steps[step].t;
            fbiSub.innerText = steps[step].s;
            step++;
        }
    }, 600);

    // Simular el tiempo de carga y luego hacer algo (ej. ir a la URL de perfil completo)
    setTimeout(() => {
        clearInterval(interval);
        
        // Simplemente ocultar la animación y recargar (o navegar)
        fbiScreen.classList.add('hidden');
        
        // **ACCIÓN DESPUÉS DE LA CARGA SIMULADA:**
        // Opcion A: Redirigir al perfil completo (usando el URL del archivo original)
        // window.location.href = `full-clients-profile.php?id=${id}&type=${type}`;
        
        // Opcion B: Mostrar una notificación de que la carga está completa
        alert(`Animación completa. Simulación de carga del contacto ID: ${id}, Tipo: ${type}.`);
        
    }, 2500); 
}

    function closeSearchModal() {
        modal.style.opacity = '0';
        modal.classList.add('pointer-events-none');
        setTimeout(() => modal.classList.add('hidden'), 200);
    }

    searchInput.addEventListener('input', (e) => {
        clearTimeout(debounceTimer);
        const term = e.target.value.trim();
        
        if(term.length < 2) {
            resultsContainer.innerHTML = '<p class="text-center text-gray-400 text-xs py-4 font-bold uppercase">...</p>';
            return;
        }

        debounceTimer = setTimeout(async () => {
            resultsContainer.innerHTML = '<p class="text-center text-[var(--color-secondary)] text-xs py-4 font-bold uppercase">Buscando...</p>';
            try {
                // Usamos la misma ruta de búsqueda que ya tenías
                const res = await fetch(`db/contact-search.php?q=${encodeURIComponent(term)}`);
                const data = await res.json();
                const results = Array.isArray(data) ? data : (data.results || []);
                
                if(results.length === 0) {
                    resultsContainer.innerHTML = '<p class="text-center text-gray-400 text-xs py-4 font-bold uppercase">Sin resultados.</p>';
                } else {
                    resultsContainer.innerHTML = results.map(c => `
                        <div class="bg-gray-50 p-4 rounded-xl border border-gray-200 active:bg-gray-100 transition cursor-pointer mb-2">
                            <div class="flex justify-between">
                                <h4 class="font-black text-[var(--color-primary)] uppercase text-sm">${escapeHtml(c.label)}</h4>
                            </div>
                            <div class="flex gap-4 mt-2">
                                <a href="tel:${escapeHtml(c.full_data.phone)}" class="text-xs font-bold text-gray-500 flex items-center gap-1 bg-white px-2 py-1 rounded border border-gray-200">
                                    <i data-lucide="phone" class="w-3 h-3"></i> Llamar
                                </a>
                            </div>
                        </div>
                    `).join('');
                    lucide.createIcons();
                }
            } catch(err) {
                console.error(err);
                resultsContainer.innerHTML = '<p class="text-center text-red-400 text-xs py-4 font-bold uppercase">Error.</p>';
            }
        }, 300);
    });

    // Monitor en Vivo (Existente)
    setInterval(async () => {
        if(document.hidden) return; // Optimización de batería
        try {
            const res = await fetch('db/live-business-monitor.php?check=1&t=' + Date.now());
            const data = await res.json();
            if(data.has_changes) {
                playNotificationSound();
                if(navigator.vibrate) navigator.vibrate([100,50,100]);
                setTimeout(() => location.reload(), 1000);
            }
        } catch(e) {
            console.error("Monitor error:", e);
        }
    }, 5000);

// --- LÓGICA MODAL GASTOS (Existente) ---
    // Agregamos una comprobación antes de adjuntar el listener
    const expenseForm = document.getElementById('expense-form');
    
    if (expenseForm) {
        
        function openExpenseModal() {
            const modal = document.getElementById('expense-modal');
            const content = document.getElementById('expense-modal-content');
            modal.classList.remove('hidden');
            setTimeout(() => {
                modal.classList.remove('opacity-0');
                content.classList.remove('translate-y-full');
            }, 10);
        }

        function closeExpenseModal() {
            const modal = document.getElementById('expense-modal');
            const content = document.getElementById('expense-modal-content');
            modal.classList.add('opacity-0');
            content.classList.add('translate-y-full');
            setTimeout(() => {
                modal.classList.add('hidden');
                expenseForm.reset();
                document.getElementById('preview-image').classList.add('hidden');
                document.getElementById('upload-placeholder').classList.remove('hidden');
            }, 300);
        }

        document.getElementById('receipt-input').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const img = document.getElementById('preview-image');
                    img.src = e.target.result;
                    img.classList.remove('hidden');
                    document.getElementById('upload-placeholder').classList.add('hidden');
                }
                reader.readAsDataURL(file);
            }
        });

        expenseForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            const btn = document.getElementById('btn-save-expense');
            const originalHtml = btn.innerHTML;
            
            btn.innerHTML = '<div class="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>';
            btn.disabled = true;
            btn.classList.add('opacity-75');

            const formData = new FormData(this);

            try {
                const res = await fetch('db/quick-expense-save.php', { // Asumiendo que esta es la ruta
                    method: 'POST',
                    body: formData
                });
                const data = await res.json();

                if(data.success) {
                    if(navigator.vibrate) navigator.vibrate(200);
                    alert('Gasto Guardado');
                    closeExpenseModal();
                } else {
                    alert('Error: ' + data.message);
                }
            } catch(err) {
                console.error(err);
                alert('Error de conexión');
            } finally {
                btn.innerHTML = originalHtml;
                btn.disabled = false;
                btn.classList.remove('opacity-75');
            }
        });
    }

    let docFormType = 'quote'; // Variable global para saber qué formulario mostrar/enviar

    function addItemRow(qty = 1, desc = '', price = 0) {
        const container = document.getElementById('items-list');
        const index = Date.now(); // ID único
        
        const itemHtml = `
            <div class="flex gap-2 items-start bg-gray-100 p-3 rounded-lg border border-gray-200 item-row" data-index="${index}">
                <div class="flex-1 space-y-1">
                    <label class="text-[9px] font-black text-gray-400 uppercase">Descripción</label>
                    <input type="text" name="item_desc_${index}" placeholder="Ej: Servicio de limpieza" value="${escapeHtml(desc)}" required
                        class="w-full text-xs font-bold uppercase p-2 border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-600 outline-none mb-1">
                    <div class="flex gap-2">
                        <div class="w-1/3">
                            <label class="text-[9px] font-black text-gray-400 uppercase">Cant.</label>
                            <input type="number" step="1" min="1" name="item_qty_${index}" placeholder="Qty" value="${qty}" required
                                class="w-full text-sm p-2 border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-600 outline-none text-center item-qty" oninput="calculateDocTotal()">
                        </div>
                        <div class="w-2/3">
                            <label class="text-[9px] font-black text-gray-400 uppercase">Precio Unitario</label>
                            <input type="number" step="0.01" min="0" name="item_price_${index}" placeholder="Precio" value="${price.toFixed(2)}" required
                                class="w-full text-sm p-2 border border-gray-300 rounded-lg focus:ring-1 focus:ring-blue-600 outline-none font-bold text-right item-price" oninput="calculateDocTotal()">
                        </div>
                    </div>
                </div>
                <button type="button" onclick="removeItemRow('${index}')" class="text-red-500 hover:text-red-700 p-2 active:scale-90 transition flex-shrink-0 mt-6">
                    <i data-lucide="trash-2" class="w-4 h-4"></i>
                </button>
            </div>
        `;
        container.insertAdjacentHTML('beforeend', itemHtml);
        lucide.createIcons();
        calculateDocTotal();
    }

    function removeItemRow(index) {
        const row = document.querySelector(`.item-row[data-index="${index}"]`);
        if (row) {
            row.style.transform = 'scale(0.9)';
            row.style.opacity = '0';
            setTimeout(() => {
                row.remove();
                calculateDocTotal();
            }, 300);
        }
    }

    function calculateDocTotal() {
        let total = 0;
        const rows = document.querySelectorAll('.item-row');
        
        rows.forEach(row => {
            const qty = parseFloat(row.querySelector('.item-qty').value) || 0;
            const price = parseFloat(row.querySelector('.item-price').value) || 0;
            total += (qty * price);
        });
        
        document.getElementById('doc-total-display').innerText = '$' + total.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    function openDocModal(type) {
        const modal = document.getElementById('doc-modal');
        const content = document.getElementById('doc-modal-content');
        const header = document.getElementById('doc-header');
        const title = document.getElementById('doc-title');
        const typeInput = document.getElementById('doc-type');
        const quoteContainer = document.getElementById('quote-items-container');
        const invoiceContainer = document.getElementById('invoice-simple-container');

        // Limpiar
        document.getElementById('doc-form').reset();
        document.getElementById('doc-client-id').value = '';
        document.getElementById('doc-client-search').value = '';
        document.getElementById('doc-search-results').classList.add('hidden');
        docFormType = type;

        // Configurar UI
        if(type === 'invoice') {
            header.className = 'bg-[var(--color-primary)] p-4 flex text-3xl justify-between items-center text-white';
            title.innerText = 'FACTURA';
            document.getElementById('doc-subtitle').innerText = 'Generación de Link de invoice';
            typeInput.value = 'invoice';
            quoteContainer.classList.add('hidden');
            invoiceContainer.classList.remove('hidden');
        } else { // type === 'quote'
            header.className = 'bg-[var(--color-primary)] p-4 flex text-3xl justify-between items-center text-white';
            title.innerText = 'NUEVO ESTIMADO';
            document.getElementById('doc-subtitle').innerText = 'Agrega múltiples conceptos';
            typeInput.value = 'quote';
            invoiceContainer.classList.add('hidden');
            quoteContainer.classList.remove('hidden');

            document.getElementById('items-list').innerHTML = '';
            addItemRow();
        }

        modal.classList.remove('hidden');
        setTimeout(() => {
            modal.classList.remove('opacity-0');
            content.classList.remove('translate-y-full');
        }, 10);
        document.getElementById('doc-client-search').focus();
    }

    function closeDocModal() {
        const modal = document.getElementById('doc-modal');
        const content = document.getElementById('doc-modal-content');
        modal.classList.add('opacity-0');
        content.classList.add('translate-y-full');
        setTimeout(() => modal.classList.add('hidden'), 300);
    }

    const docSearchInput = document.getElementById('doc-client-search');
    const docResults = document.getElementById('doc-search-results');

    docSearchInput.addEventListener('input', function(e) {
        clearTimeout(debounceTimer); 
        const term = e.target.value.trim();
        
        if(term.length < 2) {
            docResults.classList.add('hidden');
            return;
        }

        debounceTimer = setTimeout(async () => {
            try {
                const res = await fetch(`db/contact-search.php?q=${encodeURIComponent(term)}`);
                const data = await res.json();
                const results = Array.isArray(data) ? data : (data.results || []);
                
                docResults.innerHTML = '';
                
                if(results.length > 0) {
                    docResults.classList.remove('hidden');
                    results.forEach(c => {
                        const div = document.createElement('div');
                        div.className = 'p-3 hover:bg-gray-100 cursor-pointer border-b border-gray-50';
                        div.innerHTML = `<p class="font-bold text-sm uppercase text-gray-800">${escapeHtml(c.label)}</p>
                                        <p class="text-xs text-gray-400">${escapeHtml(c.sub_text)}</p>`;
                        
                        div.onclick = () => {
                            document.getElementById('doc-client-search').value = c.label;
                            document.getElementById('doc-client-id').value = c.id;
                            docResults.classList.add('hidden');
                        };
                        docResults.appendChild(div);
                    });
                } else {
                    docResults.classList.add('hidden');
                }
            } catch(err) {
                console.error(err);
                docResults.classList.add('hidden');
            }
        }, 300);
    });

    // Enviar Formulario Documentos (ACTUALIZADO para manejar Items)
    document.getElementById('doc-form').addEventListener('submit', async function(e) {
        e.preventDefault();
        
        if (document.getElementById('doc-client-id').value === '' || document.getElementById('doc-client-search').value.trim() === '') {
            alert('Debes seleccionar un cliente válido.');
            return;
        }
        
        const btn = document.getElementById('btn-create-doc');
        const originalText = btn.innerHTML;
        
        btn.disabled = true;
        btn.innerHTML = '<div class="w-5 h-5 border-2 border-white border-t-transparent rounded-full animate-spin"></div>';
        btn.classList.add('opacity-75');

        let payload = {};
        let apiUrl = '';
        const client_id = document.getElementById('doc-client-id').value;


        if(docFormType === 'quote') {
            const items = [];
            let validItems = 0;
            document.querySelectorAll('.item-row').forEach(row => {
                const index = row.dataset.index;
                const description = document.querySelector(`[name="item_desc_${index}"]`).value.trim();
                const quantity = parseFloat(document.querySelector(`[name="item_qty_${index}"]`).value) || 0;
                const price = parseFloat(document.querySelector(`[name="item_price_${index}"]`).value) || 0;

                if (description && quantity > 0 && price >= 0) {
                    items.push({ description, quantity, price });
                    validItems++;
                }
            });

            if (validItems === 0) {
                alert('Debes agregar al menos un ítem con cantidad y precio válidos.');
                btn.innerHTML = originalText;
                btn.disabled = false;
                btn.classList.remove('opacity-75');
                return;
            }

            payload = { 
                client_id: client_id,
                items: items 
            };
            apiUrl = 'db/app-quick-create.php'; 
        
        } else { 
            
            const description = this.querySelector('[name="description"]').value.trim();
            const amount = parseFloat(this.querySelector('[name="amount"]').value) || 0;

            if (description === '' || amount <= 0) {
                alert('Falta concepto o monto en la factura.');
                btn.innerHTML = originalText;
                btn.disabled = false;
                btn.classList.remove('opacity-75');
                return;
            }

            const formData = new FormData();
            formData.append('type', docFormType);
            formData.append('client_id', client_id);
            formData.append('description', description);
            formData.append('amount', amount);

            try {
                const res = await fetch('db/quick-create.php', {
                    method: 'POST',
                    body: formData
                });
                const data = await res.json();

                if(data.success) {
                    closeDocModal();
                    const shareModal = document.getElementById('share-modal');
                    const waBtn = document.getElementById('wa-share-btn');
                    waBtn.href = `https://wa.me/?text=${encodeURIComponent(data.wa_text)}`;
                    shareModal.classList.remove('hidden');
                    setTimeout(() => shareModal.classList.remove('opacity-0'), 10);
                } else {
                    alert('Error: ' + data.message);
                }
            } catch(err) {
                console.error(err);
                alert('Error de conexión');
            } finally {
                btn.innerHTML = originalText;
                btn.disabled = false;
                btn.classList.remove('opacity-75');
            }
            return; 
        }


        // Lógica de envío JSON para Estimados (quote)
        try {
            const res = await fetch(apiUrl, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await res.json();

            if(data.success) {
                closeDocModal();
                const shareModal = document.getElementById('share-modal');
                const waBtn = document.getElementById('wa-share-btn');
                
                waBtn.href = `https://wa.me/?text=${encodeURIComponent(data.wa_text)}`;
                
                shareModal.classList.remove('hidden');
                setTimeout(() => shareModal.classList.remove('opacity-0'), 10);
            } else {
                alert('Error: ' + data.message);
            }
        } catch(err) {
            console.error(err);
            alert('Error de conexión al generar estimado.');
        } finally {
            btn.innerHTML = originalText;
            btn.disabled = false;
            btn.classList.remove('opacity-75');
        }
    });

    function closeShareModal() {
        const modal = document.getElementById('share-modal');
        modal.classList.add('opacity-0');
        setTimeout(() => modal.classList.add('hidden'), 300);
    }
    
    lucide.createIcons();
    switchTab('empleados');
</script>
<script src="files/toast.js"></script>
</html>