<?php
/**
 * public/acceso/login.php
 * Pantalla de Inicio de Sesión de Alta Seguridad — Cyfort Access Pro
 */
declare(strict_types=1);

require_once __DIR__ . '/session_boot.php';
require_once __DIR__ . '/config/db.php';

$error = '';
$msg = '';

if (isset($_GET['logout']) || isset($_GET['salir'])) {
    $_SESSION = [];
    if (isset($_SESSION['acceso_user'])) {
        unset($_SESSION['acceso_user']);
    }
    @session_unset();
    @session_destroy();
    $msg = 'Sesión cerrada correctamente.';
} elseif (!empty($_SESSION['acceso_user'])) {
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim((string)($_POST['username'] ?? ''));
    $password = (string)($_POST['password'] ?? '');

    if ($username === '' || $password === '') {
        $error = 'Por favor ingresa usuario y contraseña.';
    } else {
        try {
            $pdo = acceso_db();
            $stmt = $pdo->prepare("SELECT * FROM acceso_usuarios WHERE username = ? AND estado = 'activo'");
            $stmt->execute([$username]);
            $usr = $stmt->fetch();

            if ($usr && password_verify($password, $usr['password_hash'])) {
                $_SESSION['acceso_user'] = [
                    'id' => (int)$usr['id'],
                    'username' => $usr['username'],
                    'nombre' => $usr['nombre'],
                    'email' => $usr['email'],
                    'rol' => $usr['rol'],
                    'empresa_id' => (int)$usr['empresa_id']
                ];
                header('Location: index.php');
                exit;
            } else {
                $error = 'Credenciales de acceso incorrectas.';
            }
        } catch (Throwable $ex) {
            $error = 'Error de conexión: ' . $ex->getMessage();
        }
    }
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Cyfort Access Pro — Iniciar Sesión</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="../logoprincipal.png" type="image/png">
  <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@400;500;600;700;800;900&display=swap" rel="stylesheet">
  
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }
    body {
      font-family: 'Inter', system-ui, -apple-system, sans-serif;
      background: #090d16;
      color: #f8fafc;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
      position: relative;
      overflow-x: hidden;
    }

    body::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      width: 100vw;
      height: 100vh;
      background: radial-gradient(circle at 50% 20%, rgba(99, 102, 241, 0.18), transparent 50%),
                  radial-gradient(circle at 80% 80%, rgba(16, 185, 129, 0.12), transparent 45%),
                  #090d16;
      z-index: 0;
      pointer-events: none;
    }

    .login-container {
      position: relative;
      z-index: 10;
      max-width: 440px;
      width: 100%;
    }

    .login-card {
      background: rgba(15, 23, 42, 0.85);
      border: 1px solid rgba(255, 255, 255, 0.12);
      border-radius: 28px;
      width: 100%;
      padding: 36px 32px;
      box-shadow: 0 25px 60px rgba(0, 0, 0, 0.7), 0 0 40px rgba(99, 102, 241, 0.15);
      backdrop-filter: blur(24px);
      -webkit-backdrop-filter: blur(24px);
      text-align: center;
    }

    .logo-badge {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      margin-bottom: 20px;
    }
    .logo-ring {
      padding: 4px;
      background: linear-gradient(135deg, #6366f1, #10b981);
      border-radius: 50%;
      box-shadow: 0 0 25px rgba(99, 102, 241, 0.4);
    }
    .logo-ring img {
      width: 84px;
      height: 84px;
      border-radius: 50%;
      object-fit: cover;
      display: block;
    }

    h1 {
      font-size: 1.85rem;
      font-weight: 900;
      color: #fff;
      margin: 0 0 6px 0;
      letter-spacing: -0.5px;
      background: linear-gradient(135deg, #ffffff, #cbd5e1);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    .subtitle {
      color: #94a3b8;
      font-size: 0.88rem;
      font-weight: 500;
      margin: 0 0 28px 0;
    }

    .form-group { text-align: left; margin-bottom: 20px; }
    label {
      display: block;
      font-size: 0.82rem;
      font-weight: 800;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      color: #a78bfa;
      margin-bottom: 8px;
    }
    input[type="text"], input[type="password"] {
      width: 100%;
      box-sizing: border-box;
      padding: 14px 16px;
      background: rgba(30, 41, 59, 0.7);
      border: 1px solid rgba(255, 255, 255, 0.14);
      border-radius: 14px;
      color: #fff;
      font-size: 0.95rem;
      outline: none;
      transition: all 0.2s ease;
    }
    input[type="text"]:focus, input[type="password"]:focus {
      border-color: #6366f1;
      box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.25);
    }

    .btn-submit {
      width: 100%;
      padding: 16px;
      background: linear-gradient(135deg, #6366f1, #4f46e5);
      color: #fff;
      font-size: 1rem;
      font-weight: 800;
      letter-spacing: 0.5px;
      border: none;
      border-radius: 16px;
      cursor: pointer;
      box-shadow: 0 10px 30px rgba(99, 102, 241, 0.4);
      transition: all 0.2s ease;
      margin-top: 10px;
    }
    .btn-submit:hover {
      transform: translateY(-2px);
      box-shadow: 0 12px 35px rgba(99, 102, 241, 0.6);
    }
    
    .alert-error {
      background: rgba(239, 68, 68, 0.15);
      border: 1px solid #ef4444;
      color: #f87171;
      padding: 12px 16px;
      border-radius: 14px;
      font-size: 0.88rem;
      font-weight: 600;
      margin-bottom: 20px;
      text-align: center;
    }

    .btn-link {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      width: 100%;
      padding: 12px;
      border-radius: 14px;
      text-decoration: none;
      font-weight: 700;
      font-size: 0.85rem;
      transition: all 0.2s ease;
      box-sizing: border-box;
    }
  </style>
</head>
<body>

  <div class="login-container">
    <div class="login-card">
      <div class="logo-badge">
        <div class="logo-ring">
          <img src="../logoprincipal.png" alt="Cyfort Access Pro Logo" onerror="this.src='../media/bg-image.png'">
        </div>
      </div>

      <h1>Cyfort Access Pro</h1>
      <p class="subtitle">Plataforma Enterprise de Control de Acceso & LPR IA</p>

      <?php if ($msg !== ''): ?>
        <div style="background:rgba(16,185,129,0.15); border:1px solid #10b981; color:#34d399; padding:12px 16px; border-radius:14px; font-size:0.88rem; font-weight:600; margin-bottom:20px; text-align:center;">ℹ️ <?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8') ?></div>
      <?php endif; ?>

      <?php if ($error !== ''): ?>
        <div class="alert-error">⚠️ <?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
      <?php endif; ?>

      <form method="POST" action="login.php">
        <div class="form-group">
          <label>Nombre de Usuario</label>
          <input type="text" name="username" value="" placeholder="Ingresa tu usuario" required autocomplete="username">
        </div>

        <div class="form-group">
          <label>Contraseña de Seguridad</label>
          <input type="password" name="password" value="" placeholder="••••••••" required autocomplete="current-password">
        </div>

        <button type="submit" class="btn-submit">INGRESAR A CYFORT ACCESS PRO</button>
      </form>

      <!-- Enlaces Exclusivos de Descargas de Cyfort Access Pro -->
      <div style="margin-top: 24px; border-top: 1px solid rgba(255,255,255,0.08); padding-top: 18px; display:flex; flex-direction:column; gap:10px;">
        <a href="download_app.php" download class="btn-link" style="background: rgba(16, 185, 129, 0.15); border: 1px solid #10b981; color: #34d399;">
          <span>📲</span> Descargar App Android (app-debug.apk)
        </a>

        <a href="download_installer.php" download class="btn-link" style="background: rgba(99, 102, 241, 0.15); border: 1.5px solid #6366f1; color: #818cf8;">
          <span>💾</span> Descargar Instalador Consola Local (.zip)
        </a>
      </div>

      <div style="text-align: center; margin-top: 20px; color: #64748b; font-size: 0.8rem; font-weight: 500; display: flex; flex-direction: column; gap: 6px; align-items: center;">
        <div>
          <a href="../politica_privacidad.php" style="color: #94a3b8; text-decoration: underline; font-weight: 600;">Política de Privacidad & Habeas Data</a> • 
          <a href="../terminos_condiciones.php" style="color: #94a3b8; text-decoration: underline; font-weight: 600;">Términos de Servicio</a>
        </div>
        <div>© 2026 <strong>Cyfort Access Pro</strong> • Control de Acceso Cero Contacto</div>
      </div>
    </div>
  </div>

</body>
</html>
