<?php
require_once __DIR__ . '/db.php';

// Check if user is logged in
function isLoggedIn() {
    return isset($_SESSION['user_id']);
}

// Check user role
function getUserRole() {
    return $_SESSION['role'] ?? null;
}

// Require login with specific role
function requireRole($role) {
    if (!isLoggedIn() || getUserRole() !== $role) {
        header("Location: " . BASE_URL . "/login.php");
        exit();
    }
}

// Redirect with message
function redirect($url, $message = '', $type = 'success') {
    if ($message) {
        $_SESSION['flash_msg'] = $message;
        $_SESSION['flash_type'] = $type;
    }
    header("Location: " . $url);
    exit();
}

// Display flash message
function showFlash() {
    if (isset($_SESSION['flash_msg'])) {
        $type = $_SESSION['flash_type'] ?? 'success';
        echo "<div class='alert alert-{$type}'>" . htmlspecialchars($_SESSION['flash_msg']) . "</div>";
        unset($_SESSION['flash_msg'], $_SESSION['flash_type']);
    }
}

// Sanitize input
function clean($conn, $data) {
    return mysqli_real_escape_string($conn, trim($data));
}

// Upload file
function uploadFile($file, $folder) {
    $uploadDir = __DIR__ . "/../assets/uploads/$folder/";
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }
    $fileName = time() . "_" . basename($file['name']);
    $targetPath = $uploadDir . $fileName;
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return $fileName;
    }
    return false;
}

// Get user details
function getUser($conn, $id) {
    $id = (int)$id;
    $result = mysqli_query($conn, "SELECT * FROM users WHERE id = $id");
    return mysqli_fetch_assoc($result);
}
?>
