<?php
session_start();
require_once 'db_connect.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['hasPermission' => false]);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $screen = isset($_POST['screen']) ? trim($_POST['screen']) : '';

    if (empty($screen)) {
        echo json_encode(['hasPermission' => false, 'error' => 'Screen parameter is missing']);
        exit();
    }

    $user_id = $_SESSION['user_id'];

    try {
        // التحقق من دور المستخدم
        $stmt = $conn->prepare("SELECT role FROM users WHERE id = :user_id");
        $stmt->execute([':user_id' => $user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user && $user['role'] === 'admin') {
            echo json_encode(['hasPermission' => true]);
            exit();
        }

        // التحقق من الصلاحيات في جدول permissions
        $stmt = $conn->prepare("SELECT access FROM permissions WHERE user_id = :user_id AND screen = :screen");
        $stmt->execute([':user_id' => $user_id, ':screen' => $screen]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($result && $result['access'] == 1) {
            echo json_encode(['hasPermission' => true]);
        } else {
            echo json_encode(['hasPermission' => false]);
        }
    } catch (PDOException $e) {
        error_log("Error checking permission via AJAX: " . $e->getMessage());
        echo json_encode(['hasPermission' => false, 'error' => 'Database error']);
    }
} else {
    echo json_encode(['hasPermission' => false, 'error' => 'Invalid request method']);
}
?>