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

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

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

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

    // ==============================
    // SAFE QUERY (HOSTING COMPATIBLE)
    // ==============================
    $sql = "SELECT id, full_name, role, department_id, password 
            FROM users 
            WHERE email = ? 
            LIMIT 1";

    $stmt = mysqli_prepare($conn, $sql);

    if (!$stmt) {
        die("Prepare failed: " . mysqli_error($conn));
    }

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

    // IMPORTANT: replace get_result with store_result
    mysqli_stmt_store_result($stmt);

    if (mysqli_stmt_num_rows($stmt) > 0) {

        mysqli_stmt_bind_result(
            $stmt,
            $id,
            $full_name,
            $role,
            $department_id,
            $hashed_password
        );

        mysqli_stmt_fetch($stmt);

        if (password_verify($password, $hashed_password)) {

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

            // Redirect to dashboard
            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();
}
?>