<?php
/**
 * @intranet-file base/sectores/index.php
 * @intranet-file-version 2026.03.13.1
 * @intranet-file-date 2026-03-13
 * @intranet-file-owner CSIF Intranet
 */
declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/common/app_guard.php';
require_once dirname(__DIR__, 2) . '/common/url.php';
checkAppAccess();

require_once dirname(__DIR__, 2) . '/common/catalogo_db.php';
require_once dirname(__DIR__, 2) . '/common/sectores_db.php';

if (!catalogo_is_admin()) {
    http_response_code(403);
    die('Acceso restringido');
}

$pdo = db();
sectores_ensure_schema($pdo);

function h($s): string {
    return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
function pad2(int $n): string {
    return str_pad((string)$n, 2, '0', STR_PAD_LEFT);
}
function table_exists(PDO $pdo, string $table): bool {
    $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :t");
    $st->execute(['t' => $table]);
    return (int)$st->fetchColumn() > 0;
}

$msg = '';
$err = '';

if (isset($_GET['ok'])) {
    $ok = (int)$_GET['ok'];
    if ($ok === 1) $msg = 'Sector creado.';
    if ($ok === 2) $msg = 'Cambios guardados.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        catalogo_csrf_validate($_POST['csrf'] ?? null, 'sectores_admin_csrf');
        $action = trim((string)($_POST['action'] ?? ''));

        $validateHex = function (string $color): ?string {
            $color = trim($color);
            if ($color === '') return null;
            if (!preg_match('/^#[0-9a-fA-F]{6}$/', $color)) {
                throw new RuntimeException('Color inválido. Usa formato #RRGGBB.');
            }
            return strtolower($color);
        };

        $parseCodigo = function ($raw): int {
            $s = trim((string)$raw);
            if ($s === '') throw new RuntimeException('El código es obligatorio.');
            if (!preg_match('/^\d{1,2}$/', $s)) throw new RuntimeException('Código inválido. Debe ser numérico de 2 dígitos (00–99).');
            $n = (int)$s;
            if ($n < 0 || $n > 99) throw new RuntimeException('Código inválido. Debe estar entre 00 y 99.');
            return $n;
        };

        if ($action === 'add') {
            $codigo = $parseCodigo($_POST['codigo'] ?? '');
            $nombre = trim((string)($_POST['nombre'] ?? ''));
            $email  = trim((string)($_POST['email'] ?? ''));
            $color  = (string)($_POST['color_hex'] ?? '');
            $activo = !empty($_POST['activo']) ? 1 : 0;

            if ($nombre === '') throw new RuntimeException('El nombre es obligatorio.');
            if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Email inválido.');
            $color = $validateHex($color);

            // Insert con ID manual (código de 2 dígitos)
            $st = $pdo->prepare("INSERT INTO sectores (id, nombre, email, color_hex, activo) VALUES (:id, :n, :e, :c, :a)");
            $st->execute(['id' => $codigo, 'n' => $nombre, 'e' => ($email === '' ? null : $email), 'c' => $color, 'a' => $activo]);

            header('Location: index.php?ok=1');
            exit;
        }

        if ($action === 'bulk_save') {
            $rows = $_POST['sectores'] ?? [];
            if (!is_array($rows)) $rows = [];

            $hasFlotaReservas = table_exists($pdo, 'flota_reservas');

            foreach ($rows as $r) {
                if (!is_array($r)) continue;

                $oldId = isset($r['old_id']) ? (int)$r['old_id'] : 0;
                if ($oldId < 0 || $oldId > 99) continue;

                $doDelete = !empty($r['_delete']);
                if ($doDelete) {
                    // Evitar borrar si está referenciado en flota_reservas
                    if ($hasFlotaReservas) {
                        $st = $pdo->prepare("SELECT COUNT(*) FROM flota_reservas WHERE sector_id = :id");
                        $st->execute(['id' => $oldId]);
                        if ((int)$st->fetchColumn() > 0) {
                            throw new RuntimeException("No se puede eliminar el sector ".pad2($oldId)." porque está usado en reservas de flota.");
                        }
                    }

                    $st = $pdo->prepare("DELETE FROM sectores WHERE id = :id");
                    $st->execute(['id' => $oldId]);
                    continue;
                }

                $doUpdate = !empty($r['_update']);
                if (!$doUpdate) continue;

                $newId  = $parseCodigo($r['id'] ?? '');
                $nombre = trim((string)($r['nombre'] ?? ''));
                $email  = trim((string)($r['email'] ?? ''));
                $color  = (string)($r['color_hex'] ?? '');
                $activo = !empty($r['activo']) ? 1 : 0;

                if ($nombre === '') throw new RuntimeException("Nombre obligatorio (Código ".pad2($oldId).").");
                if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) throw new RuntimeException("Email inválido (Código ".pad2($oldId).").");
                $color = $validateHex($color);

                $pdo->beginTransaction();

                // Si cambia el código, hay que mover referencias
                if ($newId !== $oldId) {
                    // comprobar que el nuevo código no existe
                    $st = $pdo->prepare("SELECT COUNT(*) FROM sectores WHERE id = :id");
                    $st->execute(['id' => $newId]);
                    if ((int)$st->fetchColumn() > 0) {
                        $pdo->rollBack();
                        throw new RuntimeException("El código ".pad2($newId)." ya existe. Elige otro.");
                    }

                    // Actualizar refs primero (si existen)
                    if ($hasFlotaReservas) {
                        $st = $pdo->prepare("UPDATE flota_reservas SET sector_id = :new WHERE sector_id = :old");
                        $st->execute(['new' => $newId, 'old' => $oldId]);
                    }

                    // Cambiar PK del sector
                    $st = $pdo->prepare("UPDATE sectores SET id = :new WHERE id = :old");
                    $st->execute(['new' => $newId, 'old' => $oldId]);
                }

                // Actualizar resto de campos (ya con el id definitivo)
                $st = $pdo->prepare("UPDATE sectores SET nombre = :n, email = :e, color_hex = :c, activo = :a WHERE id = :id");
                $st->execute(['n' => $nombre, 'e' => ($email === '' ? null : $email), 'c' => $color, 'a' => $activo, 'id' => $newId]);

                $pdo->commit();
            }

            header('Location: index.php?ok=2');
            exit;
        }

        throw new RuntimeException('Acción inválida.');
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        $err = $e->getMessage();
    }
}

// Cargar sectores (orden inicial por código)
$items = sectores_fetch($pdo, false);
usort($items, fn($a, $b) => ((int)$a['id'] <=> (int)$b['id']));

$csrf = catalogo_csrf_token('sectores_admin_csrf');
?>
<!doctype html>
<html lang="es" class="app-html" <?= intranet_theme_html_attr(); ?>>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Administración · Sectores</title>
  <?= intranet_theme_bootstrap_script_tag(); ?>
  <link rel="stylesheet" href="<?= h(asset_url('styles/css/style.css')) ?>">
  <link rel="stylesheet" href="<?= h(asset_url('styles/css/theme-vars.css')) ?>">
  <script src="<?= h(asset_url('styles/js/table_sort.js')) ?>" defer></script>

  <style>
    /* --- Crear sector: alineado --- */
    .field{display:flex;flex-direction:column;gap:6px;}
    .field label{font-size:.8rem;font-weight:700;margin:0;}
    .control-row{height:45px;display:flex;align-items:center;gap:10px;}
    .control-row .form-control{height:45px;}
    .create-grid{
      display:grid;
      grid-template-columns: 140px 2fr 1.8fr 160px auto; /* código | nombre | color | activo | crear */
      gap:12px;
      align-items:end;
    }
    @media (max-width: 980px){
      .create-grid{grid-template-columns: 1fr; }
    }

    /* --- Color UI --- */
    .color-cell{display:flex;gap:10px;align-items:center;width:100%;}
    .color-swatch{
      width:18px;height:18px;border:1px solid rgba(0,0,0,.2);
      background:#fff;display:inline-block;
    }
    .color-swatch.circle{border-radius:50%;}
    .palette-btn{
      height:45px;padding:0 12px;border-radius:10px;
      border:1px solid var(--border-light);
      background:rgba(255,255,255,.08);
      cursor:pointer;white-space:nowrap;
    }
    dialog#colorDialog{
      border:none;border-radius:14px;padding:16px;
      max-width:520px;width:min(520px, 92vw);
    }
    dialog#colorDialog::backdrop{background:rgba(0,0,0,.35);}
    .palette-grid{
      display:grid;grid-template-columns:repeat(10, 28px);
      gap:10px;margin:12px 0 10px 0;
    }
    .palette-color{
      width:28px;height:28px;border-radius:10px;
      border:1px solid rgba(0,0,0,.15);cursor:pointer;
    }
    .palette-actions{
      display:flex;gap:10px;align-items:center;justify-content:flex-end;
      margin-top:12px;flex-wrap:wrap;
    }
    .muted-help{display:block;margin-top:4px;color:var(--text-muted);font-size:.9rem;}

    /* --- Tabla: layout --- */
    .table-tools{
      display:flex;gap:12px;align-items:center;justify-content:space-between;
      margin:10px 0 12px 0;flex-wrap:wrap;
    }
    .table-tools .form-control{max-width:320px;height:40px;}
    .code-input{max-width:90px;text-align:center;}
    .row-actions{display:flex;justify-content:center;align-items:center;}
  </style>
</head>

<body class="app-body">
<div class="app-container">
  <header class="header-top">
    <div>
      <h2 style="margin:0;">Administración · Sectores</h2>
      <p style="margin:5px 0 0 0; opacity:0.9;">Gestión de sectores comunes de toda la intranet</p>
    </div>
    <div class="header-actions">
      <a href="<?= h(asset_url('dashboard.php')) ?>" target="_top" class="btn-back-dashboard">Volver al inicio</a>
    </div>
  </header>

  <?php if ($msg): ?>
    <div class="alert admin-notice" style="margin-bottom:20px;"><?=h($msg)?></div>
  <?php endif; ?>
  <?php if ($err): ?>
    <div class="alert alert-error" style="margin-bottom:20px;"><?=h($err)?></div>
  <?php endif; ?>

  <section class="card" style="margin-bottom:20px;">
    <div class="card-title">➕ Crear sector</div>

    <form method="post" class="create-grid">
      <input type="hidden" name="csrf" value="<?=h($csrf)?>">
      <input type="hidden" name="action" value="add">

      <div class="field">
        <label for="newCodigo">Código (00–99)</label>
        <div class="control-row">
          <input
            class="form-control code-input"
            name="codigo"
            id="newCodigo"
            placeholder="00"
            inputmode="numeric"
            maxlength="2"
            autocomplete="off"
          >
        </div>
        <small class="muted-help">2 dígitos. Ej: 02, 17</small>
      </div>

      <div class="field">
        <label for="newNombre">Nombre</label>
        <div class="control-row">
          <input class="form-control" id="newNombre" name="nombre" required placeholder="Ej: Educación">
        </div>
        <small class="muted-help">Intenta no repetir nombres.</small>
      </div>

      <div class="field">
        <label for="newEmail">Email del sector (opcional)</label>
        <div class="control-row">
          <input class="form-control" id="newEmail" name="email" type="email" placeholder="sector@dominio">
        </div>
        <small class="muted-help">Se usa para notificaciones si el creador no tiene email.</small>
      </div>

      <div class="field">
        <label>Color</label>
        <div class="control-row">
          <div class="color-cell">
            <span id="newColorSwatch" class="color-swatch circle" style="background:#0ea5e9;"></span>
            <input
              class="form-control"
              name="color_hex"
              id="newColorHex"
              value="#0ea5e9"
              placeholder="#RRGGBB"
              maxlength="7"
              data-color-hex="1"
              data-swatch="newColorSwatch"
            >
            <button type="button" class="palette-btn" onclick="openColorDialog('newColorHex','newColorSwatch')">🎨 Elegir…</button>
          </div>
        </div>
        <small class="muted-help">Puedes escribir el hex o elegirlo en la paleta.</small>
      </div>

      <div class="field">
        <label>Activo</label>
        <div class="control-row" style="gap:8px;">
          <label style="display:flex;gap:8px;align-items:center;margin:0;">
            <input type="checkbox" name="activo" value="1" checked> <span>Sí</span>
          </label>
        </div>
        <small class="muted-help">SI/NO</small>
      </div>

      <div class="field">
        <label style="opacity:0;">Acción</label>
        <div class="control-row" style="justify-content:flex-end;">
          <button class="btn-primary" type="submit" style="height:45px; cursor:pointer;">Crear</button>
        </div>
      </div>
    </form>
  </section>

  <section class="card">
    <div class="card-title">🧾 Sectores</div>

    <div class="table-tools">
      <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;">
        <input id="tableFilter" class="form-control" placeholder="Buscar por código o nombre…">
        <small class="muted-help" style="margin:0;">Haz click en cabeceras para ordenar.</small>
      </div>
    </div>

    <form method="post">
      <input type="hidden" name="csrf" value="<?=h($csrf)?>">
      <input type="hidden" name="action" value="bulk_save">

      <div class="table-responsive" style="border:1px solid var(--border-light); border-radius:8px;">
        <table id="sectoresTable" class="table-sortable">
          <thead>
            <tr>
              <th data-sort-type="num">CÓDIGO</th>
              <th data-sort-type="text">NOMBRE</th>
              <th data-sort-type="text">EMAIL</th>
              <th data-sort-type="text">COLOR</th>
              <th data-sort-type="num">ACTIVO</th>
              <th>ACTUALIZAR</th>
              <th>ELIMINAR</th>
            </tr>
          </thead>
          <tbody>
          <?php if (empty($items)): ?>
            <tr><td colspan="6" style="padding:40px; color:var(--text-muted); font-style:italic;">No hay sectores.</td></tr>
          <?php else: ?>
            <?php foreach ($items as $i => $s): ?>
              <?php $id = (int)$s['id']; $hex = (string)($s['color_hex'] ?? ''); ?>
              <tr>
                <td data-sort="<?=h(pad2($id))?>">
                  <input type="hidden" name="sectores[<?=$i?>][old_id]" value="<?=$id?>">
                  <input
                    class="form-control code-input"
                    name="sectores[<?=$i?>][id]"
                    value="<?=h(pad2($id))?>"
                    inputmode="numeric"
                    maxlength="2"
                    autocomplete="off"
                    data-col="codigo"
                  >
                </td>

                <td data-sort="<?=h((string)$s['nombre'])?>">
                  <input class="form-control"
                         name="sectores[<?=$i?>][nombre]"
                         value="<?=h($s['nombre'])?>"
                         data-col="nombre">
                </td>

                <td data-sort="<?=h((string)($s['email'] ?? ''))?>">
                  <input class="form-control"
                         type="email"
                         name="sectores[<?=$i?>][email]"
                         value="<?=h($s['email'] ?? '')?>"
                         placeholder="correo@dominio"
                         data-col="email">
                </td>

                <td data-sort="<?=h($hex)?>">
                  <div class="color-cell">
                    <span
                      id="swatch-<?=$i?>"
                      class="color-swatch circle"
                      style="background: <?=h($hex !== '' ? $hex : '#ffffff')?>;"
                      title="<?=h($hex !== '' ? $hex : '#ffffff')?>"
                    ></span>

                    <input
                      class="form-control"
                      name="sectores[<?=$i?>][color_hex]"
                      id="color-<?=$i?>"
                      value="<?=h($hex)?>"
                      placeholder="#RRGGBB"
                      maxlength="7"
                      data-color-hex="1"
                      data-swatch="swatch-<?=$i?>"
                      data-col="color"
                    >

                    <button type="button" class="palette-btn" onclick="openColorDialog('color-<?=$i?>','swatch-<?=$i?>')">🎨</button>
                  </div>
                </td>

                <td style="text-align:center;" data-sort="<?= !empty($s['activo']) ? '1' : '0' ?>">
                  <input type="checkbox" name="sectores[<?=$i?>][activo]" value="1" <?= !empty($s['activo']) ? 'checked' : '' ?> data-col="activo">
                </td>

                <td style="text-align:center;">
                  <input type="checkbox" name="sectores[<?=$i?>][_update]" value="1">
                </td>

                <td style="text-align:center;">
                  <input type="checkbox" name="sectores[<?=$i?>][_delete]" value="1">
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>

      <div style="margin-top:15px; display:flex; justify-content:flex-end; gap:10px;">
        <button class="btn-primary" type="submit" style="cursor:pointer;">Guardar cambios</button>
      </div>

      <p style="margin-top:10px; color:var(--text-muted); font-size:0.9rem;">
        Marca “Actualizar” para aplicar cambios en una fila. Marca “Eliminar” para borrarla.
        <br>Si cambias el código, se actualizarán las reservas de flota que usen ese sector (si existen).
      </p>
    </form>
  </section>
</div>

<dialog id="colorDialog">
  <form method="dialog">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:10px;">
      <h3 style="margin:0;">Elegir color</h3>
      <button type="submit" class="palette-btn">✕</button>
    </div>

    <div class="palette-grid" id="paletteGrid"></div>

    <div class="palette-actions">
      <label style="display:flex;align-items:center;gap:10px;">
        <span style="color:var(--text-muted);">Personalizado</span>
        <input type="color" id="colorPicker" value="#0ea5e9" style="width:54px;height:34px;border:none;background:transparent;">
      </label>
      <button type="button" class="palette-btn" onclick="usePickerColor()">Usar</button>
    </div>
  </form>
</dialog>

<script>
  // ---------------- Color dialog ----------------
  let _targetInputId = null;
  let _targetSwatchId = null;

  const PALETTE = [
    '#0ea5e9','#0284c7','#1d4ed8','#4338ca','#7c3aed',
    '#9333ea','#c026d3','#db2777','#e11d48','#ef4444',
    '#f97316','#f59e0b','#eab308','#84cc16','#22c55e',
    '#10b981','#14b8a6','#06b6d4','#64748b','#334155',
    '#111827','#000000','#ffffff','#f8fafc','#e2e8f0'
  ];

  function normalizeHex(v){
    v = (v || '').trim();
    if(!v) return '';
    if(!v.startsWith('#')) v = '#' + v;
    if(/^#[0-9a-fA-F]{6}$/.test(v)) return v.toLowerCase();
    return '';
  }

  function applyColor(hex){
    if(!_targetInputId || !_targetSwatchId) return;
    const input = document.getElementById(_targetInputId);
    const sw = document.getElementById(_targetSwatchId);
    if(!input || !sw) return;

    input.value = hex;
    sw.style.background = hex;

    const picker = document.getElementById('colorPicker');
    if (picker) picker.value = hex;
  }

  function openColorDialog(inputId, swatchId){
    _targetInputId = inputId;
    _targetSwatchId = swatchId;

    const input = document.getElementById(inputId);
    const hex = normalizeHex(input?.value) || '#0ea5e9';

    const picker = document.getElementById('colorPicker');
    if (picker) picker.value = hex;

    const dlg = document.getElementById('colorDialog');
    if (dlg) dlg.showModal();
  }

  function usePickerColor(){
    const picker = document.getElementById('colorPicker');
    const hex = picker ? picker.value : '#0ea5e9';
    applyColor(hex);

    const dlg = document.getElementById('colorDialog');
    if (dlg) dlg.close();
  }

  (function buildPalette(){
    const grid = document.getElementById('paletteGrid');
    if(!grid) return;

    PALETTE.forEach(hex => {
      const b = document.createElement('button');
      b.type = 'button';
      b.className = 'palette-color';
      b.style.background = hex;
      b.title = hex;
      b.addEventListener('click', () => {
        applyColor(hex);
        const dlg = document.getElementById('colorDialog');
        if (dlg) dlg.close();
      });
      grid.appendChild(b);
    });
  })();

  document.addEventListener('input', (e) => {
    const el = e.target;
    if(!(el instanceof HTMLInputElement)) return;

    // Actualiza swatch al escribir hex
    if(el.dataset.colorHex){
      const swId = el.dataset.swatch;
      const sw = swId ? document.getElementById(swId) : null;
      const hex = normalizeHex(el.value);
      if(sw && hex) sw.style.background = hex;
    }

    // Forzar sólo números en códigos
    if (el.classList.contains('code-input')) {
      el.value = (el.value || '').replace(/[^\d]/g,'').slice(0,2);
    }
  });

  // Autopad a 2 dígitos al salir
  document.addEventListener('blur', (e) => {
    const el = e.target;
    if(!(el instanceof HTMLInputElement)) return;
    if (!el.classList.contains('code-input')) return;

    const v = (el.value || '').trim();
    if (v === '') return;
    const n = parseInt(v, 10);
    if (Number.isFinite(n)) el.value = String(n).padStart(2,'0');
  }, true);

  // ---------------- Filtro rápido ----------------
  const table = document.getElementById('sectoresTable');
  const tbody = table?.querySelector('tbody');

  function getRowValue(tr, key){
    if (!tr) return '';
    if (key === 'codigo') {
      const inp = tr.querySelector('input[data-col="codigo"]');
      return (inp?.value || '').trim();
    }
    if (key === 'nombre') {
      const inp = tr.querySelector('input[data-col="nombre"]');
      return (inp?.value || '').trim();
    }
    return '';
  }

  const filterInput = document.getElementById('tableFilter');
  filterInput?.addEventListener('input', () => {
    const q = (filterInput.value || '').trim().toLowerCase();
    if (!tbody) return;

    Array.from(tbody.querySelectorAll('tr')).forEach(tr => {
      const code = getRowValue(tr,'codigo').toLowerCase();
      const name = getRowValue(tr,'nombre').toLowerCase();
      const ok = (q === '') || code.includes(q) || name.includes(q);
      tr.style.display = ok ? '' : 'none';
    });
  });
</script>

</body>
</html>
