<?php
require_once __DIR__ . '/includes/config.php';

if (isLoggedIn()) redirect('dashboard.php');

$errors = [];
$username = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF
    if (!verifyCsrf($_POST['csrf_token'] ?? '')) {
        $errors['general'] = 'Invalid request. Please try again.';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $remember = isset($_POST['remember']);

        if (empty($username)) $errors['username'] = 'Username or email is required.';
        if (empty($password)) $errors['password'] = 'Password is required.';

        if (empty($errors)) {
            // Find user by username or email
            $stmt = db()->prepare('SELECT id, username, full_name, password_hash, is_active FROM users WHERE (username = ? OR email = ?) LIMIT 1');
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch();

            if ($user && $user['is_active'] && password_verify($password, $user['password_hash'])) {
                // Regenerate session ID to prevent fixation
                session_regenerate_id(true);
                $_SESSION['user_id']   = $user['id'];
                $_SESSION['username']  = $user['username'];
                $_SESSION['logged_at'] = time();

                // Remember me cookie
                if ($remember) {
                    $token = bin2hex(random_bytes(32));
                    $hash  = hash('sha256', $token);
                    $exp   = date('Y-m-d H:i:s', time() + 60 * 60 * 24 * 30);
                    db()->prepare('INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?,?,?)')->execute([$user['id'], $hash, $exp]);
                    setcookie('remember_token', $token, time() + 60 * 60 * 24 * 30, '/', '', false, true);
                }

                redirect('dashboard.php');
            } else {
                $errors['general'] = 'Invalid username/email or password.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login – SPACE</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;400;500;600;700&display=swap" rel="stylesheet">
<style>
  :root {
  --bg:        #e2e2e2;
  --light:     #ffffff;
  --dark:      #c1c1c1;
  --text:      #111111;
  --muted:     #777777;
  --neu-out:   5px 5px 10px var(--dark), -5px -5px 10px var(--light);
  --neu-in:    inset 3px 3px 6px var(--dark), inset -3px -3px 6px var(--light);
}

*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

html, body {
  font-family: 'Poppins', sans-serif;
  background: var(--bg);
  color: var(--text);
  min-height: 100vh;
    -webkit-tap-highlight-color:transparent;

}

a { text-decoration: none; color: inherit; }
button { font-family: 'Poppins', sans-serif; cursor: pointer; border: none; background: none; }
input, textarea, select { font-family: 'Poppins', sans-serif; }

.auth-page {
  width: 100%;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.corner {
  position: fixed;
  width: 200px;
  height: 200px;
  pointer-events: none;
  z-index: 0;
}
.top-left    { top: 0; left: 0; }
.top-right   { top: 0; right: 0; }
.bottom-left { bottom: 0; left: 0; }
.bottom-right{ bottom: 0; right: 0; }

.star { position: absolute; filter: drop-shadow(4px 4px 6px var(--dark)) drop-shadow(-4px -4px 6px var(--light)); }
.star.big   { width: 90px; height: 90px; }
.star.small { width: 30px; height: 30px; }
.top-left  .big  { top: 60px; left: 40px; }
.top-left  .small{ top: 40px; left: 140px; }
.top-right .big  { top: 60px; right: 40px; }
.top-right .small{ top: 40px; right: 140px; }
.bottom-left  .big  { bottom: 80px; left: 40px; }
.bottom-left  .small{ bottom: 60px; left: 140px; }
.bottom-right .big  { bottom: 80px; right: 40px; }
.bottom-right .small{ bottom: 60px; right: 140px; }

.auth-wrapper {
  position: relative;
  z-index: 1;
  width: 90%;
  max-width: 360px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.logo-circle-lg {
  width: 110px; height: 110px;
  border-radius: 50%;
  background: var(--bg);
  box-shadow: var(--neu-out);
  display: flex; align-items: center; justify-content: center;
  margin-bottom: 24px;
}
.logo-circle-lg img { width: 70px; }

.auth-title { font-size: 26px; font-weight: 600; margin-bottom: 4px; text-align: center; }
.auth-subtitle { font-size: 13px; color: var(--muted); margin-bottom: 32px; text-align: center; }

.input-wrap { position: relative; width: 100%; margin-bottom: 20px; }
.input-icon {
  position: absolute; left: 18px; top: 50%; transform: translateY(-50%);
  width: 18px; height: 18px; color: #999; pointer-events: none;
}
.neu-input {
  width: 100%;
  padding: 15px 18px 15px 48px;
  border-radius: 12px;
  background: var(--bg);
  border: none; outline: none;
  font-size: 14px; color: var(--text);
  box-shadow: var(--neu-in);
  transition: box-shadow .2s;
}
.neu-input::placeholder { color: #aaa; }
.neu-input:focus { box-shadow: inset 4px 4px 10px var(--dark), inset -4px -4px 10px var(--light); }
.neu-input.error { box-shadow: inset 3px 3px 8px #e9a0a0, inset -3px -3px 8px var(--light); }

.neu-btn {
  width: 100%;
  padding: 14px;
  border-radius: 50px;
  background: var(--bg);
  box-shadow: var(--neu-out);
  font-size: 14px; font-weight: 600;
  color: var(--text);
  transition: box-shadow .15s, transform .1s;
  margin-bottom: 8px;
}
.neu-btn:active { box-shadow: var(--neu-in); transform: scale(0.99); }
.neu-btn.primary { background: var(--text); color: var(--bg); box-shadow: 4px 4px 8px var(--dark), -4px -4px 8px var(--light); }

.divider {
  display: flex; align-items: center;
  font-size: 13px; color: var(--muted);
  margin: 20px 0; width: 100%;
}
.divider::before, .divider::after { content: ''; flex: 1; border-bottom: 1px solid #bbb; }
.divider::before { margin-right: 12px; }
.divider::after  { margin-left: 12px; }

.social-btn:active { box-shadow: var(--neu-in); }

.auth-link { font-size: 13px; color: var(--text); }
.auth-link a { font-weight: 700; }

.auth-footer {
  position: fixed; bottom: 24px; text-align: center;
  font-size: 11px; color: var(--muted); width: 100%; z-index: 1;
}
.auth-footer a { color: var(--muted); }

.form-error {
  color: #dc2626; font-size: 12px; margin-top: -14px;
  margin-bottom: 10px; padding-left: 4px;
}
.flash-success {
  background: #d1fae5; color: #065f46; border: 1px solid #a7f3d0;
  border-radius: 10px; padding: 10px 14px; font-size: 13px;
  margin-bottom: 16px; width: 100%;
}
.flash-error {
  background: #fee2e2; color: #991b1b; border: 1px solid #fca5a5;
  border-radius: 10px; padding: 10px 14px; font-size: 13px;
  margin-bottom: 16px; width: 100%;
}

  .social-row{
    display: flex; width: 100%; margin-bottom: 28px; flex-direction: column; gap: 12px;
  }
  .social-row a{
    text-decoration: none; color: var(--text); 
    width: 100%; height: 48px; border-radius: 12px;
    background: var(--bg); border: 1px solid #ccc;
    display: flex; align-items: center; justify-content: center;
    font-size: 14px; font-weight: 500;
    box-shadow: var(--neu-out);
  }
  .social-row a:active { box-shadow: var(--neu-in); }
</style>
<style>
  html, body {
  -webkit-tap-highlight-color:transparent;
  }
</style>
</head>
<body class="auth-page">

  <div class="corner top-left">
    <img src="assets/img/star.svg" class="star big" alt="">
    <img src="assets/img/star.svg" class="star small" alt="">
  </div>
  <div class="corner top-right">
    <img src="assets/img/star.svg" class="star big" alt="">
    <img src="assets/img/star.svg" class="star small" alt="">
  </div>
  <div class="corner bottom-left">
    <img src="assets/img/star.svg" class="star big" alt="">
    <img src="assets/img/star.svg" class="star small" alt="">
  </div>
  <div class="corner bottom-right">
    <img src="assets/img/star.svg" class="star big" alt="">
    <img src="assets/img/star.svg" class="star small" alt="">
  </div>

  <div class="auth-wrapper">
    <a href="index.php">
      <div class="logo-circle-lg">
        <img src="assets/img/logo.svg" alt="SPACE" width="70">
      </div>
    </a>
    <h1 class="auth-title">Welcome Back!</h1>
    <p class="auth-subtitle">LOGIN to your account</p>

    <?php if (!empty($errors['general'])): ?>
      <div class="flash-error"><?= e($errors['general']) ?></div>
    <?php endif; ?>

    <form method="POST" action="login.php" style="width:100%;">
      <input type="hidden" name="csrf_token" value="<?= e(csrfToken()) ?>">

      <div class="input-wrap">
        <svg class="input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        <input type="text" name="username" class="neu-input <?= isset($errors['username']) ? 'error' : '' ?>"
               placeholder="Username or Email" value="<?= e($username) ?>" autocomplete="username">
      </div>
      <?php if (!empty($errors['username'])): ?>
        <p class="form-error"><?= e($errors['username']) ?></p>
      <?php endif; ?>

      <div class="input-wrap">
        <svg class="input-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0110 0v4"/></svg>
        <input type="password" name="password" class="neu-input <?= isset($errors['password']) ? 'error' : '' ?>"
               placeholder="Password" autocomplete="current-password">
      </div>
      <?php if (!empty($errors['password'])): ?>
        <p class="form-error"><?= e($errors['password']) ?></p>
      <?php endif; ?>

      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:28px;font-size:12px;">
        <label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
          <input type="checkbox" name="remember" style="accent-color:var(--text);">
          Remember me
        </label>
        <a href="#" style="color:var(--text);font-weight:600;">Forgot Password?</a>
      </div>

      <button type="submit" class="neu-btn primary">LOGIN</button>
    </form>
<div class="divider">or continue with</div>
    <div class="social-row" style="flex-direction: column; gap: 12px;">
      <a href="https://accounts.google.com/o/oauth2/v2/auth?client_id=507547805046-7l61dd343l1656r1i7lbuilv5qnkp09b.apps.googleusercontent.com&redirect_uri=https://airsignsoul.online/space_php/login-google.php&response_type=code&scope=email profile" class="social-btn" style="width: 100%; justify-content: center; gap: 10px;">
        <img src="assets/img/Google.svg" alt="" style="width: 30px;">
        Sign in with Google
      </a>
    </div>

    <p class="auth-link">Don't have an account? <a href="register.php">Sign Up</a></p>
  </div>

</body>
</html>
