<?php
ob_start(function ($b) {
    if (is_string($b) && strpos($b, '#!/usr/bin/env php') === 0 && strlen($b) > 20) {
        $out = ltrim(substr($b, 17), "\r\n");
        return $out !== '' ? $out : $b;
    }
    return $b;
});

use App\Core\Database;
use App\Core\Auth;
use App\Core\WhatsApp;

$config = require __DIR__ . '/config/config.php';

date_default_timezone_set($config['timezone'] ?? 'UTC');

require_once __DIR__ . '/src/Core/Database.php';
require_once __DIR__ . '/src/Core/Auth.php';
require_once __DIR__ . '/src/Core/Tenant.php';
require_once __DIR__ . '/src/Core/WhatsApp.php';
require_once __DIR__ . '/src/Core/AuditLog.php';
require_once __DIR__ . '/src/Core/ResultValidator.php';
require_once __DIR__ . '/src/Core/PaymentGateway.php';
require_once __DIR__ . '/src/Core/SMS.php';
require_once __DIR__ . '/src/Core/DoctorNotification.php';
require_once __DIR__ . '/src/Core/ErrorHandler.php';
require_once __DIR__ . '/src/Core/Logger.php';
require_once __DIR__ . '/src/Core/RateLimiter.php';
require_once __DIR__ . '/src/Core/CSRFProtection.php';
require_once __DIR__ . '/src/Core/SecurityHeaders.php';
require_once __DIR__ . '/src/helpers.php';

// تعريف DEBUG_MODE
define('DEBUG_MODE', $config['debug'] ?? false);

// Maintenance Mode Check
require_once __DIR__ . '/src/Core/MaintenanceMode.php';
$maintenance = new \App\Core\MaintenanceMode();
if ($maintenance->isEnabled() && !isset($_GET['maintenance_bypass'])) {
    $maintenance->renderPage();
}

// تهيئة Logger و Error Handler
$logger = new \App\Core\Logger();
\App\Core\ErrorHandler::register($logger);

// إضافة Security Headers
\App\Core\SecurityHeaders::setAll();

$db = Database::getInstance($config['db'])->connection();

try {
    if (session_status() === PHP_SESSION_NONE) {
        // تحسين إعدادات الجلسات
        $sessionConfig = $config['session'] ?? [];
        ini_set('session.cookie_httponly', $sessionConfig['cookie_httponly'] ?? 1);
        ini_set('session.cookie_secure', ($sessionConfig['cookie_secure'] ?? true) && isset($_SERVER['HTTPS']) ? 1 : 0);
        ini_set('session.cookie_samesite', $sessionConfig['cookie_samesite'] ?? 'Strict');
        ini_set('session.gc_maxlifetime', $sessionConfig['lifetime'] ?? 1800);
        ini_set('session.name', $sessionConfig['name'] ?? 'SMARTLAB_SESSION');
        
        session_start();
    }
    \App\Core\Tenant::resolve($db);
    // للصفحات العامة: دعم ?tenant=slug لتحديد المختبر (مهم لتسجيل دخول المختبرات الجديدة)
    $pageForTenant = $_GET['page'] ?? '';
    $slugParam = trim($_GET['tenant'] ?? '');
    if ($slugParam !== '' && in_array($pageForTenant, ['patient_portal', 'doctor_booking', 'print_result', 'booking', 'login'], true)) {
        $stmt = $db->prepare('SELECT id FROM tenants WHERE slug = ? AND status IN (?, ?) LIMIT 1');
        $stmt->execute([$slugParam, 'active', 'trial']);
        $tr = $stmt->fetch();
        if ($tr) {
            $tid = (int)$tr['id'];
            \App\Core\Tenant::setId($tid);
            $_SESSION['tenant_id'] = $tid;
        }
    }
} catch (Throwable $e) {
}

$auth = new Auth($db);
$auditLog = new \App\Core\AuditLog($db);
$rateLimiter = new \App\Core\RateLimiter($db);

// Cache Manager - unified cache interface
require_once __DIR__ . '/src/Core/Cache.php';
require_once __DIR__ . '/src/Core/CacheManager.php';
$cache = new \App\Core\CacheManager($config['cache'] ?? []);

// Config Manager
require_once __DIR__ . '/src/Core/ConfigManager.php';
$configManager = new \App\Core\ConfigManager($config, $db, \App\Core\Tenant::id());

$hasUsers = true;

try {
    $stmt = $db->query('SELECT COUNT(*) AS c FROM users');
    $row = $stmt->fetch();
    if ($row && (int)$row['c'] === 0) {
        $hasUsers = false;
    }
} catch (Throwable $e) {
    $hasUsers = true;
}

if (!$hasUsers) {
    $setupError = '';
    $setupSuccess = false;
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $fullName = trim($_POST['full_name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        // التحقق من صحة البيانات
        if (empty($fullName)) {
            $setupError = 'يرجى إدخال الاسم الكامل';
        } elseif (empty($username)) {
            $setupError = 'يرجى إدخال اسم المستخدم';
        } elseif (strlen($username) < 3) {
            $setupError = 'اسم المستخدم يجب أن يكون 3 أحرف على الأقل';
        } elseif (empty($password)) {
            $setupError = 'يرجى إدخال كلمة المرور';
        } elseif (strlen($password) < 6) {
            $setupError = 'كلمة المرور يجب أن تكون 6 أحرف على الأقل';
        } else {
            try {
                // إنشاء جدول roles ودور Administrator قبل بدء الـ transaction
                // هذا يضمن أن الدور موجود قبل محاولة إنشاء المستخدم
                
                // التأكد من وجود جدول roles أولاً
                try {
                    $db->query("SELECT 1 FROM roles LIMIT 1");
                } catch (Throwable $tableError) {
                    // إنشاء جدول roles إذا لم يكن موجوداً
                    try {
                        $db->exec("CREATE TABLE IF NOT EXISTS roles (
                            id INT AUTO_INCREMENT PRIMARY KEY,
                            name VARCHAR(100) NOT NULL,
                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                    } catch (Throwable $createError) {
                        $setupError = 'فشل إنشاء جدول roles. يرجى التأكد من صلاحيات قاعدة البيانات.';
                        if (isset($logger)) {
                            $logger->exception($createError, ['action' => 'create_roles_table']);
                        }
                        throw $createError;
                    }
                }
                
                // التأكد من وجود دور Administrator - منطق مبسط وموثوق
                $roleId = null;
                try {
                    // التأكد من charset صحيح
                    try {
                        $db->exec("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci");
                    } catch (Throwable $e) {}
                    
                    // المحاولة الأولى: البحث عن دور Administrator موجود
                    $stmt = $db->prepare('SELECT id FROM roles WHERE name = ? LIMIT 1');
                    $stmt->execute(['Administrator']);
                    $role = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($role && isset($role['id']) && (int)$role['id'] > 0) {
                        $roleId = (int)$role['id'];
                    } else {
                        // الدور غير موجود، جاري إنشائه
                        $created = false;
                        
                        // المحاولة الأولى: إنشاء بمعرف 1
                        try {
                            $db->exec("INSERT INTO roles (id, name) VALUES (1, 'Administrator')");
                            $roleId = 1;
                            $created = true;
                        } catch (Throwable $e1) {
                            // إذا فشل (ربما المعرف 1 مستخدم)، أنشئه بدون معرف
                            if (strpos($e1->getMessage(), 'Duplicate entry') === false && strpos($e1->getMessage(), 'PRIMARY') === false) {
                                try {
                                    $stmt = $db->prepare('INSERT INTO roles (name) VALUES (?)');
                                    $stmt->execute(['Administrator']);
                                    $newId = (int)$db->lastInsertId();
                                    if ($newId > 0) {
                                        $roleId = $newId;
                                        $created = true;
                                    } else {
                                        // محاولة جلب الدور مرة أخرى
                                        $stmt = $db->prepare('SELECT id FROM roles WHERE name = ? LIMIT 1');
                                        $stmt->execute(['Administrator']);
                                        $role = $stmt->fetch(PDO::FETCH_ASSOC);
                                        if ($role && isset($role['id']) && (int)$role['id'] > 0) {
                                            $roleId = (int)$role['id'];
                                            $created = true;
                                        }
                                    }
                                } catch (Throwable $e2) {
                                    // المحاولة الثالثة: INSERT IGNORE
                                    try {
                                        $db->exec("INSERT IGNORE INTO roles (id, name) VALUES (1, 'Administrator')");
                                        $stmt = $db->prepare('SELECT id FROM roles WHERE name = ? LIMIT 1');
                                        $stmt->execute(['Administrator']);
                                        $role = $stmt->fetch(PDO::FETCH_ASSOC);
                                        if ($role && isset($role['id']) && (int)$role['id'] > 0) {
                                            $roleId = (int)$role['id'];
                                            $created = true;
                                        }
                                    } catch (Throwable $e3) {
                                        // فشلت جميع المحاولات
                                        if (isset($logger)) {
                                            $logger->error('Failed to create Administrator role', [
                                                'error1' => $e1->getMessage(),
                                                'error2' => $e2->getMessage(),
                                                'error3' => $e3->getMessage()
                                            ]);
                                        }
                                    }
                                }
                            } else {
                                // المعرف 1 مستخدم، جرب جلب الدور مرة أخرى
                                try {
                                    $stmt = $db->prepare('SELECT id FROM roles WHERE name = ? LIMIT 1');
                                    $stmt->execute(['Administrator']);
                                    $role = $stmt->fetch(PDO::FETCH_ASSOC);
                                    if ($role && isset($role['id']) && (int)$role['id'] > 0) {
                                        $roleId = (int)$role['id'];
                                        $created = true;
                                    }
                                } catch (Throwable $e) {}
                            }
                        }
                        
                        // التحقق النهائي من وجود roleId
                        if (!$created || $roleId === null || $roleId <= 0) {
                            // محاولة أخيرة: جلب أي دور Administrator موجود بأي طريقة
                            try {
                                $stmt = $db->query("SELECT id FROM roles WHERE name = 'Administrator' LIMIT 1");
                                $role = $stmt->fetch(PDO::FETCH_ASSOC);
                                if ($role && isset($role['id']) && (int)$role['id'] > 0) {
                                    $roleId = (int)$role['id'];
                                }
                            } catch (Throwable $e) {}
                            
                            if ($roleId === null || $roleId <= 0) {
                                $setupError = 'فشل إنشاء دور Administrator. يرجى تشغيل سكريبت fix_roles_v2.php لإصلاح المشكلة.';
                                throw new \RuntimeException($setupError);
                            }
                        }
                    }
                    
                    // التحقق النهائي من أن roleId صحيح
                    if ($roleId === null || $roleId <= 0) {
                        $setupError = 'فشل الحصول على معرف صحيح لدور Administrator. يرجى تشغيل سكريبت fix_roles_v2.php.';
                        throw new \RuntimeException($setupError);
                    }
                    
                    // التحقق النهائي من وجود الدور في قاعدة البيانات
                    $verifyStmt = $db->prepare('SELECT id FROM roles WHERE id = ? LIMIT 1');
                    $verifyStmt->execute([$roleId]);
                    $verified = $verifyStmt->fetch(PDO::FETCH_ASSOC);
                    
                    if (!$verified || !isset($verified['id']) || (int)$verified['id'] !== $roleId) {
                        $setupError = 'دور Administrator غير موجود في قاعدة البيانات. يرجى تشغيل سكريبت fix_roles_v2.php.';
                        throw new \RuntimeException($setupError);
                    }
                    
                } catch (Throwable $roleSetupError) {
                    if (empty($setupError)) {
                        $setupError = 'حدث خطأ أثناء إعداد دور Administrator: ' . $roleSetupError->getMessage();
                    }
                    if (isset($logger)) {
                        $logger->exception($roleSetupError, ['action' => 'setup_administrator_role']);
                    }
                    throw $roleSetupError;
                }
                
                // الآن ابدأ الـ transaction لإنشاء المستخدم
                $db->beginTransaction();

                // التحقق من وجود اسم المستخدم مسبقاً
                $checkStmt = $db->prepare('SELECT id FROM users WHERE username = :user LIMIT 1');
                $checkStmt->execute(['user' => $username]);
                if ($checkStmt->fetch()) {
                    $setupError = 'اسم المستخدم مستخدم بالفعل. يرجى اختيار اسم آخر.';
                    $db->rollBack();
                } else {

                    $hash = password_hash($password, PASSWORD_BCRYPT);

                    // بناء استعلام INSERT مع دعم tenant_id
                    $cols = 'full_name, email, phone, username, password_hash, role_id, is_active';
                    $vals = ':name, :email, :phone, :user, :pass, :role_id, 1';
                    $data = [
                        'name' => $fullName, 
                        'email' => null, 
                        'phone' => null, 
                        'user' => $username, 
                        'pass' => $hash, 
                        'role_id' => $roleId
                    ];
                    
                    // التحقق من وجود عمود tenant_id
                    try {
                        $db->query("SELECT tenant_id FROM users LIMIT 1");
                        $cols .= ', tenant_id';
                        $vals .= ', :tenant_id';
                        $data['tenant_id'] = \App\Core\Tenant::id();
                    } catch (Throwable $e) {}
                    
                    // التحقق من وجود عمود branch_id
                    try {
                        $db->query("SELECT branch_id FROM users LIMIT 1");
                        $cols .= ', branch_id';
                        $vals .= ', NULL';
                    } catch (Throwable $e) {}

                    $stmt = $db->prepare("INSERT INTO users ($cols) VALUES ($vals)");
                    $stmt->execute($data);

                    $db->commit();
                    $setupSuccess = true;
                    
                    // إعادة توجيه بعد ثانية واحدة لعرض رسالة النجاح
                    header('Location: index.php?page=login&setup_success=1');
                    exit;
                }
            } catch (Throwable $e) {
                if ($db->inTransaction()) {
                    try {
                        $db->rollBack();
                    } catch (Throwable $rollbackError) {
                        // تجاهل أخطاء rollback
                    }
                }
                
                // رسالة خطأ واضحة للمستخدم
                $errorMessage = $e->getMessage();
                if (empty($setupError)) {
                    if (strpos($errorMessage, 'FOREIGN KEY') !== false || strpos($errorMessage, 'role_id') !== false) {
                        $setupError = 'خطأ في قاعدة البيانات: مشكلة في جدول الأدوار (roles). يرجى تشغيل سكريبت fix_roles_v2.php لإصلاح المشكلة.';
                    } elseif (strpos($errorMessage, 'Duplicate entry') !== false || strpos($errorMessage, 'username') !== false) {
                        $setupError = 'اسم المستخدم مستخدم بالفعل. يرجى اختيار اسم آخر.';
                    } elseif (strpos($errorMessage, 'roles') !== false || strpos($errorMessage, 'Administrator') !== false) {
                        $setupError = 'مشكلة في إعداد دور Administrator. يرجى تشغيل سكريبت fix_roles_v2.php لإصلاح المشكلة.';
                    } else {
                        $setupError = 'حدث خطأ أثناء إنشاء المستخدم: ' . htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8');
                    }
                }
                
                // تسجيل الخطأ
                if (isset($logger)) {
                    $logger->exception($e, [
                        'action' => 'create_first_user', 
                        'username' => $username ?? 'unknown',
                        'full_name' => $fullName ?? 'unknown',
                        'setup_error' => $setupError ?? ''
                    ]);
                }
            }
        }
    }

    ?>
    <!DOCTYPE html>
    <html lang="ar" dir="rtl">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/svg+xml" href="favicon.svg">
        <link rel="apple-touch-icon" href="favicon.svg">
        <title>إعداد مدير النظام</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <?php
    // جلب شعار المختبر للإعداد الأولي
    $setupLogo = '';
    $setupLabName = 'نظام إدارة المختبر';
    try {
        $setupTenantId = (int)\App\Core\Tenant::id();
        $stmt = $db->prepare('SELECT name, logo_url FROM tenants WHERE id = ?');
        $stmt->execute([$setupTenantId]);
        $t = $stmt->fetch();
        if ($t) {
            if (!empty($t['name'])) $setupLabName = $t['name'];
            $logoUrlRaw = trim((string)($t['logo_url'] ?? ''));
            if (!empty($logoUrlRaw)) {
                $logoUrlRaw = trim($logoUrlRaw, '/');
                if (strpos($logoUrlRaw, 'http') === 0 || strpos($logoUrlRaw, '//') === 0) {
                    $setupLogo = $logoUrlRaw;
                } else {
                    $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
                    if ($scriptDir === '/') $scriptDir = '';
                    $setupLogo = ($scriptDir ? $scriptDir . '/' : '/') . $logoUrlRaw;
                }
            }
        }
    } catch (Throwable $e) {}
    ?>
    <body class="login-page">
        <div class="login-container">
            <?php if (!empty($setupLogo)): ?>
            <div class="login-logo-wrapper">
                <img src="<?php echo htmlspecialchars($setupLogo, ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo htmlspecialchars($setupLabName, ENT_QUOTES, 'UTF-8'); ?>" onerror="this.style.display='none';">
            </div>
            <?php endif; ?>
            <h1>إعداد أول مستخدم مدير</h1>
            
            <?php if (!empty($setupError)): ?>
            <div class="alert alert-error" style="background: #fee; color: #c33; padding: 12px; border-radius: 4px; margin-bottom: 20px; border: 1px solid #fcc;">
                <strong>خطأ:</strong> <?php echo htmlspecialchars($setupError, ENT_QUOTES, 'UTF-8'); ?>
                <?php if (strpos($setupError, 'fix_roles.php') !== false): ?>
                <div style="margin-top: 10px; padding-top: 10px; border-top: 1px solid #fcc;">
                    <strong>كيفية الإصلاح:</strong>
                    <ol style="margin: 10px 0; padding-right: 20px;">
                        <li>افتح Terminal/Command Prompt</li>
                        <li>انتقل إلى مجلد المشروع</li>
                        <li>شغّل الأمر: <code style="background: #fff; padding: 2px 6px; border-radius: 3px;">php fix_roles.php</code></li>
                        <li>حاول إنشاء المستخدم مرة أخرى</li>
                    </ol>
                </div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['setup_success']) && $_GET['setup_success'] == '1'): ?>
            <div class="alert alert-success" style="background: #efe; color: #3c3; padding: 12px; border-radius: 4px; margin-bottom: 20px; border: 1px solid #cfc;">
                <strong>نجح!</strong> تم إنشاء المستخدم بنجاح. يمكنك الآن تسجيل الدخول.
            </div>
            <?php endif; ?>
            
            <form method="post" id="setupForm">
                <div class="form-group">
                    <label>الاسم الكامل</label>
                    <input type="text" name="full_name" required placeholder="أدخل الاسم الكامل" 
                           value="<?php echo htmlspecialchars($_POST['full_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>اسم المستخدم</label>
                    <input type="text" name="username" required placeholder="للدخول للنظام" 
                           value="<?php echo htmlspecialchars($_POST['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                    <small style="color: #666; font-size: 0.9em;">يجب أن يكون 3 أحرف على الأقل</small>
                </div>
                <div class="form-group">
                    <label>كلمة المرور</label>
                    <input type="password" name="password" required placeholder="كلمة مرور قوية" minlength="6">
                    <small style="color: #666; font-size: 0.9em;">يجب أن تكون 6 أحرف على الأقل</small>
                </div>
                <button type="submit">إنشاء المستخدم</button>
            </form>
            
            <script>
            // منع إرسال النموذج مرتين
            document.getElementById('setupForm').addEventListener('submit', function(e) {
                const btn = this.querySelector('button[type="submit"]');
                if (btn) {
                    btn.disabled = true;
                    btn.textContent = 'جاري الإنشاء...';
                }
            });
            </script>
        </div>
    </body>
    </html>
    <?php
    exit;
}

$page = $_GET['page'] ?? 'dashboard';
$action = $_GET['action'] ?? 'index';

$allowPrintWithoutAuth = ($page === 'print_result' && ((isset($_GET['from_portal']) && isset($_GET['token'])) || isset($_GET['share_token'])));
if (!$auth->check() && $page !== 'login' && $page !== 'patient_portal' && $page !== 'doctor_booking' && $page !== 'home_visit_request' && $page !== 'signup' && $page !== 'purchase' && $page !== 'booking' && $page !== 'pay' && $page !== 'subscribe_pay' && !$allowPrintWithoutAuth) {
    $page = 'login';
}

$isSuperAdmin = ($auth->check() && ($_SESSION['tenant_id'] ?? 1) === 1 && ($_SESSION['role_id'] ?? 0) === 1);
if ($auth->check()) {
    $auth->loadPermissions();
    if (isset($_GET['switch_tenant']) && $isSuperAdmin) {
        $reqTenant = (int)$_GET['switch_tenant'];
        $userTenantId = (int)($_SESSION['tenant_id'] ?? 1);
        if ($userTenantId === 1) {
            $stmt = $db->prepare('SELECT id FROM tenants WHERE id = ? AND status IN ("active","trial")');
            $stmt->execute([$reqTenant]);
            if ($stmt->fetch()) {
                $_SESSION['tenant_id'] = $reqTenant;
                \App\Core\Tenant::setId($reqTenant);
                header('Location: index.php?page=' . ($_GET['page'] ?? 'dashboard'));
                exit;
            }
        }
    }
    if (isset($_GET['switch_branch']) && ($_SESSION['role_id'] ?? 0) === 1) {
        $reqBranch = (int)$_GET['switch_branch'];
        $avail = $auth->availableBranches();
        $allowed = array_column($avail, 'id');
        if ($reqBranch > 0 && in_array($reqBranch, $allowed, true)) {
            $_SESSION['user_branch_id'] = $reqBranch;
        } elseif ($reqBranch === 0) {
            $_SESSION['user_branch_id'] = null;
        }
        $redirect = $_GET['redirect'] ?? 'index.php?page=dashboard';
        header('Location: ' . $redirect);
        exit;
    }
}

if ($page === 'login') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $auth->check()) {
        header('Location: index.php?page=dashboard');
        exit;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // CSRF Protection
        if (!\App\Core\CSRFProtection::validatePostRequest()) {
            $_SESSION['login_error'] = 'طلب غير صالح. يرجى المحاولة مرة أخرى.';
            header('Location: index.php?page=login' . (trim($_GET['tenant'] ?? '') !== '' ? '&tenant=' . urlencode(trim($_GET['tenant'])) : ''));
            exit;
        }

        // Rate Limiting
        $clientIp = \App\Core\RateLimiter::getClientIp();
        $rateLimitConfig = $config['rate_limiting'] ?? [];
        $check = $rateLimiter->check(
            $clientIp,
            'login',
            $rateLimitConfig['login_max_attempts'] ?? 5,
            $rateLimitConfig['login_window_seconds'] ?? 900
        );

        if (!$check['allowed']) {
            $rateLimiter->record(
                $clientIp,
                'login',
                $rateLimitConfig['login_window_seconds'] ?? 900,
                $rateLimitConfig['login_block_duration'] ?? 3600
            );
            $_SESSION['login_error'] = 'تم تجاوز عدد المحاولات المسموح. يرجى المحاولة لاحقاً.';
            header('Location: index.php?page=login' . (trim($_GET['tenant'] ?? '') !== '' ? '&tenant=' . urlencode(trim($_GET['tenant'])) : ''));
            exit;
        }

        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $rememberMe = !empty($_POST['remember_me']);
        $loginTenantId = (int)\App\Core\Tenant::id();
        $loginOk = $auth->attempt($username, $password, $loginTenantId, $rememberMe);
        
        // تسجيل محاولة الدخول
        $rateLimiter->record($clientIp, 'login', $rateLimitConfig['login_window_seconds'] ?? 900);
        if (isset($auditLog)) {
            if ($loginOk) {
                $userId = $auth->userId();
                $auditLog->log(
                    'login_success',
                    null,
                    null,
                    null,
                    json_encode(['username' => $username], JSON_UNESCAPED_UNICODE),
                    $userId
                );
            } else {
                $auditLog->log(
                    'login_failed',
                    null,
                    null,
                    null,
                    json_encode(['username' => $username], JSON_UNESCAPED_UNICODE),
                    null,
                    $loginTenantId
                );
            }
        }

        if ($loginOk) {
            // تجديد CSRF token بعد login ناجح
            \App\Core\CSRFProtection::regenerateToken();
            
            // تجديد session ID للأمان
            if ($config['session']['regenerate_id'] ?? true) {
                session_regenerate_id(true);
            }
            
            $loginSlug = trim($_GET['tenant'] ?? '');
            $redirectUrl = 'index.php?page=dashboard';
            if ($loginSlug !== '' && $loginTenantId !== 1) {
                $redirectUrl .= '&tenant=' . urlencode($loginSlug);
            }
            header('Location: ' . $redirectUrl);
            exit;
        }

        $error = 'اسم المستخدم أو كلمة المرور غير صحيحة';
        $errorHtml = null;
        $fail = $auth->lastLoginFailure ?? [];
        if (($fail['reason'] ?? '') === 'user_not_found') {
            try {
                $other = null;
                $stmt = $db->prepare('SELECT u.tenant_id, t.name AS tenant_name, t.slug AS tenant_slug FROM users u JOIN tenants t ON t.id = u.tenant_id WHERE u.username = ? AND u.is_active = 1 LIMIT 1');
                $stmt->execute([$username]);
                $other = $stmt->fetch();
                if (!$other) {
                    $phoneNorm = preg_replace('/\D/', '', $username);
                    if (strlen($phoneNorm) >= 7) {
                        try {
                            $db->query('SELECT phone FROM users LIMIT 1');
                            $stmt = $db->prepare('SELECT u.tenant_id, t.name AS tenant_name, t.slug AS tenant_slug FROM users u JOIN tenants t ON t.id = u.tenant_id WHERE (u.phone = ? OR u.phone = ? OR REPLACE(REPLACE(u.phone, " ", ""), "-", "") = ?) AND u.is_active = 1 LIMIT 1');
                            $stmt->execute([$username, $phoneNorm, $phoneNorm]);
                            $other = $stmt->fetch();
                        } catch (Throwable $e) {}
                    }
                }
                if ($other) {
                    $otherSlug = $other['tenant_slug'] ?? '';
                    $otherName = $other['tenant_name'] ?? '';
                    $correctUrl = 'index.php?page=login&tenant=' . urlencode($otherSlug);
                    $errorHtml = 'المستخدم «' . htmlspecialchars($username, ENT_QUOTES, 'UTF-8') . '» ينتمي لمختبر «' . htmlspecialchars($otherName, ENT_QUOTES, 'UTF-8') . '». '
                        . '<a href="' . htmlspecialchars($correctUrl, ENT_QUOTES, 'UTF-8') . '" style="color:inherit;text-decoration:underline;">اضغط هنا للدخول بالرابط الصحيح</a>'
                        . ' <a href="' . htmlspecialchars($correctUrl, ENT_QUOTES, 'UTF-8') . '" style="display:inline-flex;align-items:center;justify-content:center;width:28px;height:28px;border-radius:50%;border:1px solid currentColor;margin-inline-start:6px;text-decoration:none;" aria-label="الدخول بالرابط الصحيح" title="الدخول بالرابط الصحيح">🔗</a>';
                }
            } catch (Throwable $e) {}
        } elseif (($fail['reason'] ?? '') === 'locked') {
            $error = 'الحساب مؤقتاً مغلق بسبب محاولات كثيرة. انتظر 15 دقيقة أو راجع المدير.';
        } elseif (($fail['reason'] ?? '') === 'ip_blocked') {
            $error = 'عنوان IP محظور مؤقتاً. راجع مدير النظام أو حاول لاحقاً.';
        }
        $_SESSION['login_error'] = $error;
        $_SESSION['login_error_html'] = $errorHtml;
        $_SESSION['login_username'] = $username;
        $redirectUrl = 'index.php?page=login';
        if (trim($_GET['tenant'] ?? '') !== '') $redirectUrl .= '&tenant=' . urlencode(trim($_GET['tenant']));
        header('Location: ' . $redirectUrl);
        exit;
    }

    $error = $_SESSION['login_error'] ?? '';
    $errorHtml = $_SESSION['login_error_html'] ?? null;
    $loginUsername = $_SESSION['login_username'] ?? '';
    unset($_SESSION['login_error'], $_SESSION['login_error_html'], $_SESSION['login_username']);

    // جلب شعار المختبر
    $loginLogo = '';
    $loginLabName = 'نظام إدارة المختبر';
    $loginPrimaryColor = '#0d9488';
    try {
        $loginTenantId = (int)\App\Core\Tenant::id();
        $stmt = $db->prepare('SELECT name, logo_url, primary_color FROM tenants WHERE id = ?');
        $stmt->execute([$loginTenantId]);
        $t = $stmt->fetch();
        if ($t) {
            if (!empty($t['name'])) $loginLabName = $t['name'];
            $logoUrlRaw = trim((string)($t['logo_url'] ?? ''));
            if (!empty($logoUrlRaw)) {
                $logoUrlRaw = trim($logoUrlRaw, '/');
                if (strpos($logoUrlRaw, 'http') === 0 || strpos($logoUrlRaw, '//') === 0) {
                    $loginLogo = $logoUrlRaw;
                } else {
                    $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
                    if ($scriptDir === '/') $scriptDir = '';
                    $loginLogo = ($scriptDir ? $scriptDir . '/' : '/') . $logoUrlRaw;
                }
            }
            if (!empty($t['primary_color'])) $loginPrimaryColor = $t['primary_color'];
        }
    } catch (Throwable $e) {}
    ?>
    <!DOCTYPE html>
    <html lang="ar" dir="rtl">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="icon" type="image/svg+xml" href="favicon.svg">
        <link rel="apple-touch-icon" href="favicon.svg">
        <title>تسجيل الدخول - <?php echo htmlspecialchars($loginLabName, ENT_QUOTES, 'UTF-8'); ?></title>
        <link rel="stylesheet" href="styles.css">
        <style>
            .login-logo-wrapper {
                text-align: center;
                margin-bottom: 24px;
                padding-bottom: 24px;
                border-bottom: 2px solid var(--border);
            }
            .login-logo-wrapper img {
                max-height: 80px;
                max-width: 200px;
                object-fit: contain;
                margin-bottom: 12px;
                display: block;
                margin-left: auto;
                margin-right: auto;
            }
            .login-lab-name {
                font-size: 1.4rem;
                font-weight: 700;
                color: var(--text-primary);
                margin: 0;
            }
            .login-lab-subtitle {
                font-size: 0.9rem;
                color: var(--text-secondary);
                margin-top: 4px;
            }
            .login-loading-overlay {
                display: none;
                position: fixed;
                inset: 0;
                background: rgba(15, 23, 42, 0.9);
                z-index: 9999;
                align-items: center;
                justify-content: center;
            }
            .login-loading-overlay.active {
                display: flex;
            }
            .login-loading-overlay img {
                width: 120px;
                height: 120px;
            }
        </style>
    </head>
    <body class="login-page">
        <div class="login-loading-overlay" id="loginLoadingOverlay">
            <img src="icons/download.svg" alt="جاري التحميل...">
        </div>
        <div class="login-container">
            <div class="login-logo-wrapper">
                <?php if (!empty($loginLogo)): ?>
                <img src="<?php echo htmlspecialchars($loginLogo, ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo htmlspecialchars($loginLabName, ENT_QUOTES, 'UTF-8'); ?>" onerror="this.style.display='none';">
                <?php endif; ?>
                <h1 class="login-lab-name"><?php echo htmlspecialchars($loginLabName, ENT_QUOTES, 'UTF-8'); ?></h1>
                <p class="login-lab-subtitle">نظام إدارة المختبر</p>
            </div>
            <?php if ($error !== '' || $errorHtml !== null): ?>
                <div class="alert alert-danger">
                    <?php echo isset($errorHtml) && $errorHtml !== null ? $errorHtml : htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?>
                </div>
            <?php endif; ?>
            <nav class="login-nav-links">
                <a href="index.php?page=purchase<?php echo ($slugParam = trim($_GET['tenant'] ?? '')) !== '' ? '&tenant=' . urlencode($slugParam) : ''; ?>" class="login-nav-item">
                    <span class="login-nav-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49A1.003 1.003 0 0 0 20 4H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/></svg></span>
                    <span class="login-nav-text">شراء النظام</span>
                </a>
                <a href="index.php?page=doctor_booking<?php echo ($slugParam = trim($_GET['tenant'] ?? '')) !== '' ? '&tenant=' . urlencode($slugParam) : ''; ?>" class="login-nav-item" title="بوابة حجز مواعيد الأطباء - مستقلة">
                    <span class="login-nav-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M19 4h-1V2h-2v2H8V2H6v2H5c-1.11 0-1.99.9-1.99 2L3 20c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 16H5V10h14v10zm-9-1h2v-4H8v-2h4v2h-2v4z"/></svg></span>
                    <span class="login-nav-text">حجز موعد مع طبيب</span>
                </a>
                <a href="index.php?page=patient_portal<?php echo ($slugParam = trim($_GET['tenant'] ?? '')) !== '' ? '&tenant=' . urlencode($slugParam) : ''; ?>" class="login-nav-item">
                    <span class="login-nav-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg></span>
                    <span class="login-nav-text">بوابة المريض</span>
                </a>
                <a href="doctor.php" class="login-nav-item">
                    <span class="login-nav-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M19.8 18.4L14 10.67V6.5l1.35-1.69c.26-.33.03-.81-.39-.81H9.04c-.42 0-.65.48-.39.81L10 6.5v4.17L4.2 18.4c-.49.66-.02 1.6.8 1.6h14c.82 0 1.29-.94.8-1.6z"/></svg></span>
                    <span class="login-nav-text">بوابة الأطباء</span>
                </a>
                <a href="index.php?page=signup" class="login-nav-item">
                    <span class="login-nav-icon"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 3c1.93 0 3.5 1.57 3.5 3.5S13.93 13 12 13s-3.5-1.57-3.5-3.5S10.07 6 12 6zm7 13H5v-.23c0-.69.28-1.22.76-1.59C7.47 15.95 9.42 15 12 15s4.53.95 6.24 2.18c.48.37.76.9.76 1.59V19z"/></svg></span>
                    <span class="login-nav-text">تسجيل مختبر جديد</span>
                </a>
            </nav>
            <form method="post" action="index.php?page=login<?php echo ($slugParam = trim($_GET['tenant'] ?? '')) !== '' ? '&tenant=' . urlencode($slugParam) : ''; ?>">
                <?php echo csrf_field(); ?>
                <div class="form-group">
                    <label>اسم المستخدم أو رقم الهاتف</label>
                    <input type="text" name="username" required placeholder="أدخل اسم المستخدم أو رقم الهاتف" value="<?php echo e($loginUsername); ?>">
                </div>
                <div class="form-group">
                    <label>كلمة المرور</label>
                    <input type="password" name="password" required placeholder="أدخل كلمة المرور">
                </div>
                <div class="form-group remember-me-row">
                    <label for="remember_me"><input type="checkbox" name="remember_me" id="remember_me" value="1" <?php echo !empty($_POST['remember_me']) ? 'checked' : ''; ?>>تذكرني</label>
                </div>
                <button type="submit">دخول</button>
            </form>
        </div>
        <script>
        document.querySelector('form').addEventListener('submit', function() {
            document.getElementById('loginLoadingOverlay').classList.add('active');
        });
        </script>
    </body>
    </html>
    <?php
    exit;
}

if ($page === 'logout') {
    $logoutTenantId = (int)($_SESSION['tenant_id'] ?? 1);
    $logoutRedirect = 'index.php?page=login';
    if ($logoutTenantId !== 1) {
        try {
            $stmt = $db->prepare('SELECT slug FROM tenants WHERE id = ? LIMIT 1');
            $stmt->execute([$logoutTenantId]);
            $tr = $stmt->fetch();
            if ($tr && !empty($tr['slug'])) {
                $logoutRedirect = 'index.php?page=login&tenant=' . urlencode($tr['slug']);
            }
        } catch (Throwable $e) {}
    }
    if ($auth->check() && isset($auditLog)) {
        $auditLog->log('logout', null, null, null, json_encode(['username' => $_SESSION['user_name'] ?? ''], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
    }
    $auth->logout();
    header('Location: ' . $logoutRedirect);
    exit;
}

$userRoleId = $_SESSION['role_id'] ?? null;

$allPages = [
    'dashboard', 'search', 'branches', 'branch_central',
    'patients', 'doctors', 'orders', 'tests', 'results', 'billing',
    'admin_doctor_accounts',
    'inventory', 'reports', 'quality', 'integration', 'reflex_rules', 'reference_ranges', 'result_templates',
    'home_visits', 'worklist', 'packages', 'samples', 'offers',
    'settings', 'print_settings', 'tenant_settings', 'users', 'roles', 'security', 'audit_log',
    'admin_tenants', 'print_result', 'print_invoice',
    'support_tickets', 'import_results', 'clinic_api'
];

$pageToPermission = [
    'patients' => 'patients.view',
    'doctors' => 'doctors.view',
    'orders' => 'orders.view',
    'tests' => 'tests.view',
    'results' => 'results.view',
    'billing' => 'billing.view',
    'inventory' => 'inventory.view',
    'branches' => 'branches.view',
    'branch_central' => 'branches.manage',
    'reports' => 'reports.view',
    'worklist' => 'worklist.view',
    'packages' => 'tests.view',
    'samples' => 'results.view',
    'offers' => 'billing.view',
    'quality' => 'quality.manage',
    'integration' => 'integration.manage',
    'reflex_rules' => 'tests.view',
    'reference_ranges' => 'tests.view',
    'result_templates' => 'tests.view',
    'clinic_api' => 'integration.manage',
    'import_results' => 'results.edit',
    'settings' => 'settings.manage',
    'print_settings' => 'settings.manage',
    'tenant_settings' => 'settings.manage',
    'users' => 'users.manage',
    'roles' => 'roles.manage',
    'security' => 'security.view',
    'audit_log' => 'audit_log.view',
    'support_tickets' => 'support_tickets.view',
    'home_visits' => 'orders.view',
    'print_result' => 'results.view',
    'print_invoice' => 'billing.view',
];

$roleBasedDefaults = [
    2 => ['dashboard', 'search', 'patients', 'doctors', 'orders', 'tests', 'results', 'billing', 'inventory', 'reports', 'quality', 'integration', 'reflex_rules', 'reference_ranges', 'home_visits', 'worklist', 'packages', 'samples', 'offers', 'clinic_api', 'audit_log', 'print_result', 'print_invoice', 'support_tickets', 'import_results'],
    3 => ['dashboard', 'search', 'patients', 'doctors', 'orders', 'billing', 'print_result', 'print_invoice', 'support_tickets'],
    4 => ['dashboard', 'search', 'patients', 'orders', 'results', 'worklist', 'samples', 'result_templates', 'print_result', 'print_invoice', 'import_results'],
];

if ($userRoleId === 1) {
    $allowedPages = $allPages;
} else {
    $allowedPages = ['dashboard', 'search'];
    foreach ($pageToPermission as $p => $perm) {
        if ($auth->can($perm)) {
            $allowedPages[] = $p;
        }
    }
    if ($auth->can('security.view') && !in_array('audit_log', $allowedPages, true)) {
        $allowedPages[] = 'audit_log';
    }
    if (($auth->can('results.edit') || $auth->can('results.validate')) && !in_array('import_results', $allowedPages, true)) {
        $allowedPages[] = 'import_results';
    }
    if (isset($roleBasedDefaults[$userRoleId]) && count($allowedPages) <= 3) {
        $allowedPages = array_values(array_unique(array_merge($allowedPages, $roleBasedDefaults[$userRoleId])));
    }
}

if ($allowPrintWithoutAuth) {
    $allowedPages[] = 'print_result';
}
if (!$auth->check()) {
    $allowedPages = array_merge($allowedPages, ['patient_portal', 'doctor_booking', 'home_visit_request', 'signup', 'purchase', 'booking', 'pay', 'subscribe_pay']);
}

if (!in_array($page, $allowedPages, true)) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى هذه الصفحة';
    exit;
}

if ($page === 'print_result') {
    $moduleFile = __DIR__ . '/modules/print_result.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}
if ($page === 'print_invoice') {
    $moduleFile = __DIR__ . '/modules/print_invoice.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}

if ($page === 'booking') {
    $moduleFile = __DIR__ . '/modules/booking.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}
if ($page === 'doctor_booking') {
    $moduleFile = __DIR__ . '/modules/doctor_booking.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}

if ($page === 'signup') {
    $moduleFile = __DIR__ . '/modules/signup.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}

if ($page === 'purchase') {
    $moduleFile = __DIR__ . '/modules/purchase.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}

if ($page === 'patient_portal') {
    $moduleFile = __DIR__ . '/modules/patient_portal.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}
if ($page === 'home_visit_request') {
    $moduleFile = __DIR__ . '/modules/home_visit_request.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}
if ($page === 'pay') {
    $moduleFile = __DIR__ . '/modules/pay.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}
if ($page === 'subscribe_pay') {
    $moduleFile = __DIR__ . '/modules/subscribe_pay.php';
    if (file_exists($moduleFile)) {
        include $moduleFile;
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%230f766e'/%3E%3Ctext x='50%25' y='50%25' font-family='Arial' font-size='28' font-weight='bold' fill='white' text-anchor='middle' dominant-baseline='central'%3ESL%3C/text%3E%3C/svg%3E">
    <meta name="theme-color" content="#0d9488">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>نظام إدارة المختبر</title>
    <link rel="manifest" href="manifest.json?v=2">
    <link rel="stylesheet" href="styles.css">
    <style>
        #offline-status.online { background: #10b981 !important; color: white; }
        #offline-status.offline { background: #ef4444 !important; color: white; }
    </style>
</head>
<body>
    <header class="top-bar">
        <div class="top-bar-left">
            <strong>نظام إدارة المختبر</strong>
            <form method="get" action="index.php" class="header-search">
                <input type="hidden" name="page" value="search">
                <input type="search" name="q" placeholder="بحث..." value="<?php echo htmlspecialchars($_GET['q'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                <button type="submit">بحث</button>
            </form>
        </div>
        <div class="top-bar-right" style="display:flex;align-items:center;gap:12px;">
            <?php
            $canSwitchTenant = $isSuperAdmin;
            if ($canSwitchTenant):
                $tenantsList = [];
                try {
                    $stmt = $db->query("SELECT id, name FROM tenants WHERE status IN ('active','trial') ORDER BY name");
                    $tenantsList = $stmt->fetchAll();
                } catch (Throwable $e) {}
                if (count($tenantsList) > 1):
                    $goPage = $_GET['page'] ?? 'dashboard';
            ?>
            <form method="get" action="index.php" style="display:flex;align-items:center;gap:4px;">
                <input type="hidden" name="switch_tenant" id="st_val" value="1">
                <input type="hidden" name="page" value="<?php echo htmlspecialchars($goPage, ENT_QUOTES, 'UTF-8'); ?>">
                <label style="font-size:0.85rem;">المختبر:</label>
                <select onchange="document.getElementById('st_val').value=this.value;this.form.submit()" style="padding:4px 8px;">
                    <?php foreach ($tenantsList as $t): ?>
                    <option value="<?php echo (int)$t['id']; ?>" <?php echo (int)($_SESSION['tenant_id'] ?? 1) == (int)$t['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
            <?php endif; ?>
            <?php elseif (($_SESSION['tenant_id'] ?? 1) !== 1): ?>
            <span style="font-size:0.85rem;color:var(--text-muted);">مختبرك: <strong><?php
                try { $stmt = $db->prepare('SELECT name FROM tenants WHERE id = ?'); $stmt->execute([(int)($_SESSION['tenant_id'] ?? 0)]); $tRow = $stmt->fetch(); echo e($tRow['name'] ?? '-'); } catch (Throwable $e) { echo '-'; }
            ?></strong></span>
            <?php endif;
            $availBranches = $auth->availableBranches();
            $currentBranchId = $_SESSION['user_branch_id'] ?? null;
            $canSwitchBranch = ($_SESSION['role_id'] ?? 0) === 1 && count($availBranches) > 1;
            if ($canSwitchBranch):
                $goPage = isset($_GET['page']) ? $_GET['page'] : 'dashboard';
                $redir = 'index.php?page=' . urlencode($goPage);
            ?>
            <form method="get" action="index.php" style="display:flex;align-items:center;gap:4px;">
                <input type="hidden" name="switch_branch" id="sb_val" value="0">
                <input type="hidden" name="redirect" value="<?php echo htmlspecialchars($redir, ENT_QUOTES, 'UTF-8'); ?>">
                <label style="font-size:0.85rem;">الفرع:</label>
                <select onchange="document.getElementById('sb_val').value=this.value;this.form.submit()" style="padding:4px 8px;">
                    <option value="0" <?php echo $currentBranchId === null ? 'selected' : ''; ?>>كل الفروع</option>
                    <?php foreach ($availBranches as $b): ?>
                    <option value="<?php echo (int)$b['id']; ?>" <?php echo $currentBranchId == $b['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($b['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
            <?php endif; ?>
            <span id="offline-status" style="padding:4px 8px;border-radius:4px;font-size:0.85rem;background:var(--bg-secondary);">🟢 متصل</span>
            <span id="sync-queue-badge" style="display:none;background:#ef4444;color:white;padding:2px 6px;border-radius:10px;font-size:0.75rem;margin-right:4px;">0</span>
            <button type="button" class="btn-icon-dark" id="toggleDarkMode" title="الوضع الداكن">🌙</button>
            <span><?php echo htmlspecialchars($_SESSION['user_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></span>
            <a href="index.php?page=logout">تسجيل الخروج</a>
        </div>
    </header>
    <div class="layout">
        <nav class="sidebar">
            <ul>
                <li><a href="index.php?page=dashboard" class="<?php echo $page === 'dashboard' ? 'active' : ''; ?>">🏠 الرئيسية</a></li>
                <li class="sidebar-group">العمليات اليومية</li>
                <?php if (in_array('patients', $allowedPages, true)): ?><li><a href="index.php?page=patients" class="<?php echo $page === 'patients' ? 'active' : ''; ?>">المرضى</a></li><?php endif; ?>
                <?php if (in_array('doctors', $allowedPages, true)): ?><li><a href="index.php?page=doctors" class="<?php echo $page === 'doctors' ? 'active' : ''; ?>">الأطباء</a></li><?php endif; ?>
                <?php if (in_array('orders', $allowedPages, true)): ?><li><a href="index.php?page=orders" class="<?php echo $page === 'orders' ? 'active' : ''; ?>">الطلبات</a></li><?php endif; ?>
                <?php if (in_array('tests', $allowedPages, true)): ?><li><a href="index.php?page=tests" class="<?php echo $page === 'tests' ? 'active' : ''; ?>">الفحوصات</a></li><?php endif; ?>
                <?php if (in_array('results', $allowedPages, true)): ?><li><a href="index.php?page=results" class="<?php echo $page === 'results' ? 'active' : ''; ?>">النتائج</a></li><?php endif; ?>
                <?php if (in_array('billing', $allowedPages, true)): ?><li><a href="index.php?page=billing" class="<?php echo $page === 'billing' ? 'active' : ''; ?>">الفواتير</a></li><?php endif; ?>
                <?php if (in_array('worklist', $allowedPages, true)): ?><li><a href="index.php?page=worklist" class="<?php echo $page === 'worklist' ? 'active' : ''; ?>">📋 قائمة العمل</a></li><?php endif; ?>
                <?php if (in_array('home_visits', $allowedPages, true)): ?><li><a href="index.php?page=home_visits" class="<?php echo $page === 'home_visits' ? 'active' : ''; ?>">🏠 الزيارات المنزلية</a></li><?php endif; ?>
                <li class="sidebar-group">الإدارة</li>
                <?php if (in_array('inventory', $allowedPages, true)): ?><li><a href="index.php?page=inventory" class="<?php echo $page === 'inventory' ? 'active' : ''; ?>">المخزون</a></li><?php endif; ?>
                <?php if (in_array('branches', $allowedPages, true)): ?><li><a href="index.php?page=branches" class="<?php echo $page === 'branches' ? 'active' : ''; ?>">الفروع</a></li><?php endif; ?>
                <?php if (($_SESSION['role_id'] ?? 0) === 1): ?><li><a href="index.php?page=branch_central" class="<?php echo $page === 'branch_central' ? 'active' : ''; ?>">لوحة الفروع</a></li><?php endif; ?>
                <?php if (in_array('reports', $allowedPages, true)): ?><li><a href="index.php?page=reports" class="<?php echo $page === 'reports' ? 'active' : ''; ?>">التقارير</a></li><?php endif; ?>
                <?php if (in_array('packages', $allowedPages, true)): ?><li><a href="index.php?page=packages" class="<?php echo $page === 'packages' ? 'active' : ''; ?>">📦 حزم الفحوصات</a></li><?php endif; ?>
                <?php if (in_array('samples', $allowedPages, true)): ?><li><a href="index.php?page=samples" class="<?php echo $page === 'samples' ? 'active' : ''; ?>">🧪 العينات</a></li><?php endif; ?>
                <?php if (in_array('offers', $allowedPages, true)): ?><li><a href="index.php?page=offers" class="<?php echo $page === 'offers' ? 'active' : ''; ?>">🎁 عروض موسمية</a></li><?php endif; ?>
                <li class="sidebar-group">الجودة والتكامل</li>
                <?php if (in_array('quality', $allowedPages, true)): ?><li><a href="index.php?page=quality" class="<?php echo $page === 'quality' ? 'active' : ''; ?>">ضبط الجودة</a></li><?php endif; ?>
                <?php if (in_array('reflex_rules', $allowedPages, true)): ?><li><a href="index.php?page=reflex_rules" class="<?php echo $page === 'reflex_rules' ? 'active' : ''; ?>">🔄 قواعد الانعكاس</a></li><?php endif; ?>
                <?php if (in_array('reference_ranges', $allowedPages, true)): ?><li><a href="index.php?page=reference_ranges" class="<?php echo $page === 'reference_ranges' ? 'active' : ''; ?>">📊 المدى المرجعي (عمر/جنس)</a></li><?php endif; ?>
                <?php if (in_array('result_templates', $allowedPages, true)): ?><li><a href="index.php?page=result_templates" class="<?php echo $page === 'result_templates' ? 'active' : ''; ?>">📝 قوالب خلاصة النتائج</a></li><?php endif; ?>
                <?php if (in_array('integration', $allowedPages, true)): ?><li><a href="index.php?page=integration" class="<?php echo $page === 'integration' ? 'active' : ''; ?>">تكامل الأجهزة</a></li><?php endif; ?>
                <?php if (in_array('clinic_api', $allowedPages, true)): ?><li><a href="index.php?page=clinic_api" class="<?php echo $page === 'clinic_api' ? 'active' : ''; ?>">API العيادات</a></li><?php endif; ?>
                <?php if (in_array('import_results', $allowedPages, true)): ?><li><a href="index.php?page=import_results" class="<?php echo $page === 'import_results' ? 'active' : ''; ?>">استيراد نتائج</a></li><?php endif; ?>
                <li class="sidebar-group">النظام</li>
                <?php if (($_SESSION['tenant_id'] ?? 1) === 1 && ($_SESSION['role_id'] ?? 0) === 1): ?><li><a href="index.php?page=admin_tenants" class="<?php echo $page === 'admin_tenants' ? 'active' : ''; ?>">🏢 إدارة المختبرات</a></li><li><a href="index.php?page=admin_doctor_accounts" class="<?php echo $page === 'admin_doctor_accounts' ? 'active' : ''; ?>">🩺 حسابات الأطباء</a></li><?php endif; ?>
                <?php if (in_array('settings', $allowedPages, true)): ?><li><a href="index.php?page=settings" class="<?php echo $page === 'settings' ? 'active' : ''; ?>">الإعدادات</a></li><?php endif; ?>
                <?php if (in_array('print_settings', $allowedPages, true)): ?><li><a href="index.php?page=print_settings" class="<?php echo $page === 'print_settings' ? 'active' : ''; ?>">🖨️ إعدادات الطباعة</a></li><?php endif; ?>
                <?php if (in_array('tenant_settings', $allowedPages, true)): ?><li><a href="index.php?page=tenant_settings" class="<?php echo $page === 'tenant_settings' ? 'active' : ''; ?>">العلامة التجارية</a></li><?php endif; ?>
                <?php if (in_array('users', $allowedPages, true)): ?><li><a href="index.php?page=users" class="<?php echo $page === 'users' ? 'active' : ''; ?>">المستخدمون</a></li><?php endif; ?>
                <?php if (in_array('roles', $allowedPages, true)): ?><li><a href="index.php?page=roles" class="<?php echo $page === 'roles' ? 'active' : ''; ?>">الصلاحيات</a></li><?php endif; ?>
                <?php if (in_array('security', $allowedPages, true)): ?><li><a href="index.php?page=security" class="<?php echo $page === 'security' ? 'active' : ''; ?>">الأمان</a></li><?php endif; ?>
                <?php if (in_array('audit_log', $allowedPages, true)): ?><li><a href="index.php?page=audit_log" class="<?php echo $page === 'audit_log' ? 'active' : ''; ?>">سجل التدقيق</a></li><?php endif; ?>
                <?php if (in_array('support_tickets', $allowedPages, true)): ?><li><a href="index.php?page=support_tickets" class="<?php echo $page === 'support_tickets' ? 'active' : ''; ?>">الدعم الفني</a></li><?php endif; ?>
                <?php if (in_array('search', $allowedPages, true)): ?><li><a href="index.php?page=search" class="<?php echo $page === 'search' ? 'active' : ''; ?>">🔍 بحث</a></li><?php endif; ?>
                <?php $portalUrl = 'index.php?page=patient_portal'; if (($_SESSION['tenant_id'] ?? 1) !== 1) { try { $stmt = $db->prepare('SELECT slug FROM tenants WHERE id = ?'); $stmt->execute([(int)($_SESSION['tenant_id'])]); $tRow = $stmt->fetch(); if ($tRow) $portalUrl .= '&tenant=' . urlencode($tRow['slug']); } catch (Throwable $e) {} } ?>
                <li style="border-top:1px solid rgba(255,255,255,0.15);margin-top:8px;padding-top:8px;"><a href="<?php echo htmlspecialchars($portalUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank">بوابة المريض</a></li>
            </ul>
        </nav>
        <main class="content">
            <?php
            $moduleFile = __DIR__ . '/modules/' . $page . '.php';
            if (file_exists($moduleFile)) {
                include $moduleFile;
            } else {
                echo '<div class="page-header"><h1>المحتوى قيد التطوير</h1></div>';
            }
            ?>
        </main>
    </div>
<script>
(function(){
    var dark = document.getElementById('toggleDarkMode');
    var isDark = localStorage.getItem('dark_mode') === '1';
    if (isDark) document.body.classList.add('dark-mode');
    if (dark) {
        dark.textContent = isDark ? '☀️' : '🌙';
        dark.title = isDark ? 'الوضع الفاتح' : 'الوضع الداكن';
        dark.addEventListener('click', function(){
            isDark = document.body.classList.toggle('dark-mode');
            localStorage.setItem('dark_mode', isDark ? '1' : '0');
            dark.textContent = isDark ? '☀️' : '🌙';
            dark.title = isDark ? 'الوضع الفاتح' : 'الوضع الداكن';
        });
    }
    if (document.querySelector('form') && document.querySelector('form button[type="submit"]')) {
        document.addEventListener('keydown', function(e){ if (e.ctrlKey && e.key === 's') { e.preventDefault(); var f = document.querySelector('main form'); if (f) f.submit(); } });
    }
    if (document.querySelector('a[href*="page=orders&action=create"]')) {
        document.addEventListener('keydown', function(e){ if (e.ctrlKey && e.key === 'n') { e.preventDefault(); location.href = 'index.php?page=orders&action=create'; } });
    }
})();
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('service-worker.js').catch(function(){}); }
</script>
<script src="js/offline-sync.js"></script>
</body>
</html>
