<?php
// login.php
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
require_once __DIR__ . '/config/db.php';
startSession();

if (isLoggedIn()) { header('Location: dashboard.php'); exit; }

define('RECAPTCHA_SITE_KEY',   '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI');
define('RECAPTCHA_SECRET_KEY', '6LeIxAcTAAAAAGG-vFI1TnRWxMXnb6byBKTKoKz');

$msg = ''; $msgType = '';
$emailVal = '';
$redirect = htmlspecialchars($_GET['redirect'] ?? 'dashboard.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // ── Honeypot
    if (!empty($_POST['website'])) { header('Location: dashboard.php'); exit; }

    // ── Timing check
    if (time() - (int)($_POST['form_time'] ?? 0) < 2) {
        $msg = 'Please try again.'; $msgType = 'e'; goto render;
    }

    $emailVal = strtolower(trim($_POST['email']   ?? ''));
    $password = $_POST['password'] ?? '';
    $remember = !empty($_POST['remember']);

    if (!$emailVal || !$password) {
        $msg = 'Please enter your email and password.'; $msgType = 'e'; goto render;
    }

    try {
        $q = db()->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1 LIMIT 1");
        $q->execute([$emailVal]);
        $user = $q->fetch();

        if (!$user || !password_verify($password, $user['password_hash'])) {
            $msg = 'Invalid email or password.'; $msgType = 'e'; goto render;
        }

        // Email verified check
        if (empty($user['is_email_verified'])) {
            $msg = 'Please verify your email before signing in. <a href="resend_verify.php?email='.urlencode($emailVal).'" style="color:inherit;font-weight:700;text-decoration:underline">Resend verification →</a>';
            $msgType = 'w'; goto render;
        }

        // ── Login success
        session_regenerate_id(true);
        $_SESSION['user_id']    = $user['user_id'];
        $_SESSION['logged_in']  = true;
        $_SESSION['login_time'] = time();

        // Remember me — 30 days
        if ($remember) {
            try {
                // Create remember_tokens table if missing
                db()->exec("CREATE TABLE IF NOT EXISTS remember_tokens (
                    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    user_id INT UNSIGNED NOT NULL,
                    token_hash VARCHAR(64) NOT NULL,
                    expires_at DATETIME NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE KEY uq_token (token_hash)
                ) ENGINE=InnoDB");

                $token     = bin2hex(random_bytes(32));
                $tokenHash = hash('sha256', $token);
                $expires   = date('Y-m-d H:i:s', strtotime('+30 days'));
                db()->prepare("DELETE FROM remember_tokens WHERE user_id = ?")->execute([$user['user_id']]);
                db()->prepare("INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?,?,?)")
                   ->execute([$user['user_id'], $tokenHash, $expires]);
                setcookie('remember_token', $token, time() + 86400 * 30, '/', '', false, true);
            } catch(PDOException $e) { /* non-fatal */ }
        }

        // $dest = urldecode($_POST['redirect'] ?? 'dashboard.php');
        // if (!preg_match('/^[a-zA-Z0-9\/_\-\.?=&%]+$/', $dest)) $dest = 'dashboard.php';
        // header("Location: $dest");
        // exit;
        
        // Store role in session so both dashboards can read it
        $_SESSION['user_role'] = $user['role'];

        $roleDashboards = [
            'author'   => '/author/dashboard.php',
            'reviewer' => '/reviewer/dashboard.php',
            'both'     => '/reviewer/dashboard.php', // 'both' from reviewer login lands on reviewer first
            'editor'   => '/webadmin/dashboard.php',
        ];

        $dest = urldecode($_POST['redirect'] ?? '');
        if (!$dest || !preg_match('/^[a-zA-Z0-9\/_\-\.?=&%]+$/', $dest)) {
            $dest = $roleDashboards[$user['role']] ?? '/reviewer/dashboard.php';
        }
        header("Location: $dest");
        exit;

    } catch(PDOException $e) {
        $msg = 'Server error. Please try again.'; $msgType = 'e';
        error_log('Login error: ' . $e->getMessage());
    }
}
render:
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Sign in — communeglobal</title>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
:root{
  --primary:#E05A2B;--blue:#1B3F6E;--teal:#1A7F8E;--teal-dk:#136070;--teal-lt:#E0F4F7;
  --text:#222;--muted:#666;--border:#D1D5DB;--bg:#F0F4F8;--white:#fff;
  --error:#DC2626;--success:#1D8A5E;--warn:#D97706;--font:'Open Sans',sans-serif;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:var(--font);background:var(--bg);min-height:100vh;display:flex;flex-direction:column}
a{color:var(--teal);text-decoration:none}
a:hover{text-decoration:underline}

/* Nav */
.nav{background:var(--white);border-bottom:1px solid var(--border);padding:0 32px;height:54px;display:flex;align-items:center;justify-content:space-between;flex-shrink:0;box-shadow:0 1px 4px rgba(0,0,0,.06)}
.logo{font-size:22px;font-weight:700;color:var(--primary);display:flex;align-items:center;gap:8px}

/* Page */
.page{flex:1;display:flex;align-items:center;justify-content:center;padding:32px 16px}
.card{background:var(--white);border-radius:12px;box-shadow:0 4px 32px rgba(0,0,0,.1);width:100%;max-width:440px;overflow:hidden}

/* Card header */
.card-hdr{background:linear-gradient(135deg,var(--blue) 0%,#1A5276 100%);padding:28px 32px}
.card-hdr-title{font-size:22px;font-weight:700;color:#fff;margin-bottom:4px}
.card-hdr-sub{font-size:13.5px;color:rgba(255,255,255,.75)}

/* Card body */
.card-body{padding:28px 32px 36px}

/* Form */
.fg{margin-bottom:18px}
.fl{display:block;font-size:13px;font-weight:600;color:var(--text);margin-bottom:5px}
.req{color:var(--error)}
.fi{width:100%;padding:10px 14px;border:1.5px solid var(--border);border-radius:6px;font-family:var(--font);font-size:14px;color:var(--text);outline:none;transition:border-color .15s;background:var(--white)}
.fi:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(26,127,142,.12)}
.fi::placeholder{color:#9CA3AF}

/* Password field */
.pw-wrap{position:relative}
.pw-wrap .fi{padding-right:44px}
.pw-eye{position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--muted);font-size:16px;padding:4px;line-height:1}

/* Checkbox row */
.chk-row{display:flex;align-items:center;gap:9px;font-size:13.5px;color:var(--muted);margin-bottom:18px}
.chk-row input[type=checkbox]{width:15px;height:15px;accent-color:var(--teal);cursor:pointer;flex-shrink:0}

/* Button */
.btn{width:100%;padding:13px;background:var(--teal);color:#fff;border:none;border-radius:6px;font-family:var(--font);font-size:15px;font-weight:700;cursor:pointer;transition:background .15s;display:flex;align-items:center;justify-content:center;gap:8px}
.btn:hover{background:var(--teal-dk)}
.btn:disabled{opacity:.5;cursor:not-allowed}

/* Alerts */
.alert{padding:13px 16px;border-radius:7px;font-size:13.5px;line-height:1.6;margin-bottom:20px}
.alert-e{background:#FEF2F2;border:1px solid #FECACA;color:#991B1B}
.alert-s{background:#F0FDF4;border:1px solid #BBF7D0;color:#166534}
.alert-w{background:#FFFBEB;border:1px solid #FDE68A;color:#92400E}
.alert-i{background:#EFF6FF;border:1px solid #BFDBFE;color:#1E40AF}

/* Forgot password link */
.forgot{text-align:right;margin-top:5px}
.forgot a{font-size:12.5px;color:var(--muted)}
.forgot a:hover{color:var(--teal)}

/* Divider */
.divider{display:flex;align-items:center;gap:10px;margin:22px 0;color:#CBD5E1;font-size:12px}
.divider::before,.divider::after{content:'';flex:1;height:1px;background:var(--border)}

/* Honeypot */
.hp{position:absolute;left:-9999px;top:-9999px;width:0;height:0;overflow:hidden;opacity:0}

/* Spinner */
.spin{width:16px;height:16px;border:2.5px solid rgba(255,255,255,.35);border-top-color:#fff;border-radius:50%;animation:sp .6s linear infinite;flex-shrink:0}
@keyframes sp{to{transform:rotate(360deg)}}

/* Footer */
.footer{text-align:center;padding:14px;font-size:12px;color:var(--muted)}
</style>
</head>
<body>

<?php include __DIR__ . '/../include/header.php'; ?>


<div class="page">
  <div class="card">

    <div class="card-hdr">
      <div class="card-hdr-title">Welcome back</div>
      <div class="card-hdr-sub">Sign in to continue your manuscript submission</div>
    </div>

    <div class="card-body">

      <!-- Alerts from URL (verified, logout, session expired) -->
      <?php
      $urlMsgs = [
        'verified'        => ['s', '✅ Email verified! You can now sign in.'],
        'logout'          => ['i', 'You have been signed out successfully.'],
        'session_expired' => ['w', '⚠️ Your session expired. Please sign in again.'],
      ];
      if (!empty($_GET['msg']) && isset($urlMsgs[$_GET['msg']])):
        [$t, $m] = $urlMsgs[$_GET['msg']];
      ?>
      <div class="alert alert-<?= $t ?>"><?= $m ?></div>
      <?php endif; ?>

      <!-- Form errors -->
      <?php if ($msg): ?>
      <div class="alert alert-<?= $msgType ?>"><?= $msg ?></div>
      <?php endif; ?>

      <form method="POST" id="loginForm" novalidate>
        <input type="hidden" name="redirect"   value="<?= $redirect ?>">
        <input type="hidden" name="form_time"  value="<?= time() ?>">

        <!-- Honeypot -->
        <div class="hp" aria-hidden="true">
          <input type="text" name="website" tabindex="-1" autocomplete="off">
        </div>

        <!-- Email -->
        <div class="fg">
          <label class="fl" for="email">Email address <span class="req">*</span></label>
          <input class="fi" type="email" id="email" name="email"
                 value="<?= htmlspecialchars($emailVal) ?>"
                 placeholder="you@university.edu"
                 autocomplete="email" required>
        </div>

        <!-- Password -->
        <div class="fg">
          <label class="fl" for="password">Password <span class="req">*</span></label>
          <div class="pw-wrap">
            <input class="fi" type="password" id="password" name="password"
                   placeholder="••••••••"
                   autocomplete="current-password" required>
            <button type="button" class="pw-eye" onclick="togglePw()" title="Show/hide">👁️</button>
          </div>
          <div class="forgot"><a href="forgot_password.php">Forgot password?</a></div>
        </div>

        <!-- Remember me -->
        <div class="chk-row">
          <input type="checkbox" id="remember" name="remember">
          <label for="remember">Keep me signed in for 30 days</label>
        </div>

        <!-- Submit -->
        <button type="submit" class="btn" id="loginBtn">Sign in</button>
      </form>

      <div class="divider">new to communeglobal?</div>
      <div style="text-align:center">
        <a href="register.php" style="font-size:14px;font-weight:700;color:var(--teal)">Create a free account →</a>
      </div>

    </div>
  </div>
</div>


<script>
function togglePw() {
  const f   = document.getElementById('password');
  const btn = document.querySelector('.pw-eye');
  f.type    = (f.type === 'password') ? 'text' : 'password';
  btn.textContent = (f.type === 'password') ? '👁️' : '🙈';
}
document.getElementById('loginForm').addEventListener('submit', function() {
  const btn = document.getElementById('loginBtn');
  btn.disabled = true;
  btn.innerHTML = '<span class="spin"></span> Signing in...';
});
</script>
</body>
</html>

<?php include __DIR__ . '/../include/footer.php'; ?>
