<?php
/**
 * layout.php - النسخة الاحترافية المطورة
 * الشاملة للسايدبار الذكي، الهيدر المرن، وتنسيقات البطاقات الحديثة
 */

declare(strict_types=1);

if (!function_exists('renderPage')) {

    function renderPage(string $title, string $activeMenu, callable $callback): void
    {
        $orgName = function_exists('getSetting') ? getSetting('org_name', APP_NAME) : APP_NAME;
        $admin = function_exists('currentAdmin') ? currentAdmin() : [];
        $adminName = trim((string)($admin['full_name'] ?? $admin['display_name'] ?? 'مدير النظام'));

        // القائمة البرمجية (Navigation Logic)
        $navItems = [
            'dashboard'     => ['icon' => 'bi-grid-1x2', 'label' => 'لوحة التحكم', 'href' => ADMIN_PATH . '/dashboard.php'],
            'beneficiaries' => ['icon' => 'bi-people', 'label' => 'المستفيدون', 'href' => ADMIN_PATH . '/beneficiaries.php'],
            'distributions' => ['icon' => 'bi-box-seam', 'label' => 'التوزيعات', 'href' => ADMIN_PATH . '/distributions.php'],
            'import'        => ['icon' => 'bi-cloud-arrow-up', 'label' => 'استيراد البيانات', 'href' => ADMIN_PATH . '/import.php'],
            'ayni'          => ['icon' => 'bi-heart-pulse', 'label' => 'الواردات العينية', 'href' => '/zaka/ayni/index.php'],
            'finance'       => ['icon' => 'bi-cash-stack', 'label' => 'المالية', 'href' => '/zaka/finance/index.php'],
            'settings'      => ['icon' => 'bi-sliders', 'label' => 'الإعدادات', 'href' => ADMIN_PATH . '/settings.php'],
            'study'         => ['icon' => 'bi-card-checklist', 'label' => 'لوحة الدراسات', 'href' => '/zaka/study/admin.php'], 
        ];

        $quickLinks = [
            'orphan_admin'         => ['label' => 'إدارة الأيتام', 'href' => '/zaka/orphan/'],
            'kafala_requests_admin' => ['label' => 'طلبات الكفالة (إدارة)', 'href' => '/zaka/orphan/public/admin_requests.php'],
            'docs_center'          => ['label' => 'مركز الوثائق', 'href' => '/zaka/documents/admin/index.php'],
            'docs_benef'           => ['label' => 'وثائق المنتفعين', 'href' => '/zaka/documents/admin/beneficiary_documents.php'],
        ];
?><!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($title) ?> — <?= e($orgName) ?></title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&display=swap" rel="stylesheet">

    <style>
        :root {
            --sidebar-width: 255px;
            --topbar-height: 65px;
            --main-bg: #f8fafc;
            --primary-color: #3b82f6;
            --sidebar-bg: #ffffff;
            --text-dark: #1e293b;
            --text-muted: #64748b;
            --border-color: #e2e8f0;
            --card-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        body {
            font-family: 'Cairo', sans-serif;
            background-color: var(--main-bg);
            color: var(--text-dark);
            margin: 0;
            overflow-x: hidden;
        }

        /* --- Sidebar Style --- */
        #sidebar {
            position: fixed; top: 0; right: 0; bottom: 0;
            width: var(--sidebar-width); background: var(--sidebar-bg);
            border-left: 1px solid var(--border-color); z-index: 1050;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .sidebar-header {
            height: var(--topbar-height); padding: 0 20px;
            display: flex; align-items: center; 
            border-bottom: 1px solid var(--border-color);
            background: #fff;
        }

        .nav-container { padding: 15px 12px; height: calc(100vh - var(--topbar-height)); overflow-y: auto; }
        
        .nav-group-label {
            font-size: 0.75rem; font-weight: 800; color: #94a3b8;
            padding: 15px 15px 8px; text-transform: uppercase; letter-spacing: 0.5px;
        }

        .nav-item-link {
            display: flex; align-items: center; padding: 11px 16px;
            color: var(--text-muted); text-decoration: none; border-radius: 10px;
            font-size: 0.92rem; font-weight: 500; transition: 0.2s; margin-bottom: 2px;
        }

        .nav-item-link i { font-size: 1.2rem; margin-left: 12px; transition: 0.2s; }
        
        .nav-item-link:hover { background: #f1f5f9; color: var(--primary-color); }
        .nav-item-link.active {
            background: #eff6ff; color: var(--primary-color); font-weight: 700;
        }
        .nav-item-link.active i { color: var(--primary-color); }

        /* --- Content Area --- */
        #topbar {
            position: fixed; top: 0; left: 0; right: var(--sidebar-width);
            height: var(--topbar-height); background: rgba(255,255,255,0.9);
            backdrop-filter: blur(8px); border-bottom: 1px solid var(--border-color);
            display: flex; align-items: center; justify-content: space-between;
            padding: 0 30px; z-index: 1000; transition: all 0.3s ease;
        }

        #main-content {
            margin-right: var(--sidebar-width);
            margin-top: var(--topbar-height);
            padding: 30px;
            min-height: calc(100vh - var(--topbar-height));
        }

        /* --- Stats Cards (Modern Design) --- */
        .stat-card {
            border: none; border-radius: 18px; padding: 25px 20px;
            position: relative; overflow: hidden; color: #fff;
            transition: all 0.3s ease; min-height: 135px;
            display: flex; flex-direction: column; justify-content: center;
            box-shadow: var(--card-shadow);
        }
        .stat-card:hover { transform: translateY(-7px); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
        .stat-card .bg-icon {
            position: absolute; left: -10px; bottom: -10px;
            font-size: 5rem; opacity: 0.15; transform: rotate(-15deg);
        }
        .stat-card .card-label { font-size: 0.95rem; font-weight: 600; opacity: 0.9; margin-bottom: 5px; }
        .stat-card .card-value { font-size: 2rem; font-weight: 800; }

        /* Gradients */
        .grad-blue { background: linear-gradient(135deg, #3b82f6, #1d4ed8); }
        .grad-purple { background: linear-gradient(135deg, #8b5cf6, #6d28d9); }
        .grad-red { background: linear-gradient(135deg, #ef4444, #b91c1c); }
        .grad-green { background: linear-gradient(135deg, #10b981, #059669); }
        .grad-dark { background: linear-gradient(135deg, #475569, #1e293b); }

        /* Mobile Adjustments */
        @media (max-width: 991px) {
            #sidebar { transform: translateX(100%); }
            #sidebar.open { transform: translateX(0); }
            #topbar { right: 0; padding: 0 15px; }
            #main-content { margin-right: 0; padding: 20px 15px; }
            .sidebar-overlay {
                display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.4);
                backdrop-filter: blur(2px); z-index: 1040;
            }
            .sidebar-overlay.show { display: block; }
        }

        /* Utilities */
        .user-profile {
            display: flex; align-items: center; gap: 12px;
            padding: 6px 15px; background: #f8fafc; border-radius: 50px;
            border: 1px solid var(--border-color);
        }
    </style>
</head>
<body>

<div class="sidebar-overlay" id="overlay"></div>

<aside id="sidebar">
    <div class="sidebar-header">
        <i class="bi bi-shield-check text-primary me-2" style="font-size: 1.5rem;"></i>
        <span class="fw-bold" style="font-size: 1.05rem; letter-spacing: -0.5px;"><?= e($orgName) ?></span>
    </div>

    <div class="nav-container">
        <div class="nav-group-label">الرئيسية</div>
        <?php foreach ($navItems as $key => $item): ?>
            <a href="<?= e($item['href']) ?>" class="nav-item-link <?= $activeMenu === $key ? 'active' : '' ?>">
                <i class="bi <?= e($item['icon']) ?>"></i>
                <span><?= e($item['label']) ?></span>
            </a>
        <?php endforeach; ?>

        <div class="nav-group-label">خدمات إضافية</div>
        <div class="accordion accordion-flush" id="accQuickLinks">
            <div class="accordion-item" style="background: transparent; border: none;">
                <a class="nav-item-link w-100 justify-content-between" data-bs-toggle="collapse" href="#qLinks" role="button">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-collection"></i>
                        <span>ادارة الأيتام للكفالات</span>
                    </div>
                    <i class="bi bi-chevron-down me-0 ms-auto" style="font-size: 0.7rem; opacity: 0.5;"></i>
                </a>
                <div id="qLinks" class="collapse <?= in_array($activeMenu, array_keys($quickLinks)) ? 'show' : '' ?>" data-bs-parent="#accQuickLinks">
                    <div class="ps-4 mt-1">
                        <?php foreach ($quickLinks as $key => $item): ?>
                            <a href="<?= e($item['href']) ?>" class="nav-item-link py-2 <?= $activeMenu === $key ? 'active' : '' ?>" style="font-size: 0.85rem;">
                                <i class="bi bi-dot"></i>
                                <?= e($item['label']) ?>
                            </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="mt-4 pt-4 border-top">
            <a href="<?= e(ADMIN_PATH) ?>/logout.php" class="nav-item-link text-danger">
                <i class="bi bi-box-arrow-right"></i>
                <span>تسجيل الخروج</span>
            </a>
        </div>
    </div>
</aside>

<header id="topbar">
    <div class="d-flex align-items-center">
        <button class="btn btn-light d-lg-none me-2" id="toggleBtn">
            <i class="bi bi-list"></i>
        </button>
        <h1 class="h6 mb-0 fw-bold"><?= e($title) ?></h1>
    </div>

    <div class="user-profile">
        <div class="d-none d-md-block">
            <div class="fw-bold" style="font-size: 0.85rem;"><?= e($adminName) ?></div>
            <div class="text-muted" style="font-size: 0.7rem;">مسؤول النظام</div>
        </div>
        <div class="bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" style="width: 35px; height: 35px; font-weight: 800;">
            <?= e(mb_substr($adminName, 0, 1)) ?>
        </div>
    </div>
</header>

<main id="main-content">
    <?php $callback(); ?>
</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // التحكم في السايدبار للموبايل
    const toggleBtn = document.getElementById('toggleBtn');
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('overlay');

    if(toggleBtn) {
        toggleBtn.onclick = () => {
            sidebar.classList.toggle('open');
            overlay.classList.toggle('show');
        }
    }

    overlay.onclick = () => {
        sidebar.classList.remove('open');
        overlay.classList.remove('show');
    }

    // إغلاق التنبيهات تلقائياً بعد 5 ثواني (اختياري)
    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert-dismissible');
        alerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
</script>
</body>
</html>
<?php
    }
}