<?php
require_once "../config/db.php";
require_once "../config/session.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

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

    // GET REDIRECT URL
    $redirect = $_POST['redirect'] ?? '';

    if ($email == "" || $password == "") {
        header("Location: login.php?error=1");
        exit();
    }

    $sql = "SELECT * FROM users WHERE email = ?";
    $stmt = mysqli_prepare($conn, $sql);

    mysqli_stmt_bind_param($stmt, "s", $email);
    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

    if ($row = mysqli_fetch_assoc($result)) {

        if (password_verify($password, $row['password'])) {

            // =============================
            // SET SESSION
            // =============================
            $_SESSION['user_id']        = $row['id'];
            $_SESSION['full_name']     = $row['full_name'];
            $_SESSION['role']          = $row['role'];
            $_SESSION['department_id'] = $row['department_id'];

            // =============================
            // REDIRECT BACK TO QR PAGE
            // =============================
            if (!empty($redirect)) {

                header("Location: " . $redirect);
                exit();

            }

            // =============================
            // GUEST USER
            // =============================
            if ($row['role'] === 'guest') {

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

            }

            // =============================
            // STAFF / ADMIN / TECHNICIAN
            // =============================
            header("Location: ../dashboard.php");
            exit();

        } else {

            header("Location: login.php?error=1");
            exit();

        }

    } else {

        header("Location: login.php?error=1");
        exit();

    }

} else {

    header("Location: login.php");
    exit();

}
?>