<?php
require_once __DIR__ . '/../config/database.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

function getDBConnection() {
    return createDatabaseConnection(true);
}

function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

function getCurrentUser() {
    if (!isLoggedIn()) {
        return null;
    }

    $conn = getDBConnection();
    $stmt = $conn->prepare('SELECT * FROM users WHERE id = ?');
    $stmt->bind_param('i', $_SESSION['user_id']);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    $conn->close();

    if ($user) {
        $_SESSION['user_type'] = $user['user_type'];
        $_SESSION['account_status'] = $user['account_status'] ?? 'active';
    }

    return $user;
}

function isAdmin() {
    if (isset($_SESSION['user_type'])) {
        return $_SESSION['user_type'] === 'admin';
    }

    $user = getCurrentUser();
    return $user && $user['user_type'] === 'admin';
}

function requireLogin() {
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit();
    }

    $user = getCurrentUser();
    if (!$user || (($user['account_status'] ?? 'active') !== 'active')) {
        $_SESSION = [];
        session_destroy();
        header('Location: login.php');
        exit();
    }
}

function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        header('Location: dashboard.php');
        exit();
    }
}

function redirectToDashboard() {
    if (isAdmin()) {
        header('Location: admin.php');
    } else {
        header('Location: dashboard.php');
    }
    exit();
}
?>