<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/oauth.php';
include __DIR__ . '/../includes/header.php';

$error = null;
$next = isset($_GET['next']) ? $_GET['next'] : '/WATCHING/index.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $email = trim($_POST['email'] ?? '');
  $pass = $_POST['password'] ?? '';
  if ($email && $pass) {
    $stmt = db()->prepare("SELECT id, password_hash, name FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $res = $stmt->get_result();
    $user = $res->fetch_assoc();
    if ($user && !empty($user['password_hash']) && password_verify($pass, $user['password_hash'])) {
      $_SESSION['user_id'] = (int)$user['id'];
      $_SESSION['user_name'] = $user['name'] ?: $email;
      header('Location: ' . $next); exit;
    } else {
      $error = 'Invalid email or password';
    }
  } else {
    $error = 'Please fill in email and password';
  }
}
?>
<div class="container glass-card" style="padding:16px;margin-top:24px;max-width:520px;">
  <h2>Login</h2>
  <?php if ($error): ?><div class="alert error"><?php echo htmlspecialchars($error); ?></div><?php endif; ?>
  <form method="post">
    <label>Email</label><input class="input" type="email" name="email" required>
    <label>Password</label><input class="input" type="password" name="password" required>
    <button class="btn" type="submit" style="margin-top:10px;">Login</button>
  </form>
  <div style="margin-top:10px;">
    <a class="btn" href="/WATCHING/actions/google_oauth_start.php?next=<?php echo urlencode($next); ?>">Continue with Google</a>
  </div>
  <div style="margin-top:10px;">
    <a href="/WATCHING/pages/register.php">Create an account</a> ·
    <a href="/WATCHING/pages/forgot_password.php">Forgot password?</a>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>