<?php
/**
 * Sidebar del Client Portal con el mismo diseño del menú compartido
 * Usa las clases de style.css (.sidebar, .nav-list, .nav-link, etc.)
 */
// Preparar datos básicos del cliente
$clientName = ($_SESSION['client_first_name'] ?? '') . ' ' . ($_SESSION['client_last_name'] ?? '');
if (trim($clientName) === '') { $clientName = 'Cliente'; }

// Obtener gestor de cuentas asignado al cliente o su lead
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

$manager = null;
try {
    $db = Database::getInstance();
    $pdo = $db->getConnection();
    $clientId = $_SESSION['client_id'] ?? null;
    if ($clientId) {
        $stmtC = $pdo->prepare('SELECT id, assigned_to, lead_id FROM clients WHERE id = ? LIMIT 1');
        $stmtC->execute([$clientId]);
        $clientRow = $stmtC->fetch();
        $assignedUserId = null;
        if ($clientRow) {
            if (!empty($clientRow['assigned_to'])) {
                $assignedUserId = (int)$clientRow['assigned_to'];
            } elseif (!empty($clientRow['lead_id'])) {
                $stmtL = $pdo->prepare('SELECT assigned_to FROM leads WHERE id = ? LIMIT 1');
                $stmtL->execute([$clientRow['lead_id']]);
                $assignedUserId = (int)$stmtL->fetchColumn();
            }
        }
        if ($assignedUserId) {
            $stmtU = $pdo->prepare('SELECT first_name, last_name, email FROM users WHERE id = ? LIMIT 1');
            $stmtU->execute([$assignedUserId]);
            $manager = $stmtU->fetch();
        }
    }
} catch (Throwable $e) {
    // Silenciar errores en sidebar para no romper la UI
}

if (!$manager) {
    $manager = [
        'first_name' => 'Alex',
        'last_name' => 'Gómez',
        'email' => 'manager@example.com'
    ];
}
?>

<aside class="sidebar" id="sidebar">
    <div class="sidebar-header">
        <a class="sidebar-logo" href="<?php echo module_url('client_portal/dashboard.php'); ?>">
            <div class="logo-icon">
                <?php
                // Obtener nombre y logo desde configuración
                $company_name = 'ProfixCRM';
                $company_logo = '';
                try {
                    if (isset($pdo)) {
                        $stmt = $pdo->prepare("SELECT config_key, config_value FROM system_config WHERE config_key IN ('company_name','company_logo')");
                        $stmt->execute();
                        $config_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($config_items as $item) {
                            if ($item['config_key'] === 'company_name' && !empty($item['config_value'])) {
                                $company_name = $item['config_value'];
                            } elseif ($item['config_key'] === 'company_logo' && !empty($item['config_value'])) {
                                $company_logo = $item['config_value'];
                            }
                        }
                    }
                } catch (Exception $e) {
                    $company_logo = '';
                }
                $logo_path_disk = BASE_PATH . '/public/uploads/' . $company_logo;
                $has_logo = !empty($company_logo) && file_exists($logo_path_disk);
                ?>
                <?php if ($has_logo): ?>
                    <img src="<?php echo asset('public/uploads/' . htmlspecialchars($company_logo)); ?>" alt="<?php echo htmlspecialchars($company_name); ?>">
                <?php else: ?>
                    <img src="<?php echo asset('public/branding/profix_logo.svg'); ?>" alt="<?php echo htmlspecialchars($company_name); ?>">
                <?php endif; ?>
            </div>
        </a>
    </div>

    <nav class="sidebar-nav">
        <ul class="nav-list">
            <li class="nav-item">
                <a href="<?php echo module_url('client_portal/dashboard.php'); ?>" class="nav-link <?php echo (basename($_SERVER['PHP_SELF']) === 'dashboard.php') ? 'active' : ''; ?>">
                    <div class="nav-icon premium dashboard"><i class="fas fa-gauge-high"></i></div>
                    <span class="nav-text">Dashboard</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="<?php echo module_url('client_portal/transactions.php'); ?>" class="nav-link <?php echo (basename($_SERVER['PHP_SELF']) === 'transactions.php') ? 'active' : ''; ?>">
                    <div class="nav-icon premium transactions"><i class="fas fa-receipt"></i></div>
                    <span class="nav-text">Transacciones</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="<?php echo module_url('client_portal/documents.php'); ?>" class="nav-link <?php echo (basename($_SERVER['PHP_SELF']) === 'documents.php') ? 'active' : ''; ?>">
                    <div class="nav-icon premium documents"><i class="fas fa-folder-open"></i></div>
                    <span class="nav-text">Documentos</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="<?php echo module_url('client_portal/tickets.php'); ?>" class="nav-link <?php echo (basename($_SERVER['PHP_SELF']) === 'tickets.php') ? 'active' : ''; ?>">
                    <div class="nav-icon premium support"><i class="fas fa-headset"></i></div>
                    <span class="nav-text">Soporte</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="<?php echo module_url('client_portal/profile.php'); ?>" class="nav-link <?php echo (basename($_SERVER['PHP_SELF']) === 'profile.php') ? 'active' : ''; ?>">
                    <div class="nav-icon premium profile"><i class="fas fa-id-card"></i></div>
                    <span class="nav-text">Perfil</span>
                </a>
            </li>
            <li class="nav-item">
                <a href="<?php echo module_url('client_portal/settings.php'); ?>" class="nav-link <?php echo (basename($_SERVER['PHP_SELF']) === 'settings.php') ? 'active' : ''; ?>">
                    <div class="nav-icon premium settings"><i class="fas fa-sliders-h"></i></div>
                    <span class="nav-text">Configuración</span>
                </a>
            </li>
        </ul>
    </nav>
    <style>
      .sidebar .nav-list{display:grid;gap:8px}
      .sidebar .nav-list .nav-link{display:flex;align-items:center;gap:12px;border-radius:14px;padding:12px 14px;border:1px solid transparent;transition:transform .12s ease, box-shadow .18s ease, border-color .18s ease, background .18s ease}
      .sidebar .nav-list .nav-link:hover{transform:translateX(2px);box-shadow:0 10px 22px rgba(0,0,0,.08);background:#f9fafb;border-color:#eef2f7}
      .sidebar .nav-list .nav-link.active{background:linear-gradient(180deg,#f8fafc,#eef2ff);border:1px solid #e0e7ff;box-shadow:0 10px 22px rgba(99,102,241,.12)}
      .sidebar .nav-list .nav-icon.premium{width:40px;height:40px;min-width:40px;border-radius:14px;display:flex;align-items:center;justify-content:center;color:#fff;box-shadow:0 8px 18px rgba(0,0,0,.14);transition:transform .12s ease, filter .12s ease}
      .sidebar .nav-list .nav-icon.premium.dashboard{background:linear-gradient(135deg,#60a5fa,#2563eb)}
      .sidebar .nav-list .nav-icon.premium.transactions{background:linear-gradient(135deg,#22c55e,#16a34a)}
      .sidebar .nav-list .nav-icon.premium.documents{background:linear-gradient(135deg,#a78bfa,#7c3aed)}
      .sidebar .nav-list .nav-icon.premium.support{background:linear-gradient(135deg,#f59e0b,#d97706)}
      .sidebar .nav-list .nav-icon.premium.profile{background:linear-gradient(135deg,#14b8a6,#0d9488)}
      .sidebar .nav-list .nav-icon.premium.settings{background:linear-gradient(135deg,#94a3b8,#64748b)}
      .sidebar .nav-list .nav-link:hover .nav-icon.premium{filter:brightness(1.06);transform:scale(1.04)}
      .sidebar .nav-list .nav-text{font-weight:700;color:#1f2937}
      .sidebar .nav-list .nav-link.active .nav-text{color:#0f172a}
      .sidebar .nav-list .nav-link:focus-visible{outline:3px solid #93c5fd;outline-offset:2px}
    </style>
    <?php if ($manager): ?>
    <div class="client-manager-card" id="managerCard">
        <div class="client-manager-header">
            <div class="client-manager-avatar">
                <?php 
                $fn = trim($manager['first_name'] ?? '');
                $ln = trim($manager['last_name'] ?? '');
                $i1 = function_exists('mb_substr') ? mb_substr($fn,0,1) : substr($fn,0,1);
                $i2 = function_exists('mb_substr') ? mb_substr($ln,0,1) : substr($ln,0,1);
                $initials = strtoupper(($i1 ?: '') . ($i2 ?: ''));
                if ($initials === '') { $initials = '?'; }
                echo htmlspecialchars($initials);
                ?>
            </div>
            <div class="client-manager-info">
                <h4>Gestor de Cuentas</h4>
                <p><?php echo htmlspecialchars(($manager['first_name'] ?? '') . ' ' . ($manager['last_name'] ?? '')); ?></p>
            </div>
        </div>
        <div class="client-manager-contact">
            <button type="button" class="client-contact-btn" id="openChatBtn"><i class="fas fa-comments"></i> Chat</button>
        </div>
    </div>
    <div class="client-logout-bar">
        <a href="<?php echo module_url('client_portal/logout.php'); ?>" class="client-contact-btn logout-btn"><i class="fas fa-right-from-bracket"></i> Cerrar sesión</a>
    </div>
    <div class="chat-overlay" id="chatOverlay" style="display:none"></div>
    <div class="chat-modal" id="chatModal" style="display:none">
        <div class="chat-window">
            <div class="chat-header">
                <strong>Chat con tu gestor</strong>
                <button type="button" class="chat-close" id="chatCloseBtn">×</button>
            </div>
            <div class="chat-body" id="chatMessages"></div>
            <div class="chat-input">
                <form id="chatForm">
                    <input type="text" id="chatMessage" placeholder="Escribe tu mensaje" required />
                    <button type="submit" class="client-action-btn">Enviar</button>
                </form>
            </div>
        </div>
    </div>
    <script>
    (function(){
      var openBtn = document.getElementById('openChatBtn');
      var overlay = document.getElementById('chatOverlay');
      var modal = document.getElementById('chatModal');
      var closeBtn = document.getElementById('chatCloseBtn');
      var msgs = document.getElementById('chatMessages');
      var form = document.getElementById('chatForm');
      var input = document.getElementById('chatMessage');
      var base = window.APP_BASE_PATH || '';
      function open(){ overlay.style.display='block'; modal.style.display='block'; load(); }
      function close(){ overlay.style.display='none'; modal.style.display='none'; }
      function render(list){
        msgs.innerHTML='';
        for (var i=0;i<list.length;i++){
          var m=list[i];
          var div=document.createElement('div');
          div.className='chat-msg '+(m.sender_type==='client'?'from-client':'from-manager');
          var t=document.createElement('div');
          t.className='chat-text';
          t.textContent=m.message;
          var d=document.createElement('div');
          d.className='chat-time';
          d.textContent=m.created_at;
          div.appendChild(t); div.appendChild(d);
          msgs.appendChild(div);
        }
        msgs.scrollTop = msgs.scrollHeight;
      }
      function load(){
        fetch(base + '/api/client_chat.php?action=history')
          .then(function(r){return r.json()})
          .then(function(j){ 
            if (j && j.success) { render(j.messages||[]); }
            else { msgs.innerHTML = '<div class="chat-msg"><div class="chat-text">No hay gestor asignado actualmente.</div></div>'; }
          })
          .catch(function(_){ msgs.innerHTML = '<div class="chat-msg"><div class="chat-text">No se pudo cargar el chat.</div></div>'; });
      }
      if (openBtn){ openBtn.onclick=open; }
      if (closeBtn){ closeBtn.onclick=close; }
      if (overlay){ overlay.onclick=close; }
      if (form){
        form.addEventListener('submit', function(ev){
          ev.preventDefault();
          var msg = input.value.trim();
          if (!msg) return;
          fetch(base + '/api/client_chat.php', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'action=send&message='+encodeURIComponent(msg) })
            .then(function(r){return r.json()})
            .then(function(j){ if (j && j.success) { input.value=''; render(j.messages||[]); } else { msgs.innerHTML += '<div class="chat-msg"><div class="chat-text">No se pudo enviar: '+(j&&j.message?j.message:'')+'</div></div>'; } })
            .catch(function(){ msgs.innerHTML += '<div class="chat-msg"><div class="chat-text">Error de red al enviar.</div></div>'; });
        });
      }
    })();
    </script>
    <?php endif; ?>
</aside>
