<?php
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'db_connect.php';

function checkPermission($screen) {
    global $conn;
    $user_id = $_SESSION['user_id'];

    error_log("Checking permission for user_id: $user_id, screen: $screen"); // للتصحيح

    try {
        $stmt = $conn->prepare("SELECT access FROM permissions WHERE user_id = :user_id AND screen = :screen");
        $stmt->execute([':user_id' => $user_id, ':screen' => $screen]);
        $has_access = $stmt->fetchColumn();

        error_log("Result of query for user_id: $user_id, screen: $screen, access: " . ($has_access === false ? 'Not found' : $has_access)); // للتصحيح

        if ($has_access === false) {
            return false;
        }
        return ($has_access == 0) ? false : true;
    } catch (PDOException $e) {
        error_log("Error checking permission: " . $e->getMessage());
        return false;
    }
}

$user_name = $_SESSION['user_name'] ?? '';
if (empty($user_name)) {
    try {
        $stmt = $conn->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->execute([':user_id' => $_SESSION['user_id']]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($user) && isset($user['username'])) {
            $user_name = $user['username'];
            $_SESSION['user_name'] = $user_name;
        }
    } catch (PDOException $e) {
        error_log("Error fetching user name: " . $e->getMessage());
        $user_name = 'مستخدم غير محدد';
    }
}
?>