<?php
// admin_delegaciones.php
@session_start();
require __DIR__ . '/db.php';

$pdo = pdo();

// (Opcional) chequeo de sesión/admin
// if (empty($_SESSION['es_admin'])) { die('Acceso restringido'); }

$errores = [];
$ok = '';

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

/* ==========================
   Alta de delegaciones (POST)
   ========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['accion'] ?? '') === 'crear') {
    $nombre    = trim($_POST['nombre']    ?? '');
    $provincia = trim($_POST['provincia'] ?? '');
    $localidad = trim($_POST['localidad'] ?? '');
    $direccion = trim($_POST['direccion'] ?? '');
    $telefono  = trim($_POST['telefono']  ?? '');
    $email     = trim($_POST['email']     ?? '');

    if ($nombre === '')    { $errores[] = 'El nombre de la delegación es obligatorio.'; }
    if ($provincia === '') { $errores[] = 'La provincia es obligatoria.'; }

    if (!$errores) {
        $sql = "INSERT INTO delegaciones
                (nombre, provincia, localidad, direccion, telefono, email)
                VALUES
                (:nombre, :provincia, :localidad, :direccion, :telefono, :email)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            ':nombre'    => $nombre,
            ':provincia' => $provincia,
            ':localidad' => $localidad ?: null,
            ':direccion' => $direccion ?: null,
            ':telefono'  => $telefono ?: null,
            ':email'     => $email ?: null,
        ]);
        $ok = 'Delegación creada correctamente.';
    }
}

/* ==========================
   Borrado (GET ?del=ID)
   ========================== */
if (isset($_GET['del'])) {
    $idDel = (int)$_GET['del'];
    if ($idDel > 0) {
        $stmt = $pdo->prepare("DELETE FROM delegaciones WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $idDel]);
        $ok = 'Delegación eliminada.';
    }
}

/* ==========================
   Listado de delegaciones
   ========================== */
$stmt = $pdo->query("SELECT * FROM delegaciones ORDER BY provincia ASC, localidad ASC, nombre ASC");
$delegaciones = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="utf-8">
    <title>Admin Delegaciones - Fe.Tr.A.</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
      :root {
        --primary: #004b8d;
        --primary-light: #e9f2ff;
        --secondary: #f8f9fa;
        --accent: #00a8e8;
        --success: #28a745;
        --danger: #dc3545;
        --warning: #ffc107;
        --dark: #212529;
        --light: #f8f9fa;
        --border-radius: 12px;
        --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        --transition: all 0.3s ease;
      }
      
      * {
        font-family: 'Inter', sans-serif;
      }
      
      body {
        background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
        min-height: 100vh;
        color: var(--dark);
      }
      
      .page-title {
        padding: 1.5rem 0;
        margin-bottom: 2rem;
        position: relative;
      }
      
      .page-title::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 60px;
        height: 4px;
        background: linear-gradient(90deg, var(--primary), var(--accent));
        border-radius: 2px;
      }
      
      .card-form {
        border-radius: var(--border-radius);
        border: none;
        box-shadow: var(--box-shadow);
        transition: var(--transition);
        overflow: hidden;
      }
      
      .card-form:hover {
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      }
      
      .card-header {
        background: linear-gradient(135deg, var(--primary), #003366);
        border: none;
        padding: 1.25rem 1.5rem;
        position: relative;
      }
      
      .card-header::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.1), transparent);
        transform: translateX(-100%);
        transition: transform 0.6s ease;
      }
      
      .card:hover .card-header::before {
        transform: translateX(100%);
      }
      
      .table-container {
        border-radius: var(--border-radius);
        overflow: hidden;
        box-shadow: var(--box-shadow);
      }
      
      .table thead th {
        background: linear-gradient(135deg, var(--primary), #003366);
        color: #fff;
        white-space: nowrap;
        padding: 1rem 1.25rem;
        font-weight: 600;
        border: none;
        position: relative;
      }
      
      .table thead th::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 2px;
        background: rgba(255, 255, 255, 0.2);
      }
      
      .table tbody tr {
        transition: var(--transition);
      }
      
      .table tbody tr:hover {
        background-color: rgba(0, 75, 141, 0.05);
        transform: translateY(-2px);
      }
      
      .table tbody td {
        padding: 1rem 1.25rem;
        vertical-align: middle;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
      }
      
      .badge-provincia {
        background: var(--primary-light);
        color: var(--primary);
        font-weight: 600;
        font-size: .75rem;
        border-radius: 999px;
        padding: 0.3rem 0.8rem;
        box-shadow: 0 2px 4px rgba(0, 75, 141, 0.1);
      }
      
      .btn-primary {
        background: linear-gradient(135deg, var(--primary), #003366);
        border: none;
        border-radius: 8px;
        padding: 0.75rem 1.5rem;
        font-weight: 600;
        transition: var(--transition);
        box-shadow: 0 4px 8px rgba(0, 75, 141, 0.2);
      }
      
      .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(0, 75, 141, 0.3);
        background: linear-gradient(135deg, #003366, var(--primary));
      }
      
      .btn-outline-danger {
        border-radius: 6px;
        padding: 0.4rem 0.8rem;
        font-size: 0.875rem;
        transition: var(--transition);
        border-width: 1.5px;
      }
      
      .btn-outline-danger:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 8px rgba(220, 53, 69, 0.2);
      }
      
      .form-control {
        border-radius: 8px;
        padding: 0.75rem 1rem;
        border: 1.5px solid #e1e5eb;
        transition: var(--transition);
        font-size: 0.95rem;
      }
      
      .form-control:focus {
        border-color: var(--primary);
        box-shadow: 0 0 0 0.25rem rgba(0, 75, 141, 0.15);
      }
      
      .alert {
        border-radius: var(--border-radius);
        border: none;
        padding: 1rem 1.5rem;
        box-shadow: var(--box-shadow);
      }
      
      .alert-success {
        background: linear-gradient(135deg, #d4edda, #c3e6cb);
        color: #155724;
      }
      
      .alert-danger {
        background: linear-gradient(135deg, #f8d7da, #f1b0b7);
        color: #721c24;
      }
      
      .empty-state {
        padding: 3rem 1rem;
        text-align: center;
        color: #6c757d;
      }
      
      .empty-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
        color: #dee2e6;
      }
      
      .stats-card {
        background: linear-gradient(135deg, #ffffff, #f8f9fa);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        box-shadow: var(--box-shadow);
        text-align: center;
        transition: var(--transition);
      }
      
      .stats-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
      }
      
      .stats-number {
        font-size: 2.5rem;
        font-weight: 700;
        color: var(--primary);
        line-height: 1;
        margin-bottom: 0.5rem;
      }
      
      .stats-label {
        font-size: 0.875rem;
        color: #6c757d;
        font-weight: 500;
      }
      
      .logo-container {
        display: flex;
        align-items: center;
        gap: 0.75rem;
      }
      
      .logo-icon {
        width: 40px;
        height: 40px;
        background: linear-gradient(135deg, var(--primary), var(--accent));
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-weight: bold;
      }
      
      .section-title {
        font-weight: 600;
        margin-bottom: 1.5rem;
        position: relative;
        padding-bottom: 0.75rem;
      }
      
      .section-title::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 40px;
        height: 3px;
        background: linear-gradient(90deg, var(--primary), var(--accent));
        border-radius: 2px;
      }
      
      @media (max-width: 768px) {
        .table-responsive {
          border-radius: var(--border-radius);
        }
        
        .stats-card {
          margin-bottom: 1rem;
        }
      }
    </style>
</head>
<body>

<?php
// Si tenés una navbar de admin, acá iría:
// include __DIR__ . '/_admin_navbar.php';
?>

<div class="container my-5">

  <div class="page-title d-flex justify-content-between align-items-center">
    <div class="logo-container">
      <div class="logo-icon">
        <i class="bi bi-building"></i>
      </div>
      <div>
        <h1 class="h3 mb-0 fw-bold">Administrar Delegaciones</h1>
        <p class="text-muted mb-0">Fe.Tr.A. - Federación de Trabajadores Argentinos</p>
      </div>
    </div>
    <div class="d-none d-md-flex align-items-center gap-3">
      <div class="stats-card">
        <div class="stats-number"><?= count($delegaciones) ?></div>
        <div class="stats-label">Delegaciones</div>
      </div>
    </div>
  </div>

  <?php if ($errores): ?>
    <div class="alert alert-danger d-flex align-items-center">
      <i class="bi bi-exclamation-triangle-fill me-3 fs-4"></i>
      <div>
        <h5 class="alert-heading mb-2">Error en el formulario</h5>
        <ul class="mb-0 ps-3">
          <?php foreach ($errores as $e): ?>
            <li><?= e($e) ?></li>
          <?php endforeach; ?>
        </ul>
      </div>
    </div>
  <?php endif; ?>

  <?php if ($ok): ?>
    <div class="alert alert-success d-flex align-items-center">
      <i class="bi bi-check-circle-fill me-3 fs-4"></i>
      <div>
        <h5 class="alert-heading mb-1">¡Operación exitosa!</h5>
        <p class="mb-0"><?= e($ok) ?></p>
      </div>
    </div>
  <?php endif; ?>

  <div class="row g-4">
    <!-- Formulario alta -->
    <div class="col-12 col-lg-4">
      <div class="card card-form">
        <div class="card-header text-white">
          <div class="d-flex align-items-center">
            <i class="bi bi-plus-circle me-2 fs-5"></i>
            <h5 class="mb-0 fw-bold">Nueva delegación</h5>
          </div>
        </div>
        <div class="card-body p-4">
          <form method="post">
            <input type="hidden" name="accion" value="crear">

            <div class="mb-3">
              <label class="form-label fw-semibold">Nombre de la delegación <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text bg-light"><i class="bi bi-building"></i></span>
                <input type="text" name="nombre" class="form-control" required placeholder="Ej: Delegación Central">
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Provincia <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text bg-light"><i class="bi bi-geo-alt"></i></span>
                <input type="text" name="provincia" class="form-control" required placeholder="Ej: Buenos Aires">
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Localidad / Ciudad</label>
              <div class="input-group">
                <span class="input-group-text bg-light"><i class="bi bi-geo"></i></span>
                <input type="text" name="localidad" class="form-control" placeholder="Ej: Lomas de Zamora">
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Dirección</label>
              <div class="input-group">
                <span class="input-group-text bg-light"><i class="bi bi-house-door"></i></span>
                <input type="text" name="direccion" class="form-control" placeholder="Calle, número, piso...">
              </div>
            </div>

            <div class="mb-3">
              <label class="form-label fw-semibold">Teléfono</label>
              <div class="input-group">
                <span class="input-group-text bg-light"><i class="bi bi-telephone"></i></span>
                <input type="text" name="telefono" class="form-control" placeholder="Ej: 011-1234-5678">
              </div>
            </div>

            <div class="mb-4">
              <label class="form-label fw-semibold">Email</label>
              <div class="input-group">
                <span class="input-group-text bg-light"><i class="bi bi-envelope"></i></span>
                <input type="email" name="email" class="form-control" placeholder="delegacion@fetra.org.ar">
              </div>
            </div>

            <div class="d-grid">
              <button type="submit" class="btn btn-primary fw-semibold py-2">
                <i class="bi bi-check-lg me-2"></i>Guardar delegación
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Listado -->
    <div class="col-12 col-lg-8">
      <div class="table-container">
        <div class="card border-0">
          <div class="card-header bg-light d-flex justify-content-between align-items-center">
            <h5 class="mb-0 fw-bold"><i class="bi bi-list-ul me-2"></i>Delegaciones cargadas</h5>
            <span class="badge bg-primary rounded-pill"><?= count($delegaciones) ?></span>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-hover mb-0">
                <thead>
                  <tr>
                    <th>#</th>
                    <th>Delegación</th>
                    <th>Provincia</th>
                    <th>Localidad</th>
                    <th>Contacto</th>
                    <th class="text-center">Acciones</th>
                  </tr>
                </thead>
                <tbody>
                  <?php if (!$delegaciones): ?>
                    <tr>
                      <td colspan="6" class="empty-state">
                        <i class="bi bi-inbox"></i>
                        <h5 class="fw-semibold">No hay delegaciones cargadas</h5>
                        <p class="text-muted">Comienza agregando una nueva delegación usando el formulario.</p>
                      </td>
                    </tr>
                  <?php else: ?>
                    <?php foreach ($delegaciones as $d): ?>
                      <tr>
                        <td class="fw-semibold"><?= (int)$d['id'] ?></td>
                        <td>
                          <div class="fw-semibold"><?= e($d['nombre']) ?></div>
                          <?php if (!empty($d['email'])): ?>
                            <small class="text-muted"><?= e($d['email']) ?></small>
                          <?php endif; ?>
                        </td>
                        <td>
                          <span class="badge badge-provincia">
                            <i class="bi bi-geo-alt-fill me-1"></i><?= e($d['provincia']) ?>
                          </span>
                        </td>
                        <td><?= e($d['localidad'] ?? '') ?></td>
                        <td>
                          <?php if (!empty($d['telefono'])): ?>
                            <div class="d-flex align-items-center mb-1">
                              <i class="bi bi-telephone text-primary me-2"></i>
                              <small><?= e($d['telefono']) ?></small>
                            </div>
                          <?php endif; ?>
                          <?php if (!empty($d['direccion'])): ?>
                            <div class="d-flex align-items-center">
                              <i class="bi bi-geo text-muted me-2"></i>
                              <small class="text-truncate" style="max-width: 150px;" title="<?= e($d['direccion']) ?>">
                                <?= e($d['direccion']) ?>
                              </small>
                            </div>
                          <?php endif; ?>
                        </td>
                        <td class="text-center">
                          <a href="?del=<?= (int)$d['id'] ?>"
                             class="btn btn-sm btn-outline-danger"
                             onclick="return confirm('¿Está seguro de que desea eliminar la delegación <?= e($d['nombre']) ?>?');">
                            <i class="bi bi-trash me-1"></i>Eliminar
                          </a>
                        </td>
                      </tr>
                    <?php endforeach; ?>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Estadísticas adicionales -->
      <?php if ($delegaciones): ?>
        <div class="row mt-4">
          <div class="col-12">
            <h5 class="section-title">Resumen por provincia</h5>
          </div>
          <?php
          // Contar delegaciones por provincia
          $provincias_count = [];
          foreach ($delegaciones as $d) {
              $provincia = $d['provincia'];
              if (!isset($provincias_count[$provincia])) {
                  $provincias_count[$provincia] = 0;
              }
              $provincias_count[$provincia]++;
          }
          ?>
          <?php foreach ($provincias_count as $provincia => $count): ?>
            <div class="col-6 col-md-4 col-lg-3 mb-3">
              <div class="stats-card">
                <div class="stats-number"><?= $count ?></div>
                <div class="stats-label"><?= e($provincia) ?></div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endif; ?>
    </div>

  </div><!-- row -->

</div><!-- container -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  // Efectos adicionales para mejorar la experiencia
  document.addEventListener('DOMContentLoaded', function() {
    // Agregar animación a las filas de la tabla
    const tableRows = document.querySelectorAll('tbody tr');
    tableRows.forEach((row, index) => {
      row.style.opacity = '0';
      row.style.transform = 'translateY(10px)';
      
      setTimeout(() => {
        row.style.transition = 'opacity 0.4s ease, transform 0.4s ease';
        row.style.opacity = '1';
        row.style.transform = 'translateY(0)';
      }, index * 50);
    });
    
    // Mejorar el mensaje de confirmación de eliminación
    const deleteButtons = document.querySelectorAll('.btn-outline-danger');
    deleteButtons.forEach(button => {
      button.addEventListener('click', function(e) {
        if (!confirm('¿Está seguro de que desea eliminar esta delegación? Esta acción no se puede deshacer.')) {
          e.preventDefault();
        }
      });
    });
  });
</script>
</body>
</html>