<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) session_start();

// Include config to get DB_ constants
include __DIR__ . '/config/journal_config.php';

// ── Build PDO from the same DB_ constants journal_config defines ──
if (!isset($pdo)) {
    try {
        $pdo = new PDO(
            "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=" . DB_CHARSET,
            DB_USER,
            DB_PASS,
            [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]
        );
    } catch (PDOException $e) {
        error_log("Login DB error: " . $e->getMessage());
        die("Database connection failed. Please try again.");
    }
}

// ── Already logged in ─────────────────────────────────────────
if (!empty($_SESSION['admin_user_id'])) {
    header("Location: " . redirect_for_role($_SESSION['admin_role'], $_SESSION['admin_journal_id'] ?? null));
    exit;
}

$error = '';

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

    if (empty($email) || empty($password)) {
        $error = 'Please enter your email and password.';

    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';

    } else {
        try {
            $stmt = $pdo->prepare("
                SELECT id, email, password_hash,
                       first_name, last_name,
                       role, journal_id, is_active
                FROM   admin_users
                WHERE  email = ?
                LIMIT  1
            ");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user || !password_verify($password, $user['password_hash'])) {
                $error = 'Invalid email or password.';      // generic — no enumeration

            } elseif ((int)$user['is_active'] !== 1) {
                $error = 'Your account is inactive. Contact the administrator.';

            } else {
                // ── SUCCESS ────────────────────────────────────
                session_regenerate_id(true);

                $_SESSION['admin_user_id']  = $user['id'];
                $_SESSION['admin_email']    = $user['email'];
                $_SESSION['admin_name']     = trim($user['first_name'] . ' ' . $user['last_name']);
                $_SESSION['admin_role']     = $user['role'];
                $_SESSION['admin_journal_id'] = $user['journal_id'];

                // record last login
                $pdo->prepare("UPDATE admin_users SET last_login_at = NOW() WHERE id = ?")
                    ->execute([$user['id']]);

                // go to intended URL if set, else role default
                $dest = $_SESSION['intended_url']
                    ?? redirect_for_role($user['role'], $user['journal_id']);
                unset($_SESSION['intended_url']);

                header("Location: $dest");
                exit;
            }
        } catch (PDOException $e) {
            error_log("Login error: " . $e->getMessage());
            $error = 'A system error occurred. Please try again.';
        }
    }
}

// ── role → redirect map ───────────────────────────────────────
function redirect_for_role(string $role, ?int $journal_id): string {
    $jq = $journal_id ? "?journal_id=$journal_id" : '';
    return match($role) {
        'superadmin', 'admin', 'editor'
                   => "/webadmin/admin_dashboard.php",
        'reviewer' => "/journals/common/admin/reviewer_dashboard.php$jq",
        'author'   => "/journals/common/author/author_dashboard.php$jq",
        default    => "/webadmin/admin_dashboard.php",
    };
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login — RSIS Submission System</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <style>
    :root {
      --brand: #1a3c5e;
      --brand-dark: #122d47;
    }
    body {
      font-family: 'Inter', sans-serif;
      background: #eef1f5;
      min-height: 100vh;
      display: flex;
      align-items: center;
    }
    .auth-card {
      width: 100%;
      max-width: 420px;
      margin: auto;
      border: none;
      border-radius: 14px;
      overflow: hidden;
      box-shadow: 0 8px 32px rgba(0,0,0,0.12);
    }
    .auth-header {
      background: var(--brand);
      color: #fff;
      padding: 30px 28px 22px;
      text-align: center;
    }
    .auth-header h4  { font-weight: 700; font-size: 1.15rem; margin: 0; }
    .auth-header p   { font-size: .83rem; opacity: .75; margin: 6px 0 0; }
    .auth-body       { padding: 28px; background: #fff; }
    .form-label      { font-size: .875rem; font-weight: 500; color: #374151; }
    .form-control {
      font-size: .9rem;
      border-radius: 8px;
      border-color: #d1d5db;
    }
    .form-control:focus {
      border-color: var(--brand);
      box-shadow: 0 0 0 3px rgba(26,60,94,.12);
    }
    .btn-brand {
      background: var(--brand);
      border: none;
      border-radius: 8px;
      font-weight: 600;
      letter-spacing: .3px;
      padding: 10px;
    }
    .btn-brand:hover { background: var(--brand-dark); }
    .pw-wrap         { position: relative; }
    .pw-toggle {
      position: absolute; right: 12px; top: 50%;
      transform: translateY(-50%);
      background: none; border: none; color: #9ca3af;
      cursor: pointer; padding: 0; line-height: 1;
    }
    .pw-toggle:hover { color: #374151; }
    .divider { border-color: #e5e7eb; margin: 20px 0; }
  </style>
</head>
<body>
<div class="container px-3">
  <div class="auth-card card">

    <div class="auth-header">
      <svg width="38" height="38" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,.9)" stroke-width="1.8" class="mb-2">
        <circle cx="12" cy="8" r="4"/><path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
      </svg>
      <h4>RSIS Submission System</h4>
      <p>Sign in to your account</p>
    </div>

    <div class="auth-body">
      <?php if ($error): ?>
        <div class="alert alert-danger py-2 px-3 mb-3 d-flex align-items-center gap-2" role="alert">
          <svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
            <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0-11a.75.75 0 0 0-.75.75v4.5a.75.75 0 0 0 1.5 0v-4.5A.75.75 0 0 0 8 4zm0 7.5a.875.875 0 1 0 0-1.75.875.875 0 0 0 0 1.75z"/>
          </svg>
          <small><?= htmlspecialchars($error) ?></small>
        </div>
      <?php endif; ?>

      <?php if (isset($_GET['reset']) && $_GET['reset'] === 'success'): ?>
        <div class="alert alert-success py-2 px-3 mb-3">
          <small>✅ Password reset successfully. Please login.</small>
        </div>
      <?php endif; ?>

      <form method="POST" novalidate>

        <div class="mb-3">
          <label for="email" class="form-label">Email address</label>
          <input type="email" name="email" id="email" class="form-control"
                 value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
                 placeholder="you@example.com" required autofocus>
        </div>

        <div class="mb-4">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <label for="password" class="form-label mb-0">Password</label>
            <a href="forgot_password.php" class="small text-muted" style="font-size:.8rem">Forgot password?</a>
          </div>
          <div class="pw-wrap">
            <input type="password" name="password" id="password"
                   class="form-control pe-5" placeholder="••••••••" required>
            <button type="button" class="pw-toggle" id="pwToggle" title="Show/hide">
              <!-- eye open -->
              <svg id="eyeOpen" xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 16 16">
                <path d="M16 8s-3-5.5-8-5.5S0 8 0 8s3 5.5 8 5.5S16 8 16 8zM8 11a3 3 0 1 1 0-6 3 3 0 0 1 0 6z"/>
              </svg>
              <!-- eye slash (hidden) -->
              <svg id="eyeSlash" xmlns="http://www.w3.org/2000/svg" width="18" height="18" fill="currentColor" viewBox="0 0 16 16" style="display:none">
                <path d="M13.359 11.238C15.06 9.72 16 8 16 8s-3-5.5-8-5.5a7.03 7.03 0 0 0-2.79.588l.77.771A5.944 5.944 0 0 1 8 3.5c2.12 0 3.879 1.168 5.168 2.457A13.134 13.134 0 0 1 14.828 8c-.058.087-.122.183-.195.288-.335.48-.83 1.12-1.465 1.755-.165.165-.337.328-.517.486l.708.709z"/>
                <path d="M11.297 9.176a3.5 3.5 0 0 0-4.474-4.474l.823.823a2.5 2.5 0 0 1 2.829 2.829l.822.822zm-2.943 1.299.822.822a3.5 3.5 0 0 1-4.474-4.474l.823.823a2.5 2.5 0 0 0 2.829 2.829z"/>
                <path d="M3.35 5.47c-.18.16-.353.322-.518.487A13.134 13.134 0 0 0 1.172 8l.195.288c.335.48.83 1.12 1.465 1.755C4.121 11.332 5.881 12.5 8 12.5c.716 0 1.39-.133 2.02-.36l.77.772A7.029 7.029 0 0 1 8 13.5C3 13.5 0 8 0 8s.939-1.721 2.641-3.238l.708.709z"/>
                <path fill-rule="evenodd" d="M13.646 14.354l-12-12 .708-.708 12 12-.708.708z"/>
              </svg>
            </button>
          </div>
        </div>

        <button type="submit" class="btn btn-brand btn-primary w-100">
          Sign In
        </button>

      </form>
    </div>

  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
  const pwInput  = document.getElementById('password');
  const eyeOpen  = document.getElementById('eyeOpen');
  const eyeSlash = document.getElementById('eyeSlash');

  document.getElementById('pwToggle').addEventListener('click', () => {
    const isText = pwInput.type === 'text';
    pwInput.type       = isText ? 'password' : 'text';
    eyeOpen.style.display  = isText ? '' : 'none';
    eyeSlash.style.display = isText ? 'none' : '';
  });
</script>
</body>
</html>