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

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: login.php");
    exit;
}

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

if ($email === "" || $password === "") {
    fxh_set_flash("Email and password required.","error");
    header("Location: login.php");
    exit;
}

/*
  ✅ FIXED:
  Use NEW user system table
*/
$stmt = $conn->prepare("
    SELECT id, email, password_hash, username, status
    FROM fxh_users
    WHERE email = ?
    LIMIT 1
");

$stmt->bind_param("s", $email);
$stmt->execute();

$res = $stmt->get_result();

if ($res->num_rows === 0) {
    fxh_set_flash("Invalid login credentials.","error");
    header("Location: login.php");
    exit;
}

$user = $res->fetch_assoc();

/*
  ✅ Secure password verify
*/
if (!password_verify($password, $user["password_hash"])) {
    fxh_set_flash("Invalid login credentials.","error");
    header("Location: login.php");
    exit;
}

if ($user["status"] !== "active") {
    fxh_set_flash("Account is disabled.","error");
    header("Location: login.php");
    exit;
}

/*
  ✅ LOGIN SUCCESS
*/
$_SESSION["user_id"]  = $user["id"];
$_SESSION["email"]    = $user["email"];
$_SESSION["username"] = $user["username"] ?? "";

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