<?php
// Enforce Baghdad Local Timezone (Asia/Baghdad) globally
date_default_timezone_set('Asia/Baghdad');

// Central Session and Permission Middleware System
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Enable GZIP Output Buffering Compression for Ultra High Performance
if (!ob_get_level() && !headers_sent()) {
    if (extension_loaded('zlib') && strpos($_SERVER['HTTP_ACCEPT_ENCODING'] ?? '', 'gzip') !== false) {
        ob_start('ob_gzhandler');
    } else {
        ob_start();
    }
}

// Enterprise Security HTTP Headers
header("X-Content-Type-Options: nosniff");
header("X-Frame-Options: SAMEORIGIN");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

// CSRF Token Seeding
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Session Inactivity Timeout (2 Hours = 7200 Seconds)
$maxInactivity = 7200;
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > $maxInactivity)) {
    session_unset();
    session_destroy();
    header('HTTP/1.1 401 Unauthorized');
    echo json_encode(['status' => 'error', 'message' => 'انتهت مدة الجلسة بسبب عدم النشاط، يرجى إعادة تسجيل الدخول.']);
    exit;
}
$_SESSION['last_activity'] = time();

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || !isset($_SESSION['user'])) {
    header('HTTP/1.1 401 Unauthorized');
    echo json_encode(['status' => 'error', 'message' => 'عذراً، يجب تسجيل الدخول أولاً للوصول للبيانات.']);
    exit;
}

// Real-Time Permissions & Live Account Status Synchronization with DB
if (isset($conn) && isset($_SESSION['user']['id']) && is_numeric($_SESSION['user']['id'])) {
    $uid = intval($_SESSION['user']['id']);
    $resSync = $conn->query("SELECT status, permissions FROM users WHERE id = $uid LIMIT 1");
    if ($resSync && $rowSync = $resSync->fetch_assoc()) {
        if ($rowSync['status'] === 'suspended') {
            session_unset();
            session_destroy();
            header('HTTP/1.1 403 Forbidden');
            echo json_encode(['status' => 'error', 'message' => 'عذراً، تم إيقاف حسابك من قبل إدارة النظام.']);
            exit;
        }
        $freshPerms = json_decode($rowSync['permissions'], true);
        if ($freshPerms && is_array($freshPerms)) {
            $_SESSION['user']['permissions'] = $freshPerms;
        }
    }
}

/**
 * Checks if the logged in user has the required permission for a specific page and action type.
 * 
 * @param string $pageKey The identifier of the page/component (e.g. 'customers', 'debts')
 * @param string $actionType The type of action (e.g. 'view', 'add', 'edit', 'delete')
 */
function checkApiPagePermission($pageKey, $actionType) {
    if (!isset($_SESSION['user'])) {
        header('HTTP/1.1 401 Unauthorized');
        echo json_encode(['status' => 'error', 'message' => 'عذراً، يجب تسجيل الدخول أولاً للوصول للبيانات.']);
        exit;
    }
    $user = $_SESSION['user'];
    
    // Main administrator is always allowed full access
    if (isset($user['username']) && strtolower($user['username']) === 'admin') {
        return;
    }
    
    if (!isset($user['permissions'][$pageKey]) || !isset($user['permissions'][$pageKey][$actionType]) || $user['permissions'][$pageKey][$actionType] !== true) {
        header('HTTP/1.1 403 Forbidden');
        echo json_encode(['status' => 'error', 'message' => 'عذراً، لا تمتلك الصلاحيات الكافية لتنفيذ هذا الإجراء.']);
        exit;
    }
}

/**
 * Helper to check if user is allowed to see other users' data.
 * @return bool
 */
function canViewOthersData() {
    if (!isset($_SESSION['user'])) return false;
    $user = $_SESSION['user'];
    
    // Main administrator is always allowed
    if (strtolower($user['username']) === 'admin') {
        return true;
    }
    
    // Check special permission
    if (isset($user['permissions']['view_others_data']['view']) && $user['permissions']['view_others_data']['view'] === true) {
        return true;
    }
    
    return false;
}
