<?php
require_once __DIR__ . "/_commons.php";
$pdo = pdo_m(); $GF = get_global_filters();

if(!require_filters_guard($GF)){
  echo '<div class="warn">Sin filtros aplicados.</div>
        <div style="width:100%;height:380px;display:flex;align-items:center;justify-content:center;border:1px dashed #e5e5e5;border-radius:6px"><span class="muted">Sin filtros</span></div>';
  return;
}

/* ===== Rango + filtros ===== */
[$from,$to] = build_range($GF['range'] ?? 'month', $GF['fromUi'] ?? '', $GF['toUi'] ?? '');
$entryCond  = entry_condition_sql();
$paramsBase = [':site'=>$GF['site'], ':from'=>$from, ':to'=>$to] + allowed_url_params();

/* Fuente/campaña global */
list($campWhere, $campParams) = campaign_source_condition($GF, 'v');

/* Búsqueda avanzada (idvisit, idvisitor HEX, URL de entrada) */
list($advWhere, $advParams, $needAin) = build_advanced_where($GF, 'v', 'ain');

/* ===== Datos por país ===== */
$byCountry=[];
try{
  $sql = "
    SELECT UPPER(COALESCE(v.location_country,'')) AS code,
           COUNT(*) AS visits,
           COUNT(DISTINCT HEX(v.idvisitor)) AS uniques
    FROM matomo_log_visit v
    LEFT JOIN matomo_log_action ain ON ain.idaction = v.visit_entry_idaction_url
    WHERE v.idsite = :site
      AND v.visit_last_action_time BETWEEN :from AND :to
      AND $entryCond
      $campWhere
      $advWhere
    GROUP BY UPPER(COALESCE(v.location_country,''))
  ";
  $st = $pdo->prepare($sql);
  $st->execute($paramsBase + $campParams + $advParams);
  $byCountry = $st->fetchAll() ?: [];
}catch(Throwable $e){ $byCountry=[]; }

/* ===== Parámetros locales (mantener en URL) ===== */
$metric  = $_GET['cm_metric']  ?? 'visits';
$country = strtoupper($_GET['cm_country'] ?? 'ALL');

/* Diccionarios de nombre regional (opcionales) */
$CR = ['SJ'=>'San José','A'=>'Alajuela','H'=>'Heredia','C'=>'Cartago','G'=>'Guanacaste','P'=>'Puntarenas','L'=>'Limón'];
$PA = ['1'=>'Bocas del Toro','2'=>'Coclé','3'=>'Colón','4'=>'Chiriquí','5'=>'Darién','6'=>'Herrera','7'=>'Los Santos','8'=>'Panamá','9'=>'Veraguas','10'=>'Panamá Oeste','EM'=>'Emberá','KY'=>'Kuna Yala','NB'=>'Ngäbe-Buglé'];
?>
<div id="mapContainer" style="position:relative">
  <!-- Preservamos TODOS los filtros globales y avanzados al enviar el form -->
  <form class="filters" method="get" accept-charset="UTF-8"
        style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;z-index:10;position:relative">
    <input type="hidden" name="g_site"      value="<?= e($_GET['g_site'] ?? '') ?>">
    <input type="hidden" name="g_range"     value="<?= e($_GET['g_range']?? '') ?>">
    <input type="hidden" name="g_from"      value="<?= e($_GET['g_from'] ?? '') ?>">
    <input type="hidden" name="g_to"        value="<?= e($_GET['g_to']   ?? '') ?>">
    <input type="hidden" name="g_src"       value="<?= e($_GET['g_src']  ?? ($GF['src'] ?? 'all')) ?>">
    <input type="hidden" name="g_idvisit"   value="<?= e($_GET['g_idvisit']   ?? '') ?>">
    <input type="hidden" name="g_idvisitor" value="<?= e($_GET['g_idvisitor'] ?? '') ?>">
    <input type="hidden" name="g_url"       value="<?= e($_GET['g_url']       ?? '') ?>">

    <label><b>Métrica:</b></label>
    <select name="cm_metric" onchange="this.form.submit()">
      <option value="visits"  <?= $metric==='visits' ?'selected':'' ?>>Visitas</option>
      <option value="uniques" <?= $metric==='uniques'?'selected':'' ?>>Visitantes únicos</option>
    </select>
    <label><b>País:</b></label>
    <select name="cm_country" onchange="this.form.submit()">
      <option value="ALL" <?= $country==='ALL'?'selected':'' ?>>Todos</option>
      <?php foreach($byCountry as $r): $c=$r['code'] ?: 'ZZ'; if($c==='ZZ') continue; ?>
        <option value="<?= e($c) ?>" <?= $country===$c?'selected':'' ?>><?= e(strtolower($c)) ?> (<?= (int)$r[$metric] ?>)</option>
      <?php endforeach; ?>
    </select>
    <button type="button" onclick="redrawMap()" style="padding:4px 8px">🔄 Refrescar</button>
    <button type="button" onclick="resetMap()" style="padding:4px 8px">🌍 Ver Mundo</button>
    <button type="button" onclick="toggleFullscreen()" style="padding:4px 8px">⛶ Pantalla completa</button>
  </form>

  <div id="countries_map_chart"
       style="width:100%;aspect-ratio:16/9;max-height:80vh;border-radius:6px;margin-top:8px;display:flex;align-items:center;justify-content:center"></div>
</div>

<?php
/* ===== Nivel país o provincias según selección ===== */
$rowsPlot=[]; $regionOpt='world'; $resolution='countries'; $withTooltip=false;
try{
  if($country!=='ALL'){
    $regionOpt=$country; $resolution='provinces'; $withTooltip=true;
    $sql2 = "
      SELECT UPPER(v.location_country) AS cc,
             UPPER(v.location_region)  AS rr,
             CONCAT(UPPER(v.location_country),'-',UPPER(v.location_region)) AS sub,
             COUNT(*) AS visits,
             COUNT(DISTINCT HEX(v.idvisitor)) AS uniques
      FROM matomo_log_visit v
      LEFT JOIN matomo_log_action ain ON ain.idaction = v.visit_entry_idaction_url
      WHERE v.idsite=:site
        AND v.visit_last_action_time BETWEEN :from AND :to
        AND $entryCond
        $campWhere
        $advWhere
        AND UPPER(v.location_country)=:cc
        AND v.location_region <> ''
      GROUP BY sub
    ";
    $p2 = $paramsBase + $campParams + $advParams; $p2[':cc']=$country;
    $stmt2=$pdo->prepare($sql2); $stmt2->execute($p2); $rowsPlot=$stmt2->fetchAll() ?: [];
  } else {
    $rowsPlot=$byCountry;
  }
}catch(Throwable $e){ $rowsPlot=[]; }

/* ===== Datos para el gráfico ===== */
$dataRows=[];
foreach($rowsPlot as $r){
  $k   = isset($r['sub']) ? $r['sub'] : strtoupper($r['code']?:'');
  $val = (int)($r[$metric] ?? 0);
  if($withTooltip && isset($r['rr'])){
    $name = ($r['cc']==='CR') ? ($CR[$r['rr']] ?? $r['rr']) :
            (($r['cc']==='PA') ? ($PA[$r['rr']] ?? $r['rr']) : $r['rr']);
    $tip  = '<div style="padding:6px 8px"><b>'.e($name).'</b><br>Valor: '.$val.'</div>';
    $dataRows[] = [$k, $val, $tip];
  } else {
    $dataRows[] = [$k, $val];
  }
}
?>
<script>
let chart, data, options;

ensureGoogleCharts(function(){
  data=new google.visualization.DataTable();
  data.addColumn('string','Región');
  data.addColumn('number','Valor');
  <?php if($withTooltip): ?>data.addColumn({type:'string', role:'tooltip', p:{html:true}});<?php endif; ?>
  data.addRows(<?= json_encode($dataRows, JSON_UNESCAPED_UNICODE|JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP) ?>);

  chart=new google.visualization.GeoChart(document.getElementById('countries_map_chart'));
  options={
    region:'<?= e($regionOpt) ?>',
    displayMode:'regions',
    resolution:'<?= e($resolution) ?>',
    colorAxis:{colors:['#E3F2FD','#1E88E5']},
    legend:'none',
    keepAspectRatio:true,
    enableRegionInteractivity:true,
    magnifyingGlass:{enable:true,zoomFactor:6},
    explorer:{ actions:['dragToPan','scrollToZoom'], keepInBounds:true, maxZoomIn:10, maxZoomOut:0.5 },
    <?php if($withTooltip): ?>tooltip:{isHtml:true},<?php endif; ?>
  };
  chart.draw(data,options);

  google.visualization.events.addListener(chart,'regionClick',function(e){
    const code=(e.region||'').toUpperCase(); if(!code) return;
    const url=new URL(window.location);
    url.searchParams.set('cm_country',code);
    // Preservamos TODO lo demás (query actual ya los contiene)
    window.location.assign(url.toString());
  });
});

/* ===== Mantener fullscreen tras recarga ===== */
const LS_KEY = 'cm_fullscreen';

function applyPseudoFS(on){
  const cont = document.getElementById('mapContainer');
  const form = cont.querySelector('form.filters');
  if(on){
    cont.classList.add('pseudo-fs');
    Object.assign(cont.style,{position:'fixed',inset:'0',zIndex:'9999',background:'#fff'});
    form.style.position='fixed'; form.style.top='10px'; form.style.left='50%';
    form.style.transform='translateX(-50%)';
    form.style.background='rgba(0,0,0,0.5)'; form.style.color='white';
    form.style.padding='8px 12px'; form.style.borderRadius='8px';
    form.style.boxShadow='0 2px 8px rgba(0,0,0,0.3)';
    form.querySelectorAll('label,b').forEach(el=>el.style.color='white');
  }else{
    cont.classList.remove('pseudo-fs');
    Object.assign(cont.style,{position:'relative',inset:'',zIndex:'' ,background:''});
    const form = cont.querySelector('form.filters');
    form.style.position='relative'; form.style.transform='none';
    form.style.background='none';  form.style.color='';
    form.style.boxShadow='none';   form.style.padding='0';
    form.querySelectorAll('label,b').forEach(el=>el.style.color='black');
  }
  redrawMap();
}

function enterFullscreen(){
  const cont=document.getElementById('mapContainer');
  if(cont.requestFullscreen){
    cont.requestFullscreen().then(()=>{ localStorage.setItem(LS_KEY,'1'); }).catch(()=>{
      // Si el navegador bloquea (no hay gesto), usamos pseudo-fullscreen
      localStorage.setItem(LS_KEY,'1'); applyPseudoFS(true);
    });
  }else{
    localStorage.setItem(LS_KEY,'1'); applyPseudoFS(true);
  }
}
function exitFullscreen(){
  localStorage.removeItem(LS_KEY);
  if(document.fullscreenElement){ document.exitFullscreen().catch(()=>{}); }
  applyPseudoFS(false);
}
function toggleFullscreen(){
  if(document.fullscreenElement || document.getElementById('mapContainer').classList.contains('pseudo-fs')){
    exitFullscreen();
  }else{
    enterFullscreen();
  }
}

document.addEventListener('fullscreenchange',()=>{
  // Si salimos de fullscreen nativo y no queremos mantenerlo
  if(!document.fullscreenElement){
    if(localStorage.getItem(LS_KEY)!=='1'){ applyPseudoFS(false); }
  }else{
    localStorage.setItem(LS_KEY,'1');
  }
  redrawMap();
});

// Reaplicar preferencia al cargar (intenta nativo; si falla, pseudo)
document.addEventListener('DOMContentLoaded',()=>{
  if(localStorage.getItem(LS_KEY)==='1'){
    // Intento nativo; si el browser bloquea, pseudo:
    const cont=document.getElementById('mapContainer');
    if(cont.requestFullscreen){
      cont.requestFullscreen().then(()=>{}).catch(()=>{ applyPseudoFS(true); });
    }else{
      applyPseudoFS(true);
    }
  }
});

/* ===== Utilidades ===== */
function redrawMap(){ if(chart&&data) chart.draw(data,options); }
function resetMap(){
  const url=new URL(window.location);
  url.searchParams.set('cm_country','ALL');
  window.location.assign(url.toString());
}
window.addEventListener('resize',()=>{ redrawMap(); });
</script>
