<?php if (!isset($page_title)) { $page_title = "Portal"; } ?>
<?php if (!isset($active)) { $active = ''; } ?>
<?php if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); } ?>
<?php require_once BASE_PATH . '/modules/shared/helpers.php'; ?>
<?php require_once BASE_PATH . '/database/config.php'; ?>
<?php require_once BASE_PATH . '/database/connection.php'; ?>
<?php
// Presencia inmediata en carga de vista (server-side)
if (isset($_SESSION['client_id'])) {
    try {
        $dbp = Database::getInstance();
        $pdop = $dbp->getConnection();
        try { $pdop->query("SHOW COLUMNS FROM clients LIKE 'last_seen'"); }
        catch (Throwable $__) { $pdop->exec("ALTER TABLE clients ADD COLUMN last_seen DATETIME NULL"); }
        $pdop->prepare('UPDATE clients SET last_seen = NOW() WHERE id = ?')->execute([ (int)$_SESSION['client_id'] ]);
        $pdop->prepare('CREATE TABLE IF NOT EXISTS client_presence (client_id INT PRIMARY KEY, last_seen DATETIME NULL, source VARCHAR(20) NULL, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (client_id) REFERENCES clients(id) ON DELETE CASCADE)')->execute();
        $pdop->prepare('INSERT INTO client_presence (client_id,last_seen,source,updated_at) VALUES (?,?,"portal",NOW()) ON DUPLICATE KEY UPDATE last_seen=VALUES(last_seen), source=VALUES(source), updated_at=NOW()')->execute([ (int)$_SESSION['client_id'], date('Y-m-d H:i:s') ]);
    } catch (Throwable $__) {}
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?> - Trader Room</title>
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/client_portal.css'); ?>">
    <script src="<?php echo asset('public/basepath.js'); ?>"></script>
</head>
<body class="layout">
    <!-- Botón de menú móvil -->
    <button class="mobile-menu-toggle" aria-label="Abrir menú" aria-controls="sidebar" aria-expanded="false">
        <i class="fas fa-bars"></i>
    </button>
    <section class="topbar">
        <div class="brand">
            <a href="<?php echo module_url('client_portal/dashboard.php'); ?>" class="brand-logo">TR</a>
            <a href="<?php echo module_url('client_portal/dashboard.php'); ?>" class="brand-title">Trader Room</a>
        </div>
        <nav class="menu">
            <a href="<?php echo module_url('client_portal/dashboard.php'); ?>" class="menu-link <?php echo $active === 'home' ? 'active' : ''; ?>">Inicio</a>
            <div class="dropdown">
                <button class="dropdown-toggle">Más</button>
                <div class="dropdown-menu">
                    <a href="<?php echo module_url('client_portal/tickets.php'); ?>" class="dropdown-item">Soporte</a>
                    <a href="<?php echo module_url('client_portal/documents.php'); ?>" class="dropdown-item">Documentos</a>
                </div>
            </div>
        </nav>
    </section>

    <main class="content">
        <?php include __DIR__ . '/sidebar.php'; ?>
        <!-- Overlay para móvil -->
        <div class="sidebar-overlay" id="sidebarOverlay"></div>
        <section class="main">
            <?php if (isset($content)) { echo $content; } ?>
        </section>
    </main>

    <footer class="footer">
        <p>© <?php echo date('Y'); ?> Trader Room</p>
    </footer>

    <script src="<?php echo asset('public/script.js'); ?>"></script>
    <script src="https://kit.fontawesome.com/a2e0a6ad53.js" crossorigin="anonymous"></script>
    <script>
    (function(){
      function ping(){ fetch('<?php echo module_url('api/client_presence.php'); ?>', { method:'POST' }).catch(function(){}); }
      ping();
      setInterval(ping, 60000);
    })();
    </script>
    <script>
    (function(){
      var p=new URLSearchParams(window.location.search);
      if(p.get('message')==='profile_updated'){
        var note=p.get('note')||'';
        var text='Perfil actualizado correctamente';
        if(note==='email_conflict'){ text+=' · El email ya existe, se mantuvo el original'; }
        var el=document.createElement('div');
        el.style.position='fixed'; el.style.right='16px'; el.style.top='16px'; el.style.zIndex='3000'; el.style.background='#dcfce7'; el.style.color='#166534'; el.style.padding='10px 12px'; el.style.borderRadius='10px'; el.style.boxShadow='0 10px 20px rgba(0,0,0,.12)'; el.textContent=text;
        document.body.appendChild(el);
        setTimeout(function(){ if(el&&el.remove) el.remove(); }, 4500);
        var qs = window.location.search.replace(/([?&])message=[^&]*(&|$)/,'$1').replace(/([?&])note=[^&]*(&|$)/,'$1');
        qs = qs.replace(/[?&]$/,'');
        var newUrl = window.location.pathname + (qs?qs:'');
        history.replaceState(null,'',newUrl);
      }
      if(p.get('error')){
        var text='Error al guardar el perfil';
        var detail=p.get('detail')||'';
        if(detail){ text+=' · '+decodeURIComponent(detail).replace(/\|/g,' · '); }
        var el=document.createElement('div');
        el.style.position='fixed'; el.style.right='16px'; el.style.top='16px'; el.style.zIndex='3000'; el.style.background='#fee2e2'; el.style.color='#7f1d1d'; el.style.padding='10px 12px'; el.style.borderRadius='10px'; el.style.boxShadow='0 10px 20px rgba(0,0,0,.12)'; el.textContent=text;
        document.body.appendChild(el);
        setTimeout(function(){ if(el&&el.remove) el.remove(); }, 6000);
        var qs = window.location.search.replace(/([?&])error=[^&]*(&|$)/,'$1').replace(/([?&])detail=[^&]*(&|$)/,'$1');
        qs = qs.replace(/[?&]$/,'');
        var newUrl = window.location.pathname + (qs?qs:'');
        history.replaceState(null,'',newUrl);
      }
    })();
    </script>
    <?php
    // Asistente guiado de perfil: mostrar si faltan datos requeridos
    if (isset($_SESSION['client_id'])) {
        $cid = (int)$_SESSION['client_id'];
        try {
            $dbx = Database::getInstance();
            $pdoX = $dbx->getConnection();
            $want = ['email','first_name','last_name','phone','address_line','country','phone_country_code','state','province','city','postal_code','district','document_number'];
            $have = [];
            foreach ($want as $col) {
                try {
                    $chk = $pdoX->prepare("SHOW COLUMNS FROM clients LIKE ?");
                    $chk->execute([$col]);
                    if ($chk->fetch()) { $have[] = $col; }
                } catch (Throwable $__) {}
            }
            $selectCols = [];
            foreach ($have as $c) { $selectCols[] = "COALESCE($c,'') AS $c"; }
            if (empty($selectCols)) { $row = ['email'=>'','first_name'=>'','last_name'=>'','phone'=>'','address_line'=>'','country'=>'','phone_country_code'=>'','document_number'=>'']; }
            else {
                $sql = "SELECT " . implode(', ', $selectCols) . " FROM clients WHERE id = ? LIMIT 1";
                $st = $pdoX->prepare($sql);
                $st->execute([$cid]);
                $row = $st->fetch(PDO::FETCH_ASSOC) ?: [];
            }
            $defaults = ['email'=>'','first_name'=>'','last_name'=>'','phone'=>'','address_line'=>'','country'=>'','phone_country_code'=>'','state'=>'','province'=>'','city'=>'','postal_code'=>'','district'=>'','document_number'=>''];
            $row = array_merge($defaults, $row);
            $req = ['email','first_name','last_name','phone','address_line','country','phone_country_code','document_number'];
            // Solo validar campos requeridos que existan en la tabla
            $existingReq = array_values(array_intersect($req, $have));
            $missing = [];
            foreach ($existingReq as $k) { if (empty($row[$k])) { $missing[] = $k; } }
            // Requisito principal: país debe estar definido; si la columna no existe, considerarlo como faltante
            $countryMissing = (!in_array('country', $have) || empty($row['country']));
            // Si se acaba de actualizar el perfil, no mostrar el modal en este reload
            $justUpdated = isset($_GET['message']) && $_GET['message'] === 'profile_updated';
            if (!$justUpdated && ($countryMissing || !empty($missing))) {
                ?>
                <div id="profileWizardModal" class="modal" style="display:block; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); z-index:2200; width:820px; max-width:96vw;">
                  <div class="modal-content" style="position:relative; width:100%; background:var(--bg-primary); border:1px solid var(--border-light); border-radius:16px; box-shadow:0 20px 40px rgba(0,0,0,.12); animation: fadeInUp .28s cubic-bezier(0.4,0,0.2,1); display:flex; flex-direction:column;">
                    <div class="modal-header" style="display:flex; align-items:center; justify-content:space-between; padding:14px 16px; border-bottom:1px solid var(--border-light); background:linear-gradient(180deg,#f8fafc,#ffffff)">
                      <h3 style="margin:0; font-size:1.12rem; color:var(--text-primary)">Completar perfil</h3>
                      <button type="button" class="close-modal js-close-profile" aria-label="Cerrar" style="border:0; background:transparent; font-size:22px; color:var(--text-muted); padding:4px 8px">&times;</button>
                    </div>
                    <div class="modal-body" style="padding:0;">
                      <form id="profileWizardForm" method="post" action="<?php echo module_url('client_portal/api/update_profile.php'); ?>" enctype="multipart/form-data" style="display:flex; flex-direction:column; height:100%">
                        <div style="padding:12px 16px; border-bottom:1px solid var(--border-light)">
                          <div style="height:6px; background:var(--bg-tertiary); border-radius:8px; overflow:hidden"><div id="pwProgress" style="height:100%; width:25%; background:linear-gradient(90deg,#3b82f6,#1e40af)"></div></div>
                          <div style="display:flex; gap:8px; margin-top:6px; color:var(--text-muted)">
                            <span id="stepLabel">Paso 1 de 4 · Identidad</span>
                          </div>
                        </div>
                        <div id="pwSteps" style="padding:14px 16px; display:grid; gap:14px">
                          <section data-step="1" style="display:block">
                            <div class="form-group" style="display:grid; grid-template-columns:1fr 1fr; gap:10px">
                              <div><label>Nombre</label><input type="text" name="first_name" value="<?php echo htmlspecialchars($row['first_name'] ?? ''); ?>" class="search-input" required></div>
                              <div><label>Apellido</label><input type="text" name="last_name" value="<?php echo htmlspecialchars($row['last_name'] ?? ''); ?>" class="search-input" required></div>
                            </div>
                            <div class="form-group" style="display:grid; grid-template-columns:1fr 1fr; gap:10px">
                              <div><label>Documento personal (número)</label><input type="text" name="document_number" value="<?php echo htmlspecialchars($row['document_number'] ?? ''); ?>" class="search-input" required></div>
                              <div><label>Adjuntar documento</label><input type="file" name="document_file" class="search-input" accept="image/*,application/pdf"></div>
                            </div>
                          </section>

                          <section data-step="2" style="display:none">
                            <div class="form-group" style="display:grid; grid-template-columns:1fr 1fr; gap:10px">
                              <div><label>Email (inicio de sesión)</label><input type="email" name="email" value="<?php echo htmlspecialchars($_SESSION['client_email'] ?? ($row['email'] ?? '')); ?>" class="search-input" required readonly></div>
                              <div><label>Teléfono</label><input type="text" name="phone" value="<?php echo htmlspecialchars($row['phone'] ?? ''); ?>" class="search-input" required></div>
                            </div>
                            <div class="form-group"><label>Dirección</label><input type="text" name="address_line" value="<?php echo htmlspecialchars($row['address_line'] ?? ''); ?>" class="search-input" required></div>
                          </section>

                          <section data-step="3" style="display:none">
                            <div class="form-group" style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px">
                              <div>
                                <label>País</label>
                                <div class="country-select" style="position:relative">
                                  <input type="text" id="countryInput" name="country" value="<?php echo htmlspecialchars($row['country'] ?? ''); ?>" class="search-input" placeholder="Buscar país" autocomplete="off" required>
                                  <div id="countryDropdown" style="position:absolute; top:100%; left:0; right:0; background:var(--bg-primary); border:1px solid var(--border-light); border-radius:12px; box-shadow:var(--shadow-md); max-height:240px; overflow:auto; display:none; z-index:50; padding:6px"></div>
                                </div>
                              </div>
                              <div><label>Código país (tel.)</label><input type="text" id="phoneCodeInput" name="phone_country_code" value="<?php echo htmlspecialchars($row['phone_country_code'] ?? ''); ?>" class="search-input" required></div>
                              <div><label>Número país</label><input type="text" name="country_code" id="countryCodeDisplay" value="" class="search-input" readonly></div>
                            </div>
                            <div class="form-group" style="display:grid; grid-template-columns:repeat(3,1fr); gap:10px">
                              <div><label>Estado/Provincia</label><input type="text" name="state" value="<?php echo htmlspecialchars($row['state'] ?? ''); ?>" class="search-input"></div>
                              <div><label>Ciudad</label><input type="text" name="city" value="<?php echo htmlspecialchars($row['city'] ?? ''); ?>" class="search-input"></div>
                              <div><label>Código Postal</label><input type="text" name="postal_code" value="<?php echo htmlspecialchars($row['postal_code'] ?? ''); ?>" class="search-input"></div>
                            </div>
                            <div class="form-group"><label>Barrio</label><input type="text" name="district" value="<?php echo htmlspecialchars($row['district'] ?? ''); ?>" class="search-input"></div>
                          </section>

                          <section data-step="4" style="display:none">
                            <div class="support-card">
                              <p style="margin:0 0 8px 0; color:var(--text-muted)">Revisa que la información esté correcta antes de guardar.</p>
                              <ul style="margin:0; padding-left:18px; color:var(--text-secondary)">
                                <li>Nombre y Apellido</li>
                                <li>Email y Teléfono</li>
                                <li>Dirección y País</li>
                                <li>Documento</li>
                              </ul>
                            </div>
                          </section>
                        </div>
                        <div class="filter-actions" style="display:flex; gap:12px; justify-content:space-between; padding:12px 16px; border-top:1px solid var(--border-light)">
                          <div>
                            <button type="button" id="pwPrev" class="btn-secondary btn-size-md">Anterior</button>
                          </div>
                          <div>
                            <button type="button" id="pwNext" class="btn-primary btn-size-md">Siguiente</button>
                            <button type="submit" id="pwSubmit" class="btn-success btn-size-md" style="display:none">Guardar perfil</button>
                          </div>
                        </div>
                      </form>
                    </div>
                  </div>
                </div>
                <script>
                (function(){
                  var current = 1, total = 4;
                  var steps = document.querySelectorAll('#pwSteps [data-step]');
                  var prevBtn = document.getElementById('pwPrev');
                  var nextBtn = document.getElementById('pwNext');
                  var submitBtn = document.getElementById('pwSubmit');
                  var progress = document.getElementById('pwProgress');
                  var stepLabel = document.getElementById('stepLabel');
                  function showStep(n){
                    steps.forEach(function(s){ s.style.display = (Number(s.getAttribute('data-step'))===n)?'block':'none'; });
                    prevBtn.style.visibility = (n>1)?'visible':'hidden';
                    nextBtn.style.display = (n<total)?'inline-block':'none';
                    submitBtn.style.display = (n===total)?'inline-block':'none';
                    progress.style.width = (n/total*100)+'%';
                    var labels = ['Identidad','Contacto','Ubicación','Revisión'];
                    stepLabel.textContent = 'Paso '+n+' de '+total+' · '+labels[n-1];
                  }
                  function validateStep(n){
                    var container = document.querySelector('#pwSteps [data-step="'+n+'"]');
                    if (!container) return true;
                    var required = container.querySelectorAll('input[required]');
                    for (var i=0;i<required.length;i++){ if (!required[i].value.trim()){ required[i].focus(); return false; } }
                    return true;
                  }
                  prevBtn.addEventListener('click', function(){ if (current>1){ current--; showStep(current); } });
                  nextBtn.addEventListener('click', function(){ if (validateStep(current)){ if (current<total){ current++; showStep(current); } } });
                  showStep(current);

                  // Country premium selector
                  var countries = [
                    {code:'US',name:'Estados Unidos',flag:'🇺🇸',phone:'+1'},
                    {code:'ES',name:'España',flag:'🇪🇸',phone:'+34'},
                    {code:'MX',name:'México',flag:'🇲🇽',phone:'+52'},
                    {code:'AR',name:'Argentina',flag:'🇦🇷',phone:'+54'},
                    {code:'CL',name:'Chile',flag:'🇨🇱',phone:'+56'},
                    {code:'CO',name:'Colombia',flag:'🇨🇴',phone:'+57'},
                    {code:'PE',name:'Perú',flag:'🇵🇪',phone:'+51'},
                    {code:'BR',name:'Brasil',flag:'🇧🇷',phone:'+55'},
                    {code:'UY',name:'Uruguay',flag:'🇺🇾',phone:'+598'},
                    {code:'PY',name:'Paraguay',flag:'🇵🇾',phone:'+595'},
                    {code:'BO',name:'Bolivia',flag:'🇧🇴',phone:'+591'},
                    {code:'EC',name:'Ecuador',flag:'🇪🇨',phone:'+593'},
                    {code:'VE',name:'Venezuela',flag:'🇻🇪',phone:'+58'},
                    {code:'CA',name:'Canadá',flag:'🇨🇦',phone:'+1'},
                    {code:'GB',name:'Reino Unido',flag:'🇬🇧',phone:'+44'},
                    {code:'DE',name:'Alemania',flag:'🇩🇪',phone:'+49'},
                    {code:'FR',name:'Francia',flag:'🇫🇷',phone:'+33'},
                    {code:'IT',name:'Italia',flag:'🇮🇹',phone:'+39'},
                    {code:'PT',name:'Portugal',flag:'🇵🇹',phone:'+351'},
                    {code:'NL',name:'Países Bajos',flag:'🇳🇱',phone:'+31'},
                    {code:'IE',name:'Irlanda',flag:'🇮🇪',phone:'+353'},
                    {code:'SE',name:'Suecia',flag:'🇸🇪',phone:'+46'},
                    {code:'NO',name:'Noruega',flag:'🇳🇴',phone:'+47'},
                    {code:'DK',name:'Dinamarca',flag:'🇩🇰',phone:'+45'},
                    {code:'FI',name:'Finlandia',flag:'🇫🇮',phone:'+358'},
                    {code:'CH',name:'Suiza',flag:'🇨🇭',phone:'+41'},
                    {code:'AT',name:'Austria',flag:'🇦🇹',phone:'+43'},
                    {code:'BE',name:'Bélgica',flag:'🇧🇪',phone:'+32'},
                    {code:'PL',name:'Polonia',flag:'🇵🇱',phone:'+48'},
                    {code:'CZ',name:'Chequia',flag:'🇨🇿',phone:'+420'},
                    {code:'HU',name:'Hungría',flag:'🇭🇺',phone:'+36'},
                    {code:'RO',name:'Rumanía',flag:'🇷🇴',phone:'+40'}
                  ];
                  var cInput = document.getElementById('countryInput');
                  var dd = document.getElementById('countryDropdown');
                  var phoneCodeInput = document.getElementById('phoneCodeInput');
                  var ccDisplay = document.getElementById('countryCodeDisplay');
                  // No establecer valores por defecto si país está vacío
                  if (!cInput.value) { phoneCodeInput.value = ''; ccDisplay.value = ''; }
                  var activeIndex = -1;
                  function highlight(text, query){
                    if (!query) return text;
                    var i = text.toLowerCase().indexOf(query.toLowerCase());
                    if (i<0) return text;
                    return text.substring(0,i) + '<strong>' + text.substring(i,i+query.length) + '</strong>' + text.substring(i+query.length);
                  }
                  function renderList(filter){
                    var q = (filter||'').toLowerCase();
                    var list = countries.filter(function(c){ return c.name.toLowerCase().indexOf(q)>-1 || c.code.toLowerCase().indexOf(q)>-1; }).slice(0,10);
                    dd.innerHTML = list.map(function(c,idx){ return '<div class="item'+(idx===activeIndex?' active':'')+'" data-index="'+idx+'" data-code="'+c.code+'" data-phone="'+c.phone+'" style="display:flex; align-items:center; gap:10px; padding:8px 12px; cursor:pointer; border-radius:8px"><span style="font-size:18px">'+c.flag+'</span><span style="flex:1">'+highlight(c.name,q)+' ('+c.code+')</span><span style="color:var(--text-muted)">'+c.phone+'</span></div>'; }).join('');
                    dd.style.display = list.length? 'block':'none';
                  }
                  dd.addEventListener('click', function(ev){ var it = ev.target.closest('.item'); if (!it) return; var code = it.getAttribute('data-code'); var phone = it.getAttribute('data-phone'); var obj = countries.find(function(c){return c.code===code}); if (obj){ cInput.value = obj.name; phoneCodeInput.value = phone; ccDisplay.value = code; dd.style.display='none'; }
                  });
                  cInput.addEventListener('input', function(){ renderList(cInput.value); });
                  cInput.addEventListener('focus', function(){ renderList(cInput.value); });
                  cInput.addEventListener('keydown', function(ev){
                    var items = dd.querySelectorAll('.item');
                    if (ev.key==='ArrowDown'){ ev.preventDefault(); activeIndex = Math.min(items.length-1, activeIndex+1); items.forEach(function(it,i){ it.classList.toggle('active', i===activeIndex); }); if (items[activeIndex]) items[activeIndex].scrollIntoView({block:'nearest'}); }
                    else if (ev.key==='ArrowUp'){ ev.preventDefault(); activeIndex = Math.max(0, activeIndex-1); items.forEach(function(it,i){ it.classList.toggle('active', i===activeIndex); }); if (items[activeIndex]) items[activeIndex].scrollIntoView({block:'nearest'}); }
                    else if (ev.key==='Enter'){ var it = items[activeIndex]; if (it){ var code = it.getAttribute('data-code'); var phone = it.getAttribute('data-phone'); var obj = countries.find(function(c){return c.code===code}); if (obj){ cInput.value = obj.name; phoneCodeInput.value = phone; ccDisplay.value = code; dd.style.display='none'; } } }
                    else if (ev.key==='Escape'){ dd.style.display='none'; }
                  });
                  document.addEventListener('click', function(ev){ if (!ev.target.closest('.country-select')){ dd.style.display='none'; } });

                  // Close modal
                  document.addEventListener('click',function(ev){ if(ev.target.closest('.js-close-profile')){ var m=document.getElementById('profileWizardModal'); if(m) m.style.display='none'; } });
                })();
                </script>
                <?php
            }
        } catch (Throwable $e) {}
    }
    ?>
</body>
</html>
