<?php
require_once 'auth.php';

if (!isset($_POST['login'])) {
    header("Location: index.php");
    exit();
}

$user = trim($_POST['username'] ?? '');
$pass = $_POST['password'] ?? '';

if ($user === '' || $pass === '') {
    $_SESSION['error'] = "ইউজারনেম এবং পাসওয়ার্ড দিন!";
    header("Location: index.php");
    exit();
}

$stmt = $conn->prepare("SELECT * FROM agh_users WHERE username = ? LIMIT 1");
$stmt->bind_param("s", $user);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    $row = $result->fetch_assoc();

    if (password_verify($pass, $row['password'])) {
        session_regenerate_id(true);

        set_login_session($row);
        create_remember_token((int) $row['id']);

        if ($row['role'] === 'admin') {
            header("Location: admin/index.php");
        } else {
            header("Location: officer_dashboard.php");
        }

        $stmt->close();
        exit();
    }

    $_SESSION['error'] = "ভুল পাসওয়ার্ড দিয়েছেন!";
    $stmt->close();
    header("Location: index.php");
    exit();
}

$_SESSION['error'] = "এই ইউজারনেমটি খুঁজে পাওয়া যায়নি!";
$stmt->close();
header("Location: index.php");
exit();
