<?php
// select_scope.php
// BReport · Selección de empresa/planta con cards azules y modal único de confirmación.
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'] ?? 0);

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

$companyLocations = [];
foreach ($companies as $c) {
    $cid = (int)($c['id'] ?? 0);
    $companyLocations[$cid] = $cid > 0 ? allowed_locations($uid, $cid) : [];
}

$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(static fn($x) => (int)$x['id'], $locs);

        if (!in_array($lid, $allowedL, true)) {
            $err = 'Localidad no permitida.';
        } else {
            set_scope($cid, $lid);
            redirect('dashboard.php');
        }
    }
}

if (!function_exists('h')) {
    function h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
    }
}

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

    if (str_contains($s, 'barra')) return 'bi-snow2';
    if (str_contains($s, 'bolsa')) return 'bi-bag';
    if (str_contains($s, 'botella')) return 'bi-droplet-fill';
    if (str_contains($s, 'garraf')) return 'bi-droplet-half';

    return 'bi-building';
}

function scopeKindLabel(string $name, string $code=''): string {
    $s = mb_strtolower(trim($name . ' ' . $code), 'UTF-8');

    if (str_contains($s, 'barra')) return 'Hielo Barra';
    if (str_contains($s, 'bolsa')) return 'Hielo Bolsa';
    if (str_contains($s, 'botella')) return 'Planta Botella';
    if (str_contains($s, 'garraf')) return 'Garrafón';

    return 'Operación';
}

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

$jsCompanies = [];
foreach ($companies as $c) {
    $cid = (int)($c['id'] ?? 0);
    $locs = [];
    foreach (($companyLocations[$cid] ?? []) as $l) {
        $locs[] = [
            'id' => (int)($l['id'] ?? 0),
            'name' => (string)($l['name'] ?? ''),
            'code' => (string)($l['code'] ?? ''),
        ];
    }

    $jsCompanies[$cid] = [
        'id' => $cid,
        'name' => (string)($c['name'] ?? ''),
        'code' => (string)($c['code'] ?? ''),
        'kind' => scopeKindLabel((string)($c['name'] ?? ''), (string)($c['code'] ?? '')),
        'icon' => iconForCompany((string)($c['name'] ?? ''), (string)($c['code'] ?? '')),
        'locations' => $locs,
    ];
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>BReport · Seleccionar planta</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:#edf4fb;
  --ink:#0c1f35;
  --muted:#6b7f96;
  --line:#d9e5f2;
  --blue:#0f4c81;
  --blue2:#1565c0;
  --blue3:#1d75d8;
  --navy:#08213f;
  --white:#ffffff;
  --shadow:0 22px 55px rgba(8,33,63,.16);
  --shadow-soft:0 16px 36px rgba(8,33,63,.10);
}

*{box-sizing:border-box}

body{
  margin:0;
  min-height:100vh;
  color:var(--ink);
  font-family:Inter,system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif;
  background:
    radial-gradient(circle at 12% 8%, rgba(29,117,216,.20), transparent 24rem),
    radial-gradient(circle at 92% 15%, rgba(15,76,129,.16), transparent 28rem),
    linear-gradient(180deg,#f8fbff 0%, var(--bg) 100%);
}

.page{
  max-width:1500px;
  margin:0 auto;
  padding:24px;
}

.hero{
  position:relative;
  overflow:hidden;
  background:linear-gradient(135deg,var(--navy) 0%,var(--blue) 52%,var(--blue3) 100%);
  color:#fff;
  border-radius:30px;
  box-shadow:var(--shadow);
  padding:26px;
  margin-bottom:18px;
}

.hero::before{
  content:"";
  position:absolute;
  right:-90px;
  top:-100px;
  width:280px;
  height:280px;
  border-radius:50%;
  background:rgba(255,255,255,.13);
}

.hero::after{
  content:"";
  position:absolute;
  left:42%;
  bottom:-115px;
  width:330px;
  height:170px;
  border-radius:50%;
  background:rgba(255,255,255,.08);
}

.hero-content{position:relative;z-index:1}

.hero-title{
  font-size:clamp(1.7rem,3vw,2.65rem);
  font-weight:950;
  letter-spacing:-.045em;
  margin:0;
  line-height:1.02;
}

.hero-sub{
  margin:.55rem 0 0;
  color:rgba(255,255,255,.82);
  max-width:820px;
  font-size:1rem;
}

.hero-actions .btn{
  border-radius:999px;
  font-weight:850;
  padding:.58rem .9rem;
}

.user-pill{
  display:inline-flex;
  align-items:center;
  gap:8px;
  padding:9px 13px;
  border-radius:999px;
  background:rgba(255,255,255,.12);
  border:1px solid rgba(255,255,255,.17);
  color:#fff;
  font-weight:750;
  font-size:.88rem;
}

.main-panel{
  background:rgba(255,255,255,.88);
  border:1px solid rgba(15,76,129,.12);
  border-radius:28px;
  box-shadow:var(--shadow-soft);
  padding:22px;
  backdrop-filter:blur(10px);
}

.section-head{
  display:flex;
  align-items:flex-start;
  justify-content:space-between;
  gap:14px;
  margin-bottom:20px;
}

.section-title{
  margin:0;
  font-size:1.25rem;
  font-weight:950;
  letter-spacing:-.025em;
}

.section-sub{
  margin:.35rem 0 0;
  color:var(--muted);
}

.summary-chip{
  display:inline-flex;
  align-items:center;
  gap:8px;
  border-radius:999px;
  padding:9px 13px;
  background:#eef6ff;
  color:#174a7c;
  border:1px solid #cfe3f8;
  font-size:.88rem;
  font-weight:850;
  white-space:nowrap;
}

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

.plant-card{
  position:relative;
  width:100%;
  min-height:172px;
  text-align:left;
  color:#fff;
  border:1px solid rgba(255,255,255,.18);
  border-radius:24px;
  padding:20px;
  overflow:hidden;
  cursor:pointer;
  background:
    radial-gradient(circle at 92% 12%, rgba(255,255,255,.22), transparent 5.8rem),
    linear-gradient(135deg,#08335e 0%,#0f4c81 52%,#1d75d8 100%);
  box-shadow:0 18px 38px rgba(15,76,129,.22);
  transition:transform .15s ease, box-shadow .15s ease, filter .15s ease;
}

.plant-card:hover{
  transform:translateY(-4px);
  box-shadow:0 26px 52px rgba(15,76,129,.30);
  filter:saturate(1.05);
}

.plant-card:focus{
  outline:none;
  box-shadow:0 0 0 4px rgba(29,117,216,.18), 0 26px 52px rgba(15,76,129,.30);
}

.plant-card::after{
  content:"";
  position:absolute;
  right:-36px;
  bottom:-42px;
  width:150px;
  height:150px;
  border-radius:50%;
  background:rgba(255,255,255,.10);
}

.plant-card-inner{position:relative;z-index:1}

.plant-top{
  display:flex;
  align-items:flex-start;
  gap:14px;
}

.plant-icon{
  width:58px;
  height:58px;
  border-radius:18px;
  display:flex;
  align-items:center;
  justify-content:center;
  color:#fff;
  font-size:1.65rem;
  background:rgba(255,255,255,.16);
  border:1px solid rgba(255,255,255,.20);
  flex:0 0 auto;
}

.plant-kind{
  display:inline-flex;
  border-radius:999px;
  padding:5px 9px;
  background:rgba(255,255,255,.14);
  border:1px solid rgba(255,255,255,.18);
  color:rgba(255,255,255,.88);
  font-size:.74rem;
  font-weight:900;
  letter-spacing:.04em;
  text-transform:uppercase;
  margin-bottom:7px;
}

.plant-title{
  margin:0;
  color:#fff;
  font-size:1.12rem;
  font-weight:950;
  line-height:1.12;
  letter-spacing:-.02em;
}

.plant-code{
  margin-top:4px;
  color:rgba(255,255,255,.72);
  font-size:.9rem;
}

.plant-footer{
  margin-top:18px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:12px;
}

.plant-meta{
  display:inline-flex;
  align-items:center;
  gap:7px;
  color:rgba(255,255,255,.86);
  font-size:.84rem;
  font-weight:800;
}

.enter-pill{
  display:inline-flex;
  align-items:center;
  gap:7px;
  border-radius:999px;
  padding:8px 11px;
  background:#fff;
  color:#0f4c81;
  font-weight:950;
  font-size:.82rem;
  box-shadow:0 10px 22px rgba(8,33,63,.12);
}

.info-grid{
  margin-top:18px;
  display:grid;
  grid-template-columns:repeat(3,minmax(0,1fr));
  gap:12px;
}

.info-card{
  border:1px solid var(--line);
  border-radius:20px;
  background:#fff;
  padding:16px;
}

.info-label{
  color:var(--muted);
  text-transform:uppercase;
  font-size:.76rem;
  letter-spacing:.055em;
  font-weight:900;
}

.info-value{
  margin-top:3px;
  font-size:1.03rem;
  font-weight:950;
}

.modal-scope .modal-content{
  border:0;
  border-radius:26px;
  overflow:hidden;
  box-shadow:0 28px 80px rgba(8,33,63,.30);
}

.modal-scope .modal-header{
  border:0;
  color:#fff;
  background:linear-gradient(135deg,var(--navy),var(--blue),var(--blue3));
  padding:20px 22px;
}

.modal-scope .modal-body{
  background:#f7fbff;
  padding:22px;
}

.modal-scope .modal-footer{
  background:#fff;
  border-top:1px solid #e4edf7;
  padding:16px 22px;
}

.confirm-card{
  border:1px solid #d9e8f6;
  background:#fff;
  border-radius:20px;
  padding:16px;
}

.confirm-label{
  color:var(--muted);
  text-transform:uppercase;
  font-size:.76rem;
  letter-spacing:.055em;
  font-weight:900;
}

.confirm-value{
  color:#0c2340;
  margin-top:4px;
  font-size:1.16rem;
  font-weight:950;
}

.form-select{
  border-radius:16px;
  min-height:48px;
  border-color:#cfddec;
  font-weight:780;
}

.btn-confirm{
  border:0;
  border-radius:15px;
  padding:.85rem 1.1rem;
  font-weight:950;
  color:#fff;
  background:linear-gradient(135deg,var(--blue),var(--blue3));
  box-shadow:0 16px 30px rgba(15,76,129,.24);
}

@media(max-width:991.98px){
  .page{padding:16px}
  .section-head{display:block}
  .summary-chip{margin-top:12px}
  .info-grid{grid-template-columns:1fr}
}

@media(max-width:575.98px){
  .hero{border-radius:22px;padding:18px}
  .main-panel{border-radius:22px;padding:16px}
  .company-grid{grid-template-columns:1fr}
  .plant-card{min-height:160px}
}
</style>
</head>

<body>
<div class="page">

  <header class="hero">
    <div class="hero-content">
      <div class="d-flex flex-wrap justify-content-between align-items-start gap-3">
        <div>
          <h1 class="hero-title">Selecciona tu planta</h1>
        </div>
        <div class="hero-actions d-flex flex-wrap gap-2">
          <a class="btn btn-outline-light" href="dashboard.php"><i class="bi bi-speedometer2 me-1"></i>Dashboard</a>
          <a class="btn btn-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="user-pill"><i class="bi bi-person-circle"></i><?=h($u['full_name'] ?? '')?></span>
        <span class="user-pill"><i class="bi bi-person-badge"></i><?=h($u['username'] ?? '')?></span>
        <?php foreach ($roleList as $role): ?>
          <span class="user-pill"><i class="bi bi-shield-check"></i><?=h($role)?></span>
        <?php endforeach; ?>
      </div>
    </div>
  </header>

  <?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; ?>

  <main class="main-panel">
    <div class="section-head">
      <div>
        <h2 class="section-title">Empresas / plantas disponibles</h2>
      </div>
      <span class="summary-chip"><i class="bi bi-shield-lock"></i>Accesos validados por usuario</span>
    </div>

    <div class="company-grid">
      <?php foreach ($companies as $c):
        $cid = (int)($c['id'] ?? 0);
        $locCount = count($companyLocations[$cid] ?? []);
        $name = (string)($c['name'] ?? '');
        $code = (string)($c['code'] ?? '');
        $kind = scopeKindLabel($name, $code);
        $icon = iconForCompany($name, $code);
      ?>
        <button type="button"
                class="plant-card js-open-confirm"
                data-company-id="<?=$cid?>">
          <div class="plant-card-inner">
            <div class="plant-top">
              <div class="plant-icon"><i class="bi <?=$icon?>"></i></div>
              <div class="flex-grow-1">
                <div class="plant-kind"><?=h($kind)?></div>
                <h3 class="plant-title"><?=h($name)?></h3>
                <div class="plant-code"><?=h($code !== '' ? $code : 'Sin código')?></div>
              </div>
            </div>

            <div class="plant-footer">
              <div class="plant-meta">
                <i class="bi bi-geo-alt"></i>
                <?= $locCount > 0 ? h((string)$locCount . ' localidad(es)') : 'Sin localidades' ?>
              </div>
              <div class="enter-pill">
                Entrar <i class="bi bi-arrow-right"></i>
              </div>
            </div>
          </div>
        </button>
      <?php endforeach; ?>
    </div>
  </main>
</div>

<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 class="d-flex align-items-center gap-3">
          <div class="plant-icon" style="width:50px;height:50px;border-radius:16px">
            <i class="bi bi-building" id="modalCompanyIcon"></i>
          </div>
          <div>
            <h5 class="modal-title fw-black mb-0">Confirmar ingreso a planta</h5>
            <div class="small text-white-50">Valida el alcance antes de continuar</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">
        <div class="confirm-card mb-3">
          <div class="confirm-label"><i class="bi bi-building me-1"></i>Empresa / planta</div>
          <div class="confirm-value" id="confirmCompanyName">—</div>
          <div class="small text-muted mt-1" id="confirmCompanyCode">—</div>
        </div>

        <div class="confirm-card">
          <div class="confirm-label mb-2"><i class="bi bi-geo-alt me-1"></i>Localidad</div>
          <select class="form-select" id="confirmLocationSelect"></select>
          <div class="small text-muted mt-2" id="confirmLocationHelp">Selecciona la localidad operativa.</div>
        </div>

        <div class="alert alert-primary small mt-3 mb-0">
          <i class="bi bi-info-circle me-1"></i>
          Al confirmar, BReport usará esta empresa y localidad para dashboard, inventario, almacén, producción y ventas.
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary fw-bold" data-bs-dismiss="modal">Cancelar</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="btn-confirm">
            <i class="bi bi-arrow-right-circle me-2"></i>Confirmar y entrar
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
const COMPANIES = <?=json_encode($jsCompanies, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>;

document.addEventListener('DOMContentLoaded', () => {
  const modalEl = document.getElementById('confirmScopeModal');
  const modal = modalEl ? new bootstrap.Modal(modalEl) : null;

  const companyNameEl = document.getElementById('confirmCompanyName');
  const companyCodeEl = document.getElementById('confirmCompanyCode');
  const companyIdEl = document.getElementById('confirmCompanyId');
  const locationIdEl = document.getElementById('confirmLocationId');
  const locationSelect = document.getElementById('confirmLocationSelect');
  const locationHelp = document.getElementById('confirmLocationHelp');
  const modalCompanyIcon = document.getElementById('modalCompanyIcon');

  function setSelectedLocation() {
    if (!locationSelect || !locationIdEl) return;
    locationIdEl.value = locationSelect.value || '';
  }

  document.querySelectorAll('.js-open-confirm').forEach((card) => {
    card.addEventListener('click', () => {
      const companyId = String(card.dataset.companyId || '');
      const company = COMPANIES[companyId];

      if (!company) return;

      companyNameEl.textContent = company.name || '—';
      companyCodeEl.textContent = `${company.kind || 'Operación'} · ${company.code || 'Sin código'}`;
      companyIdEl.value = company.id || '';
      modalCompanyIcon.className = `bi ${company.icon || 'bi-building'}`;

      locationSelect.innerHTML = '';

      const locations = Array.isArray(company.locations) ? company.locations : [];
      if (locations.length === 0) {
        const opt = document.createElement('option');
        opt.value = '';
        opt.textContent = 'Sin localidades asignadas';
        locationSelect.appendChild(opt);
        locationSelect.disabled = true;
        locationIdEl.value = '';
        locationHelp.textContent = 'No hay localidades asignadas para esta planta.';
      } else {
        locations.forEach((loc, index) => {
          const opt = document.createElement('option');
          opt.value = loc.id || '';
          opt.textContent = `${loc.name || 'Localidad'}${loc.code ? ' · ' + loc.code : ''}`;
          if (index === 0) opt.selected = true;
          locationSelect.appendChild(opt);
        });
        locationSelect.disabled = false;
        locationHelp.textContent = locations.length === 1
          ? 'Esta planta tiene una localidad disponible.'
          : 'Selecciona la localidad a la que deseas ingresar.';
        setSelectedLocation();
      }

      if (modal) modal.show();
    });
  });

  if (locationSelect) {
    locationSelect.addEventListener('change', setSelectedLocation);
  }

  const form = document.getElementById('confirmScopeForm');
  if (form) {
    form.addEventListener('submit', (ev) => {
      setSelectedLocation();
      if (!companyIdEl.value || !locationIdEl.value) {
        ev.preventDefault();
        alert('Selecciona una empresa y localidad válida antes de continuar.');
      }
    });
  }
});
</script>
</body>
</html>
