<?php
// File: /fuelpos/admin_login.php
// Login page con detección automática de rol y redirección inteligente

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require __DIR__ . '/init.php';
if (session_status() === PHP_SESSION_NONE) session_start();

function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

try {
    $pdo = pdo();
} catch (Throwable $e) {
    http_response_code(500);
    echo "<h3>Error inicializando la aplicación</h3><pre>" . esc($e->getMessage()) . "</pre>";
    exit;
}

/**
 * Encuentra la primera columna tipo "password" disponible
 */
function first_existing_col_local(PDO $pdo, array $names) {
    foreach ($names as $n) {
        $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME='users' AND COLUMN_NAME = ?");
        $st->execute([$n]);
        if ((int)$st->fetchColumn() > 0) return $n;
    }
    return null;
}

function col_exists_local(PDO $pdo, string $table, string $col): bool {
    try {
        $st = $pdo->prepare("SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ?");
        $st->execute([$table, $col]);
        return (int)$st->fetchColumn() > 0;
    } catch (Exception $e) {
        return false;
    }
}

$pwdCol = first_existing_col_local($pdo, ['password','password_hash','passwd','pass']);
$fullNameCol = col_exists_local($pdo, 'users', 'full_name') ? 'full_name' : null;

$err = '';
$success = '';

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

    if ($username === '' || $password === '') {
        $err = 'Usuario y contraseña son requeridos.';
    } else {
        // Construir query con columnas opcionales
        $selectCols = ["id", "username"];
        if ($pwdCol) $selectCols[] = "{$pwdCol} AS pwd";
        if ($fullNameCol) $selectCols[] = "{$fullNameCol} AS full_name";
        
        $sql = "SELECT " . implode(', ', $selectCols) . " FROM users WHERE username = ? LIMIT 1";

        try {
            $st = $pdo->prepare($sql);
            $st->execute([$username]);
            $u = $st->fetch(PDO::FETCH_ASSOC);
        } catch (Throwable $e) {
            error_log("admin_login.php DB error: " . $e->getMessage());
            $u = false;
            $err = 'Error consultando la base de datos.';
        }

        if (!$u) {
            $err = $err ?: 'Usuario no encontrado.';
        } else {
            $hash = $u['pwd'] ?? '';
            $ok = false;

            if ($pwdCol && $hash) {
                // Verificar contraseña
                if (is_string($hash) && (strpos($hash, '$2y$') === 0 || strpos($hash, '$2a$') === 0 || stripos($hash,'argon2') !== false)) {
                    if (password_verify($password, $hash)) $ok = true;
                } else {
                    if ($password === $hash) $ok = true;
                }
            } else {
                $err = 'La tabla users no tiene columna de contraseñas configurada.';
            }

            if ($ok) {
                // ✅ CARGAR ROLES COMPLETOS
                $roles = [];
                $roleIds = [];
                $isAdmin = false;
                $isCashier = false;
                
                try {
                    $ridSt = $pdo->prepare("
                        SELECT r.id, r.name, r.is_admin 
                        FROM roles r 
                        JOIN user_roles ur ON ur.role_id = r.id 
                        WHERE ur.user_id = ?
                    ");
                    $ridSt->execute([$u['id']]);
                    $roles = $ridSt->fetchAll(PDO::FETCH_ASSOC);
                    
                    foreach ($roles as $r) {
                        $roleIds[] = (int)$r['id'];
                        
                        // Detectar administrador
                        if (!empty($r['is_admin'])) {
                            $isAdmin = true;
                        }
                        
                        // Detectar roles específicos
                        $roleName = strtolower(trim($r['name'] ?? ''));
                        if (in_array($roleName, ['administrator','admin','administrador'])) {
                            $isAdmin = true;
                        }
                        if (in_array($roleName, ['cashier','cajero','caja'])) {
                            $isCashier = true;
                        }
                    }
                } catch (Throwable $e) {
                    error_log("admin_login.php roles load error: " . $e->getMessage());
                }

                // ✅ FALLBACK: leer users.role (texto)
                if (!$isAdmin && !$isCashier) {
                    try {
                        $st2 = $pdo->prepare("SELECT COALESCE(role, '') AS role_text FROM users WHERE id = ? LIMIT 1");
                        $st2->execute([$u['id']]);
                        $roleText = (string)$st2->fetchColumn();
                        if ($roleText !== '') {
                            $parts = array_map('trim', explode(',', strtolower($roleText)));
                            foreach ($parts as $p) {
                                if (in_array($p, ['administrator','admin','administrador'])) $isAdmin = true;
                                if (in_array($p, ['cashier','cajero','caja'])) $isCashier = true;
                            }
                        }
                    } catch (Throwable $e) {
                        error_log("admin_login.php fallback role_text error: " . $e->getMessage());
                    }
                }

                // ✅ GUARDAR SESIÓN COMPLETA
                session_regenerate_id(true);
                $_SESSION['user_id'] = (int)$u['id'];
                $_SESSION['username'] = $u['username'];
                $_SESSION['full_name'] = $u['full_name'] ?? $u['username'];
                $_SESSION['roles'] = $roles;
                $_SESSION['role_ids'] = $roleIds;
                $_SESSION['is_admin'] = $isAdmin ? 1 : 0;
                $_SESSION['is_cashier'] = $isCashier ? 1 : 0;

                // ✅ REDIRECCIÓN INTELIGENTE
                if ($isAdmin) {
                    // Administrador -> Dashboard principal
                    header('Location: ' . site('index.php'));
                    exit;
                } elseif ($isCashier) {
                    // Cajero -> Dashboard de cajero
                    header('Location: ' . site('cashier_dashboard.php'));
                    exit;
                } elseif (in_array(2, $roleIds)) {
                    // ID 2 es Cashier -> Dashboard de cajero
                    header('Location: ' . site('cashier_dashboard.php'));
                    exit;
                } else {
                    // Otros usuarios -> Dashboard general
                    header('Location: ' . site('index.php'));
                    exit;
                }
            } else {
                $err = $err ?: 'Contraseña incorrecta.';
            }
        }
    }
}

// Obtener info de la estación para el logo
$station = null;
try {
    $station = $pdo->query("SELECT * FROM stations LIMIT 1")->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Ignorar error
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Iniciar Sesión - <?= esc($station['nombre'] ?? 'FuelPOS') ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
  <style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
    
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      font-family: 'Inter', sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
      position: relative;
      overflow: hidden;
    }
    
    body::before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px);
      background-size: 50px 50px;
      animation: backgroundMove 20s linear infinite;
    }
    
    @keyframes backgroundMove {
      0% { transform: translate(0, 0); }
      100% { transform: translate(50px, 50px); }
    }
    
    .login-container {
      position: relative;
      z-index: 1;
      width: 100%;
      max-width: 450px;
    }
    
    .login-card {
      background: white;
      border-radius: 25px;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
      overflow: hidden;
      animation: slideUp 0.6s ease;
    }
    
    @keyframes slideUp {
      from {
        opacity: 0;
        transform: translateY(50px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    
    .login-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 40px 30px;
      text-align: center;
      position: relative;
    }
    
    .login-header::before {
      content: '';
      position: absolute;
      bottom: -30px;
      left: 50%;
      transform: translateX(-50%);
      width: 80px;
      height: 80px;
      background: white;
      border-radius: 50%;
      box-shadow: 0 5px 20px rgba(0,0,0,0.2);
    }
    
    .login-icon {
      position: absolute;
      bottom: -30px;
      left: 50%;
      transform: translateX(-50%);
      width: 80px;
      height: 80px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 36px;
      color: white;
      box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
      z-index: 10;
    }
    
    .login-header h1 {
      font-size: 28px;
      font-weight: 800;
      margin: 0 0 8px 0;
    }
    
    .login-header p {
      font-size: 14px;
      opacity: 0.9;
      margin: 0;
    }
    
    .login-body {
      padding: 60px 40px 40px;
    }
    
    .form-label {
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
      font-size: 14px;
    }
    
    .form-control {
      border: 2px solid #e9ecef;
      border-radius: 12px;
      padding: 12px 16px;
      font-size: 15px;
      transition: all 0.3s ease;
    }
    
    .form-control:focus {
      border-color: #667eea;
      box-shadow: 0 0 0 4px rgba(102, 126, 234, 0.1);
    }
    
    .input-group {
      position: relative;
    }
    
    .input-group .form-control {
      padding-left: 48px;
    }
    
    .input-icon {
      position: absolute;
      left: 16px;
      top: 50%;
      transform: translateY(-50%);
      color: #667eea;
      font-size: 18px;
      z-index: 10;
    }
    
    .btn-login {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      border-radius: 12px;
      padding: 14px;
      font-size: 16px;
      font-weight: 700;
      color: white;
      width: 100%;
      transition: all 0.3s ease;
      box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }
    
    .btn-login:hover {
      transform: translateY(-2px);
      box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }
    
    .btn-login:active {
      transform: translateY(0);
    }
    
    .alert {
      border-radius: 12px;
      border: none;
      padding: 12px 16px;
      margin-bottom: 20px;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .alert-danger {
      background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%);
      color: white;
    }
    
    .alert-success {
      background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
      color: white;
    }
    
    .form-footer {
      text-align: center;
      margin-top: 25px;
      padding-top: 25px;
      border-top: 1px solid #e9ecef;
    }
    
    .form-footer small {
      color: #666;
      font-size: 13px;
    }
    
    .features {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
      margin-top: 20px;
    }
    
    .feature-item {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 13px;
      color: #666;
    }
    
    .feature-icon {
      width: 35px;
      height: 35px;
      border-radius: 8px;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      color: #667eea;
      font-size: 16px;
    }
    
    .password-toggle {
      position: absolute;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
      cursor: pointer;
      color: #999;
      font-size: 18px;
      z-index: 10;
      transition: color 0.3s ease;
    }
    
    .password-toggle:hover {
      color: #667eea;
    }
    
    @media (max-width: 576px) {
      .login-body {
        padding: 60px 25px 25px;
      }
      
      .features {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>

<div class="login-container">
  <div class="login-card">
    <div class="login-header">
      <h1><?= esc($station['nombre'] ?? 'FuelPOS') ?></h1>
      <p>Sistema de Gestión de Combustibles</p>
      <div class="login-icon">
        <i class="bi bi-fuel-pump-fill"></i>
      </div>
    </div>
    
    <div class="login-body">
      <?php if (!empty($err)): ?>
        <div class="alert alert-danger">
          <i class="bi bi-exclamation-triangle-fill"></i>
          <span><?= esc($err) ?></span>
        </div>
      <?php endif; ?>
      
      <?php if (!empty($success)): ?>
        <div class="alert alert-success">
          <i class="bi bi-check-circle-fill"></i>
          <span><?= esc($success) ?></span>
        </div>
      <?php endif; ?>
      
      <form method="post" autocomplete="off">
        <div class="mb-4">
          <label class="form-label">
            <i class="bi bi-person-fill"></i> Usuario
          </label>
          <div class="input-group">
            <i class="input-icon bi bi-person-circle"></i>
            <input 
              class="form-control" 
              name="username" 
              type="text"
              placeholder="Ingresa tu usuario"
              value="<?= esc($_POST['username'] ?? '') ?>" 
              required 
              autofocus
            >
          </div>
        </div>
        
        <div class="mb-4">
          <label class="form-label">
            <i class="bi bi-lock-fill"></i> Contraseña
          </label>
          <div class="input-group">
            <i class="input-icon bi bi-shield-lock"></i>
            <input 
              class="form-control" 
              name="password" 
              type="password"
              id="passwordInput"
              placeholder="Ingresa tu contraseña"
              required
            >
            <i class="password-toggle bi bi-eye" id="togglePassword"></i>
          </div>
        </div>
        
        <button class="btn btn-login" type="submit">
          <i class="bi bi-box-arrow-in-right"></i> Iniciar Sesión
        </button>
      </form>
      
      <div class="features">
        <div class="feature-item">
          <div class="feature-icon">
            <i class="bi bi-shield-check"></i>
          </div>
          <span>Acceso seguro</span>
        </div>
        <div class="feature-item">
          <div class="feature-icon">
            <i class="bi bi-speedometer2"></i>
          </div>
          <span>Dashboard en tiempo real</span>
        </div>
        <div class="feature-item">
          <div class="feature-icon">
            <i class="bi bi-people-fill"></i>
          </div>
          <span>Roles personalizados</span>
        </div>
        <div class="feature-item">
          <div class="feature-icon">
            <i class="bi bi-graph-up"></i>
          </div>
          <span>Reportes avanzados</span>
        </div>
      </div>
      
      <div class="form-footer">
        <small>
          <?php if (!$pwdCol): ?>
            <i class="bi bi-info-circle"></i>
            Advertencia: No se detectó columna de contraseñas en la BD.
          <?php else: ?>
            <i class="bi bi-shield-check"></i>
            Conexión segura con encriptación
          <?php endif; ?>
        </small>
      </div>
    </div>
  </div>
</div>

<script>
// Toggle password visibility
document.getElementById('togglePassword').addEventListener('click', function() {
  const passwordInput = document.getElementById('passwordInput');
  const icon = this;
  
  if (passwordInput.type === 'password') {
    passwordInput.type = 'text';
    icon.classList.remove('bi-eye');
    icon.classList.add('bi-eye-slash');
  } else {
    passwordInput.type = 'password';
    icon.classList.remove('bi-eye-slash');
    icon.classList.add('bi-eye');
  }
});

// Auto-hide alerts after 5 seconds
setTimeout(() => {
  const alerts = document.querySelectorAll('.alert');
  alerts.forEach(alert => {
    alert.style.transition = 'opacity 0.5s ease';
    alert.style.opacity = '0';
    setTimeout(() => alert.remove(), 500);
  });
}, 5000);
</script>

</body>
</html>