<?php
// login.php
session_start();

$host = "localhost";
$dbname = "liongate";
$user = "root";
$pass = "";

try {
  $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
  ]);
} catch (Exception $e) {
  http_response_code(500);
  exit("Database connection failed.");
}

$identity = trim($_POST["identity"] ?? "");
$password = $_POST["password"] ?? "";

if ($identity === "" || $password === "") {
  exit("Please enter your email/username and password.");
}

// Look up by email OR username
$stmt = $pdo->prepare("
  SELECT id, username, email, password_hash
  FROM users
  WHERE email = :id OR username = :id
  LIMIT 1
");
$stmt->execute([":id" => $identity]);
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$userRow) {
  exit("Invalid login details.");
}

// Verify password (matches password_hash() you used in register.php)
if (!password_verify($password, $userRow["password_hash"])) {
  exit("Invalid login details.");
}

// Success: log user in
$_SESSION["user_id"] = (int)$userRow["id"];

// Optional "remember me" (simple version: not implemented securely here)
// If you want remember-me cookies, tell me and I’ll show the safe way.

header("Location: ../dashboard.php");
exit;
exit;