<?php
// select_scope.php
// Rediseño visual estilo MES: selección de empresa/localidad más intuitiva y profesional.
declare(strict_types=1);

require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/helpers.php';
require_once __DIR__ . '/includes/csrf.php';

require_login();
$u = current_user();
$uid = (int)$u['id'];

$companies = allowed_companies($uid);
if (!$companies) {
  http_response_code(403);
  exit('No tienes empresas asignadas.');
}

$selectedCompanyId = (int)($_GET['company_id'] ?? ($_POST['company_id'] ?? ($companies[0]['id'] ?? 0)));
$locations = $selectedCompanyId ? allowed_locations($uid, $selectedCompanyId) : [];

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_verify((string)($_POST['csrf'] ?? ''));

  $cid = (int)($_POST['company_id'] ?? 0);
  $lid = (int)($_POST['location_id'] ?? 0);

  $allowedC = array_map('intval', array_column($companies, 'id'));
  if (!in_array($cid, $allowedC, true)) {
    $err = 'Empresa no permitida.';
  } else {
    $locs = allowed_locations($uid, $cid);
    $allowedL = array_map(fn($x)=> (int)$x['id'], $locs);
    if (!in_array($lid, $allowedL, true)) {
      $err = 'Localidad no permitida.';
    } else {
      set_scope($cid, $lid);
      redirect('dashboard.php');
    }
  }
}

function companyNameById(array $companies, int $id): string {
  foreach ($companies as $c) {
    if ((int)$c['id'] === $id) return (string)$c['name'];
  }
  return '';
}

function iconForCompany(string $name, string $code=''): array {
  $s = mb_strtolower(trim($name.' '.$code));

  // Devuelve: [iconClass, badgeClass]
  if (str_contains($s, 'barra'))   return ['bi-snow2', 'theme-blue'];
  if (str_contains($s, 'bolsa'))   return ['bi-bag', 'theme-green'];
  if (str_contains($s, 'botella')) return ['bi-droplet', 'theme-cyan'];
  if (str_contains($s, 'garraf'))  return ['bi-droplet-half', 'theme-amber'];

  return ['bi-building', 'theme-gray'];
}

$selCompanyName = companyNameById($companies, $selectedCompanyId);
$roleList = array_values(array_filter(array_map('strval', $u['roles'] ?? [])));

$companyLocations = [];
foreach ($companies as $c) {
  $cidTmp = (int)$c['id'];
  $companyLocations[$cidTmp] = allowed_locations($uid, $cidTmp);
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>BReport · Seleccionar alcance</title>

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">

  <style>
    :root{
      --bg:#f4f7fb;
      --panel:#ffffff;
      --line:#dfe7f1;
      --line-soft:#edf2f7;
      --text:#11243d;
      --title:#0c2340;
      --muted:#667b94;
      --primary:#165dff;
      --primary-2:#0f4ecf;
      --success:#16a34a;
      --cyan:#0891b2;
      --amber:#d97706;
      --gray:#64748b;
      --shadow:0 18px 40px rgba(17,34,61,.08);
      --shadow-soft:0 10px 24px rgba(17,34,61,.06);
      --radius-xl:26px;
      --radius-lg:20px;
      --radius-md:15px;
    }

    *{ box-sizing:border-box; }
    body{
      margin:0;
      min-height:100vh;
      color:var(--text);
      font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
      background:
        radial-gradient(circle at top right, rgba(22,93,255,.08), transparent 22%),
        linear-gradient(180deg, #f9fbff 0%, var(--bg) 100%);
    }

    .page-wrap{ padding:24px; }

    .hero{
      background:linear-gradient(135deg, #102743 0%, #173c62 55%, #2360a1 100%);
      color:#fff;
      border-radius:28px;
      padding:24px;
      box-shadow:var(--shadow);
      position:relative;
      overflow:hidden;
      margin-bottom:20px;
    }
    .hero::after{
      content:'';
      position:absolute;
      right:-50px;
      top:-50px;
      width:210px;
      height:210px;
      border-radius:50%;
      background:radial-gradient(circle, rgba(255,255,255,.18) 0%, rgba(255,255,255,0) 70%);
      pointer-events:none;
    }
    .hero-title{ font-size:clamp(1.5rem, 2vw, 2.15rem); font-weight:800; margin-bottom:8px; }
    .hero-sub{ color:rgba(255,255,255,.8); margin:0; }

    .hero-pill,
    .role-pill{
      display:inline-flex;
      align-items:center;
      gap:8px;
      padding:9px 13px;
      border-radius:999px;
      background:rgba(255,255,255,.10);
      border:1px solid rgba(255,255,255,.16);
      color:#fff;
      font-size:.88rem;
      white-space:nowrap;
    }

    .mes-panel{
      background:var(--panel);
      border:1px solid var(--line);
      border-radius:24px;
      box-shadow:var(--shadow-soft);
      padding:22px;
    }

    .section-header{
      display:flex;
      justify-content:space-between;
      align-items:flex-start;
      gap:16px;
      margin-bottom:18px;
    }
    .section-title{
      margin:0;
      font-size:1.12rem;
      font-weight:800;
      color:var(--title);
    }
    .section-subtitle{
      margin:6px 0 0;
      color:var(--muted);
      font-size:.92rem;
    }

    .step-badge{
      display:inline-flex;
      align-items:center;
      justify-content:center;
      width:36px;
      height:36px;
      border-radius:12px;
      background:rgba(22,93,255,.10);
      color:var(--primary);
      font-weight:800;
      flex:0 0 auto;
    }

    .summary-chip{
      display:inline-flex;
      align-items:center;
      gap:8px;
      padding:10px 14px;
      border-radius:14px;
      background:#f6f9fd;
      border:1px solid var(--line-soft);
      color:var(--muted);
      font-size:.9rem;
    }

    .company-grid,
    .location-grid{
      display:grid;
      grid-template-columns:repeat(auto-fit, minmax(240px, 1fr));
      gap:16px;
    }

    .pick-card{
      position:relative;
      display:block;
      width:100%;
      height:100%;
      background:linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
      border:1px solid var(--line-soft);
      border-radius:20px;
      padding:18px;
      text-decoration:none;
      color:inherit;
      transition:transform .16s ease, box-shadow .16s ease, border-color .16s ease;
      overflow:hidden;
      box-shadow:0 8px 20px rgba(17,34,61,.04);
    }
    .pick-card:hover{
      transform:translateY(-3px);
      border-color:rgba(22,93,255,.28);
      box-shadow:0 18px 32px rgba(17,34,61,.10);
      color:inherit;
    }
    .pick-card.active{
      border-color:rgba(22,93,255,.50);
      box-shadow:0 0 0 3px rgba(22,93,255,.10), 0 18px 32px rgba(17,34,61,.09);
      background:linear-gradient(180deg, #ffffff 0%, #f7fbff 100%);
    }
    .pick-card::after{
      content:'';
      position:absolute;
      right:-28px;
      bottom:-28px;
      width:96px;
      height:96px;
      border-radius:50%;
      background:linear-gradient(135deg, rgba(22,93,255,.08), rgba(22,93,255,0));
      pointer-events:none;
    }

    .company-top,
    .location-top{
      display:flex;
      align-items:flex-start;
      gap:14px;
    }

    .ico-pill{
      width:52px;
      height:52px;
      border-radius:16px;
      display:flex;
      align-items:center;
      justify-content:center;
      font-size:1.4rem;
      flex:0 0 auto;
      border:1px solid transparent;
    }
    .theme-blue{ background:rgba(22,93,255,.12); color:var(--primary); border-color:rgba(22,93,255,.14); }
    .theme-green{ background:rgba(22,163,74,.12); color:var(--success); border-color:rgba(22,163,74,.14); }
    .theme-cyan{ background:rgba(8,145,178,.12); color:var(--cyan); border-color:rgba(8,145,178,.16); }
    .theme-amber{ background:rgba(217,119,6,.12); color:var(--amber); border-color:rgba(217,119,6,.16); }
    .theme-gray{ background:rgba(100,116,139,.12); color:var(--gray); border-color:rgba(100,116,139,.16); }

    .pick-title{ font-size:1rem; font-weight:800; color:var(--title); margin:0 0 4px; }
    .pick-sub{ color:var(--muted); font-size:.9rem; }
    .pick-state{
      margin-top:14px;
      display:inline-flex;
      align-items:center;
      gap:6px;
      padding:7px 10px;
      border-radius:999px;
      background:#f6f9fd;
      border:1px solid var(--line-soft);
      color:#526780;
      font-size:.78rem;
      font-weight:700;
    }

    .location-card{
      cursor:pointer;
    }
    .location-radio{
      position:absolute;
      opacity:0;
      pointer-events:none;
    }

    .location-check{
      margin-left:auto;
      width:28px;
      height:28px;
      border-radius:50%;
      border:1px solid var(--line);
      background:#fff;
      display:flex;
      align-items:center;
      justify-content:center;
      color:transparent;
      transition:all .16s ease;
      flex:0 0 auto;
    }
    .pick-card.active .location-check{
      background:var(--primary);
      color:#fff;
      border-color:var(--primary);
      box-shadow:0 8px 20px rgba(22,93,255,.25);
    }

    .action-bar{
      position:sticky;
      bottom:16px;
      z-index:5;
      margin-top:20px;
    }
    .action-panel{
      background:rgba(255,255,255,.95);
      backdrop-filter: blur(10px);
      border:1px solid var(--line);
      border-radius:20px;
      box-shadow:var(--shadow);
      padding:16px;
    }

    .primary-btn{
      border:none;
      border-radius:14px;
      padding:.9rem 1.1rem;
      font-weight:700;
      background:linear-gradient(135deg, var(--primary), var(--primary-2));
      color:#fff;
      box-shadow:0 14px 28px rgba(22,93,255,.22);
    }
    .primary-btn:hover{ filter:brightness(.98); }

    .empty-box{
      border:1px dashed var(--line);
      border-radius:18px;
      padding:22px;
      background:#fbfdff;
      color:var(--muted);
    }



    .company-pick-btn{
      border:0;
      text-align:left;
      cursor:pointer;
    }
    .company-pick-btn:focus{
      outline:none;
      box-shadow:0 0 0 4px rgba(22,93,255,.14), 0 18px 32px rgba(17,34,61,.10);
    }
    .modal-scope .modal-content{
      border:0;
      border-radius:24px;
      overflow:hidden;
      box-shadow:0 24px 70px rgba(17,34,61,.24);
    }
    .modal-scope .modal-header{
      background:linear-gradient(135deg, #102743 0%, #173c62 58%, #2360a1 100%);
      color:#fff;
      border:0;
      padding:20px 22px;
    }
    .modal-scope .modal-body{ background:#f7faff; padding:22px; }
    .modal-scope .modal-footer{ border-top:1px solid var(--line-soft); padding:16px 22px; }
    .modal-location-btn{
      border:1px solid var(--line-soft);
      text-align:left;
      cursor:pointer;
    }
    .modal-location-btn:hover{
      border-color:rgba(22,93,255,.34);
      transform:translateY(-2px);
    }
    .confirm-box{
      border:1px solid var(--line-soft);
      background:#fff;
      border-radius:18px;
      padding:16px;
    }
    .confirm-label{
      color:var(--muted);
      font-size:.82rem;
      font-weight:700;
      text-transform:uppercase;
      letter-spacing:.04em;
    }
    .confirm-value{
      color:var(--title);
      font-size:1.12rem;
      font-weight:800;
      margin-top:2px;
    }

    @media (max-width:991.98px){
      .page-wrap{ padding:16px; }
      .hero{ padding:20px; }
      .mes-panel{ padding:18px; }
    }
  </style>
</head>
<body>
  <div class="page-wrap">
    <div class="container-fluid px-0">

      <div class="hero">
        <div class="d-flex flex-wrap gap-3 justify-content-between align-items-start position-relative">
          <div>
            <div class="hero-title">Seleccionar alcance de trabajo</div>
            <p class="hero-sub">Elige la empresa y la localidad para entrar al dashboard operativo del sistema.</p>
          </div>
          <div class="d-flex flex-wrap gap-2 align-items-center">
            <a class="btn btn-outline-light" href="dashboard.php"><i class="bi bi-speedometer2 me-1"></i>Dashboard</a>
            <a class="btn btn-outline-light" href="logout.php"><i class="bi bi-box-arrow-right me-1"></i>Salir</a>
          </div>
        </div>

        <div class="d-flex flex-wrap gap-2 mt-3">
          <span class="hero-pill"><i class="bi bi-person-circle"></i><?=h($u['full_name'])?></span>
          <span class="hero-pill"><i class="bi bi-person-badge"></i><?=h($u['username'])?></span>
          <?php foreach ($roleList as $role): ?>
            <span class="role-pill"><i class="bi bi-shield-check"></i><?=h($role)?></span>
          <?php endforeach; ?>
        </div>
      </div>

      <?php if ($err !== ''): ?>
        <div class="alert alert-danger border-0 shadow-sm mb-3" role="alert">
          <i class="bi bi-exclamation-triangle me-2"></i><?=h($err)?>
        </div>
      <?php endif; ?>

      <div class="mes-panel mb-4">
        <div class="section-header">
          <div class="d-flex gap-3 align-items-start">
            <div class="step-badge">1</div>
            <div>
              <h2 class="section-title">Selecciona la empresa</h2>
              <p class="section-subtitle">Cada tarjeta representa una línea o familia de operación dentro del sistema.</p>
            </div>
          </div>
          <?php if ($selCompanyName !== ''): ?>
            <span class="summary-chip"><i class="bi bi-building"></i>Actual: <?=h($selCompanyName)?></span>
          <?php endif; ?>
        </div>

        <div class="company-grid">
          <?php foreach ($companies as $c):
            $cid = (int)$c['id'];
            $active = ($cid === $selectedCompanyId);
            [$ico, $theme] = iconForCompany((string)$c['name'], (string)($c['code'] ?? ''));
            $locCount = count($companyLocations[$cid] ?? []);
          ?>
            <button type="button"
                    class="pick-card company-pick-btn <?= $active ? 'active' : '' ?>"
                    data-bs-toggle="modal"
                    data-bs-target="#companyLocationsModal<?=$cid?>">
              <div class="company-top">
                <div class="ico-pill <?=$theme?>"><i class="bi <?=$ico?>"></i></div>
                <div class="flex-grow-1">
                  <h3 class="pick-title"><?=h($c['name'])?></h3>
                  <div class="pick-sub"><?=h((string)($c['code'] ?? 'Sin código'))?></div>
                  <div class="pick-state">
                    <i class="bi bi-list-check"></i>
                    <?= $locCount > 0 ? ($locCount . ' localidad(es) disponible(s)') : 'Sin localidades asignadas' ?>
                  </div>
                </div>
              </div>
            </button>
          <?php endforeach; ?>
        </div>
      </div>

      <div class="mes-panel">
        <div class="section-header">
          <div class="d-flex gap-3 align-items-start">
            <div class="step-badge"><i class="bi bi-check2-circle"></i></div>
            <div>
              <h2 class="section-title">Flujo de selección mejorado</h2>
              <p class="section-subtitle mb-0">Selecciona una empresa, elige la localidad desde el modal y confirma el alcance antes de entrar al dashboard.</p>
            </div>
          </div>
          <span class="summary-chip"><i class="bi bi-shield-check"></i>Validación por permisos</span>
        </div>

        <div class="row g-3">
          <div class="col-12 col-md-4">
            <div class="confirm-box h-100">
              <div class="confirm-label">Paso 1</div>
              <div class="confirm-value">Empresa</div>
              <div class="text-muted small mt-1">El usuario solo visualiza empresas asignadas.</div>
            </div>
          </div>
          <div class="col-12 col-md-4">
            <div class="confirm-box h-100">
              <div class="confirm-label">Paso 2</div>
              <div class="confirm-value">Localidad</div>
              <div class="text-muted small mt-1">Las localidades se muestran en modal según la empresa seleccionada.</div>
            </div>
          </div>
          <div class="col-12 col-md-4">
            <div class="confirm-box h-100">
              <div class="confirm-label">Paso 3</div>
              <div class="confirm-value">Confirmación</div>
              <div class="text-muted small mt-1">Antes de continuar se confirma empresa y localidad.</div>
            </div>
          </div>
        </div>
      </div>

      <?php foreach ($companies as $c):
        $cid = (int)$c['id'];
        [$ico, $theme] = iconForCompany((string)$c['name'], (string)($c['code'] ?? ''));
        $locsModal = $companyLocations[$cid] ?? [];
      ?>
        <div class="modal fade modal-scope" id="companyLocationsModal<?=$cid?>" tabindex="-1" aria-hidden="true">
          <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
              <div class="modal-header">
                <div class="d-flex align-items-center gap-3">
                  <div class="ico-pill <?=$theme?> bg-white bg-opacity-10 text-white border border-white border-opacity-25"><i class="bi <?=$ico?>"></i></div>
                  <div>
                    <h5 class="modal-title fw-bold mb-0"><?=h($c['name'])?></h5>
                    <div class="small text-white-50">Selecciona la localidad para esta empresa</div>
                  </div>
                </div>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
              </div>
              <div class="modal-body">
                <?php if (!$locsModal): ?>
                  <div class="empty-box bg-white">
                    <i class="bi bi-exclamation-circle me-2"></i>
                    No hay localidades asignadas para esta empresa.
                  </div>
                <?php else: ?>
                  <div class="location-grid">
                    <?php foreach ($locsModal as $l):
                      $lid = (int)$l['id'];
                    ?>
                      <button type="button"
                              class="pick-card modal-location-btn js-location-pick"
                              data-company-id="<?=$cid?>"
                              data-company-name="<?=h((string)$c['name'])?>"
                              data-location-id="<?=$lid?>"
                              data-location-name="<?=h((string)$l['name'])?>"
                              data-source-modal="companyLocationsModal<?=$cid?>">
                        <div class="location-top">
                          <div class="ico-pill theme-blue"><i class="bi bi-geo-alt"></i></div>
                          <div class="flex-grow-1">
                            <h3 class="pick-title"><?=h($l['name'])?></h3>
                            <div class="pick-sub"><?=h((string)($l['code'] ?? 'Sin código'))?></div>
                            <div class="pick-state"><i class="bi bi-diagram-3"></i> Usar esta localidad</div>
                          </div>
                          <div class="location-check"><i class="bi bi-check-lg"></i></div>
                        </div>
                      </button>
                    <?php endforeach; ?>
                  </div>
                <?php endif; ?>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancelar</button>
              </div>
            </div>
          </div>
        </div>
      <?php endforeach; ?>

      <div class="modal fade modal-scope" id="confirmScopeModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content">
            <div class="modal-header">
              <div>
                <h5 class="modal-title fw-bold mb-0">Confirmar alcance de trabajo</h5>
                <div class="small text-white-50">Valida la empresa y localidad antes de continuar</div>
              </div>
              <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
              <div class="confirm-box mb-3">
                <div class="confirm-label"><i class="bi bi-building me-1"></i>Empresa seleccionada</div>
                <div class="confirm-value" id="confirmCompanyName">—</div>
              </div>
              <div class="confirm-box">
                <div class="confirm-label"><i class="bi bi-geo-alt me-1"></i>Localidad seleccionada</div>
                <div class="confirm-value" id="confirmLocationName">—</div>
              </div>
              <div class="alert alert-info small mt-3 mb-0">
                Al confirmar, el sistema guardará este alcance para tus capturas, movimientos y consultas del dashboard.
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Regresar</button>
              <form method="post" id="confirmScopeForm" class="m-0">
                <input type="hidden" name="csrf" value="<?=h(csrf_token())?>">
                <input type="hidden" name="company_id" id="confirmCompanyId" value="">
                <input type="hidden" name="location_id" id="confirmLocationId" value="">
                <button type="submit" class="primary-btn">
                  <i class="bi bi-arrow-right-circle me-2"></i>Confirmar y entrar
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const confirmModalEl = document.getElementById('confirmScopeModal');
      const confirmModal = confirmModalEl && window.bootstrap ? new bootstrap.Modal(confirmModalEl) : null;
      const companyNameEl = document.getElementById('confirmCompanyName');
      const locationNameEl = document.getElementById('confirmLocationName');
      const companyIdEl = document.getElementById('confirmCompanyId');
      const locationIdEl = document.getElementById('confirmLocationId');

      document.querySelectorAll('.js-location-pick').forEach((btn) => {
        btn.addEventListener('click', () => {
          const companyId = btn.dataset.companyId || '';
          const locationId = btn.dataset.locationId || '';
          const companyName = btn.dataset.companyName || '—';
          const locationName = btn.dataset.locationName || '—';
          const sourceModalId = btn.dataset.sourceModal || '';

          if (companyNameEl) companyNameEl.textContent = companyName;
          if (locationNameEl) locationNameEl.textContent = locationName;
          if (companyIdEl) companyIdEl.value = companyId;
          if (locationIdEl) locationIdEl.value = locationId;

          const sourceModalEl = sourceModalId ? document.getElementById(sourceModalId) : null;
          const sourceModal = sourceModalEl && window.bootstrap ? bootstrap.Modal.getOrCreateInstance(sourceModalEl) : null;

          if (sourceModalEl && sourceModal) {
            sourceModalEl.addEventListener('hidden.bs.modal', () => {
              if (confirmModal) confirmModal.show();
            }, { once: true });
            sourceModal.hide();
          } else if (confirmModal) {
            confirmModal.show();
          }
        });
      });
    });
  </script>
</body>
</html>
