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

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

function requireLogin() {
    if (!isLoggedIn()) {
        $isApi = (strpos($_SERVER['SCRIPT_NAME'] ?? '', '/api/') !== false || 
                  (strpos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') !== false));
        if ($isApi) {
            header('Content-Type: application/json; charset=utf-8');
            header('HTTP/1.1 401 Unauthorized');
            echo json_encode(['success' => false, 'message' => 'انتهت الجلسة. حدّث الصفحة وسجّل دخولك مجدداً.']);
            exit;
        }
        header('Location: index.php');
        exit;
    }
    // تحديث الصلاحيات من DB إن لم تكن في الجلسة (عند ترقية النظام)
    if (!isset($_SESSION['is_admin']) && isset($conn)) {
        $r = $conn->query("SELECT is_admin, can_edit, can_delete, can_export FROM users WHERE id = " . (int)$_SESSION['user_id']);
        if ($r && $row = $r->fetch_assoc()) {
            $_SESSION['is_admin'] = !empty($row['is_admin']);
            $_SESSION['can_edit'] = !empty($row['can_edit']);
            $_SESSION['can_delete'] = !empty($row['can_delete']);
            $_SESSION['can_export'] = !empty($row['can_export']);
        } else {
            $_SESSION['is_admin'] = $_SESSION['can_edit'] = $_SESSION['can_delete'] = $_SESSION['can_export'] = 1;
        }
    }
}

function requireAdmin() {
    requireLogin();
    if (empty($_SESSION['is_admin'])) {
        header('Location: dashboard.php');
        exit;
    }
}

function canEdit() {
    return !empty($_SESSION['is_admin']) || !empty($_SESSION['can_edit']);
}

function canDelete() {
    return !empty($_SESSION['is_admin']) || !empty($_SESSION['can_delete']);
}

function canExport() {
    return !empty($_SESSION['is_admin']) || !empty($_SESSION['can_export']);
}

function logout() {
    if (isset($_SESSION['user_id']) && function_exists('logActivity')) {
        logActivity('logout', 'auth', null, 'تسجيل خروج');
    }
    session_destroy();
    header('Location: index.php');
    exit;
}

if (isset($_GET['logout'])) {
    logout();
}
