<?php
require_once __DIR__ . "/config.inc.php";

$errors = [];
$email = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        user_check_csrf();
    } catch (Throwable $e) {
        $errors[] = "Invalid CSRF token. Refresh and try again.";
    }

    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = "Valid email is required.";
    if ($password === '') $errors[] = "Password is required.";

    if (!$errors) {
        $stmt = db()->prepare("SELECT id, full_name, password_hash FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $res = $stmt->get_result();
        $user = $res->fetch_assoc();
        $stmt->close();

        if (!$user || !password_verify($password, $user['password_hash'])) {
            $errors[] = "Invalid email or password.";
        } else {
            $_SESSION['user_id'] = (int)$user['id'];
            $_SESSION['user_name'] = $user['full_name'];
            redirect('index.php');
        }
    }
}

require_once __DIR__ . "/partials/header.php";
?>
<div class="row justify-content-center">
  <div class="col-md-6 col-lg-5">
    <div class="card shadow-sm">
      <div class="card-body">
        <h4 class="mb-3">User Login</h4>

        <?php if ($errors): ?>
          <div class="alert alert-danger">
            <ul class="mb-0">
              <?php foreach ($errors as $er): ?>
                <li><?= e($er) ?></li>
              <?php endforeach; ?>
            </ul>
          </div>
        <?php endif; ?>

        <form method="post" class="row g-3">
          <input type="hidden" name="csrf_token" value="<?= e(user_csrf()) ?>">

          <div class="col-12">
            <label class="form-label">Email</label>
            <input class="form-control" type="email" name="email" value="<?= e($email) ?>" required>
          </div>

          <div class="col-12">
            <label class="form-label">Password</label>
            <input class="form-control" type="password" name="password" required>
          </div>

          <div class="col-12 d-grid">
            <button class="btn btn-primary">Login</button>
          </div>

          <div class="col-12 text-center">
            New user? <a href="signup.php">Create account</a>
          </div>
        </form>

      </div>
    </div>
  </div>
</div>
<?php require_once __DIR__ . "/partials/footer.php"; ?>