<?php
/**
 * Smart Doctor - بوابة الأطباء
 * واجهة منفصلة لتسجيل دخول الأطباء وعرض مرضاهم ونتائج التحاليل والإحصائيات
 */
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;
});

$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/Session.php';
require_once __DIR__ . '/src/Core/Auth.php';
require_once __DIR__ . '/src/Core/DoctorAuth.php';
require_once __DIR__ . '/src/Core/UnifiedAuth.php';
require_once __DIR__ . '/src/Core/Csrf.php';
require_once __DIR__ . '/src/Core/Tenant.php';
require_once __DIR__ . '/src/Core/TOTP.php';

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

\App\Core\Session::start();
\App\Core\Tenant::resolve($db);
if (\App\Core\Tenant::isSubdomainRejected()) {
    http_response_code(403);
    header('Content-Type: text/html; charset=utf-8');
    echo '<!DOCTYPE html><html lang="ar" dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>غير متاح</title></head><body style="font-family:system-ui,sans-serif;padding:2rem;text-align:center;background:#0f172a;color:#e2e8f0;"><h1 style="margin:0 0 12px;">المختبر غير متاح</h1><p style="color:#94a3b8;margin:0;">النطاق يشير إلى مختبر غير مسجّل، موقوف، أو انتهى الاشتراك. تحقق من الرابط أو تواصل مع الدعم.</p></body></html>';
    exit;
}

$auth = new \App\Core\Auth($db);
$doctorAuth = new \App\Core\DoctorAuth($db);
$unifiedAuth = new \App\Core\UnifiedAuth($db, $auth);

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

// تسجيل الدخول
if ($page === 'login') {
    if ($unifiedAuth->isLoggedIn()) {
        $availablePortals = $unifiedAuth->availablePortals();
        if (in_array('doctor', $availablePortals, true) && $unifiedAuth->activatePortal('doctor')) {
            header('Location: doctor.php?page=dashboard');
            exit;
        }
        if (!in_array('doctor', $availablePortals, true)) {
            header('Location: index.php?page=choose_portal');
            exit;
        }
    }
    if ($doctorAuth->check()) {
        header('Location: doctor.php?page=dashboard');
        exit;
    }
    $loginStep = $_GET['step'] ?? 'form';
    $noDoctorAccounts = false;
    try {
        $cnt = $db->query('SELECT COUNT(*) FROM doctor_accounts')->fetchColumn();
        $noDoctorAccounts = ((int)$cnt === 0);
    } catch (Throwable $e) { $noDoctorAccounts = true; }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        \App\Core\Csrf::enforce($_POST['_csrf'] ?? null, 'doctor.php?page=login');
        if ($loginStep === '2fa' && $doctorAuth->hasPending2FA()) {
            if (!empty($_POST['skip_2fa'])) {
                if ($doctorAuth->disable2FAAndCompleteLogin()) {
                    header('Location: doctor.php?page=dashboard');
                    exit;
                }
            }
            $code = trim($_POST['totp_code'] ?? '');
            if ($code !== '' && $doctorAuth->verify2FA($code)) {
                header('Location: doctor.php?page=dashboard');
                exit;
            }
            if ($code !== '') {
                $loginError = 'رمز التحقق غير صحيح. استخدم التطبيق (مثل Google Authenticator).';
            }
            $loginStep = '2fa';
        } else {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $attempt = $doctorAuth->attempt($username, $password);
            if ($attempt === true) {
                $unifiedAuth->syncFromDoctorSession();
                header('Location: doctor.php?page=dashboard');
                exit;
            }
            if ($attempt === '2fa_required') {
                header('Location: doctor.php?page=login&step=2fa');
                exit;
            }
            $tenantForUnified = (int)(\App\Core\Tenant::id());
            $login = $unifiedAuth->attempt($username, $password, $tenantForUnified, false);
            if (!empty($login['ok'])) {
                $redirect = $unifiedAuth->redirectTargetAfterLogin();
                header('Location: ' . $redirect);
                exit;
            }
            $_SESSION['doctor_login_error'] = 'اسم المستخدم أو كلمة المرور غير صحيحة';
            header('Location: doctor.php?page=login');
            exit;
        }
    } elseif ($loginStep === '2fa' && $doctorAuth->hasPending2FA()) {
        // عرض نموذج 2FA
    } elseif ($loginStep === '2fa') {
        header('Location: doctor.php?page=login');
        exit;
    }
    $loginError = $_SESSION['doctor_login_error'] ?? \App\Core\Csrf::pullError();
    if (isset($_SESSION['doctor_login_error'])) unset($_SESSION['doctor_login_error']);
    ?>
    <!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">
        <title>تسجيل الدخول - Smart Doctor</title>
        <link rel="stylesheet" href="styles.css">
        <style>
            .doctor-login-bg { background: linear-gradient(135deg, #0f172a 0%, #1e3a5f 50%, #0d9488 100%); }
            .doctor-login-title { color: #14b8a6; font-size: 1.8rem; }
        </style>
    </head>
    <body class="login-page doctor-login-bg">
        <div class="login-container">
            <h1 class="doctor-login-title">🩺 Smart Doctor</h1>
            <p style="text-align:center;color:var(--text-secondary);margin-bottom:24px;">بوابة الأطباء - عرض المرضى والتحاليل</p>
            <?php if ($noDoctorAccounts): ?>
            <div class="alert alert-warning" style="background:#fef3c7;border:1px solid #f59e0b;color:#92400e;">
                لا توجد حسابات أطباء. يجب إنشاء حساب من لوحة إدارة المختبر:<br>
                <a href="index.php?page=admin_doctor_accounts" style="color:#0d9488;font-weight:600;">لوحة التحكم → حسابات الأطباء</a> (تسجيل دخول كـ مدير المنصة مطلوب أولاً)
            </div>
            <?php elseif ($loginError !== null && $loginError !== ''): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($loginError, ENT_QUOTES, 'UTF-8'); ?></div>
            <p style="font-size:0.85rem;color:var(--text-secondary);margin-top:8px;">💡 بيانات الدخول تُنشأ من <a href="index.php?page=admin_doctor_accounts" style="color:#14b8a6;">حسابات الأطباء</a> في نظام المختبر (ليست نفس بيانات مستخدمي المختبر)</p>
            <?php endif; ?>
            <?php if ($loginStep === '2fa'): ?>
            <form method="post" action="doctor.php?page=login&step=2fa">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <p style="text-align:center;color:var(--text-secondary);margin-bottom:16px;">أدخل رمز التحقق من تطبيق المصادقة (مثل Google Authenticator)</p>
                <div class="form-group">
                    <label>رمز التحقق (6 أرقام)</label>
                    <input type="text" name="totp_code" placeholder="000000" pattern="[0-9]{6}" maxlength="6" inputmode="numeric" autocomplete="one-time-code" style="text-align:center;letter-spacing:8px;font-size:1.5rem;">
                </div>
                <button type="submit">تحقق والدخول</button>
                <p style="text-align:center;margin-top:16px;">
                    <button type="submit" name="skip_2fa" value="1" style="background:transparent;border:none;color:#64748b;font-size:0.9rem;cursor:pointer;text-decoration:underline;">لم أفعّل التحقق الثنائي — الدخول مباشرة</button>
                </p>
                <p style="text-align:center;margin-top:12px;"><a href="doctor.php?page=login" style="color:#14b8a6;font-size:0.9rem;">← إلغاء وتغيير المستخدم</a></p>
            </form>
            <?php else: ?>
            <form method="post">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <div class="form-group">
                    <label>اسم المستخدم</label>
                    <input type="text" name="username" required placeholder="أدخل اسم المستخدم">
                </div>
                <div class="form-group">
                    <label>كلمة المرور</label>
                    <input type="password" name="password" required placeholder="أدخل كلمة المرور">
                </div>
                <button type="submit">دخول</button>
            </form>
            <?php endif; ?>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// تسجيل الخروج
if ($page === 'logout') {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !\App\Core\Csrf::isValid($_POST['_csrf'] ?? null)) {
        http_response_code(405);
        echo 'طلب غير صالح';
        exit;
    }
    $doctorAuth->logout();
    if ($unifiedAuth->isLoggedIn()) {
        $unifiedAuth->clearPortal('doctor');
        $remaining = $unifiedAuth->availablePortals();
        if (!empty($remaining)) {
            if (count($remaining) === 1 && $unifiedAuth->activatePortal($remaining[0])) {
                header('Location: ' . $unifiedAuth->portalHome($remaining[0]));
                exit;
            }
            header('Location: index.php?page=choose_portal');
            exit;
        }
    }
    header('Location: doctor.php?page=login');
    exit;
}

// التحقق من الدخول لجميع الصفحات الأخرى
if (!$doctorAuth->check()) {
    if ($unifiedAuth->isLoggedIn() && in_array('doctor', $unifiedAuth->availablePortals(), true) && $unifiedAuth->activatePortal('doctor')) {
        // session bridge succeeded
    } else {
        header('Location: doctor.php?page=login');
        exit;
    }
}
if (!$doctorAuth->check()) {
    header('Location: doctor.php?page=login');
    exit;
}

// حارس CSRF عام لكل طلبات POST داخل بوابة الطبيب
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $page !== 'login' && $page !== 'logout') {
    $csrfRedirect = 'doctor.php?page=' . urlencode((string)$page);
    if (isset($_GET['action']) && $_GET['action'] !== '') {
        $csrfRedirect .= '&action=' . urlencode((string)$_GET['action']);
    }
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null, $csrfRedirect);
}

$doctorId = $doctorAuth->doctorId();
$tenantId = $doctorAuth->tenantId();
\App\Core\Tenant::setId($tenantId);

// لا ننفذ migrations أثناء runtime في production.
// يتم الاعتماد على migrations الرسمية مسبقاً، ونكتفي بتسجيل نقص schema إذا وجد.
$doctorSchemaChecks = [
    ['sql' => 'SELECT id FROM doctor_follow_up_reminders LIMIT 1', 'name' => 'doctor_follow_up_reminders'],
    ['sql' => 'SELECT id FROM doctor_search_history LIMIT 1', 'name' => 'doctor_search_history'],
    ['sql' => 'SELECT id FROM doctor_appointments LIMIT 1', 'name' => 'doctor_appointments'],
    ['sql' => 'SELECT booking_token FROM doctor_accounts LIMIT 1', 'name' => 'doctor_accounts.booking_token'],
    ['sql' => 'SELECT photo FROM doctor_accounts LIMIT 1', 'name' => 'doctor_accounts.photo'],
    ['sql' => 'SELECT two_factor_enabled FROM doctor_accounts LIMIT 1', 'name' => 'doctor_accounts.two_factor_enabled'],
    ['sql' => 'SELECT phone FROM doctor_accounts LIMIT 1', 'name' => 'doctor_accounts.phone'],
    ['sql' => 'SELECT id FROM patient_accounts LIMIT 1', 'name' => 'patient_accounts'],
    ['sql' => 'SELECT whatsapp_notify_appointments FROM doctor_accounts LIMIT 1', 'name' => 'doctor_accounts.whatsapp_notify_appointments'],
    ['sql' => 'SELECT id FROM doctor_alerts LIMIT 1', 'name' => 'doctor_alerts'],
    ['sql' => 'SELECT id FROM patient_appointment_reminders LIMIT 1', 'name' => 'patient_appointment_reminders'],
    ['sql' => 'SELECT id FROM whatsapp_send_queue LIMIT 1', 'name' => 'whatsapp_send_queue'],
    ['sql' => 'SELECT whatsapp_instance_id FROM doctor_accounts LIMIT 1', 'name' => 'doctor_accounts.whatsapp_instance_id'],
    ['sql' => 'SELECT reminder_entity_type FROM whatsapp_send_queue LIMIT 1', 'name' => 'whatsapp_send_queue.reminder_entity_type'],
];
foreach ($doctorSchemaChecks as $check) {
    try {
        $db->query($check['sql']);
    } catch (Throwable $e) {
        error_log('doctor.php schema missing: ' . $check['name'] . ' | run migrations before production traffic');
    }
}

$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

/** رابط واتساب مجاني (wa.me) - بدون API ولا تكلفة */
function doctor_wa_link($phone, $message = '') {
    $p = preg_replace('/\D/', '', trim((string)$phone));
    if (strlen($p) < 8) return '';
    if (strlen($p) === 10 && $p[0] === '0') $p = '964' . substr($p, 1);
    elseif (strlen($p) === 9 && $p[0] === '7') $p = '964' . $p;
    $url = 'https://wa.me/' . $p;
    if ($message !== '') $url .= '?text=' . rawurlencode($message);
    return $url;
}

// تحميل الوحدة المطلوبة
$doctorPages = ['dashboard', 'patients', 'results', 'statistics', 'profile', 'search', 'trend', 'print', 'reminders', 'appointments', 'alerts', 'tasks', 'templates', 'share', 'accounts', 'reports', 'patient_file_pdf', 'booking_link'];
if (!in_array($page, $doctorPages, true)) {
    $page = 'dashboard';
}

// تذكير متابعة - إضافة
if ($page === 'reminders' && ($_GET['action'] ?? '') === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $pid = (int)($_POST['patient_id'] ?? 0);
    $rdate = trim($_POST['reminder_date'] ?? '');
    $note = trim($_POST['note'] ?? '');
    $toReminders = isset($_POST['redirect']) && $_POST['redirect'] === 'reminders';
    if ($pid > 0 && $rdate !== '') {
        try {
            $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
            $stmt = $db->prepare('INSERT INTO doctor_follow_up_reminders (doctor_account_id, patient_id, reminder_date, note) VALUES (?, ?, ?, ?)');
            $stmt->execute([$doctorAuth->accountId(), $pid, $rdate, $note ?: null]);
            $_SESSION['doctor_msg'] = 'تم إضافة التذكير.';
        } catch (Throwable $e) {}
        header('Location: doctor.php?page=' . ($toReminders ? 'reminders' : 'results&patient_id=' . $pid));
        exit;
    }
}
// تذكير - تم/حذف/تعديل
if ($page === 'reminders' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['id'])) {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $rid = (int)($_POST['id'] ?? 0);
    if ($rid > 0) {
        try {
            $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
            $stmt = $db->prepare('SELECT id, patient_id FROM doctor_follow_up_reminders WHERE id = ? AND doctor_account_id = ?');
            $stmt->execute([$rid, $doctorAuth->accountId()]);
            $r = $stmt->fetch();
            if ($r) {
                $rAction = $_POST['action'] ?? '';
                if ($rAction === 'done') {
                    $db->prepare('UPDATE doctor_follow_up_reminders SET is_done = 1 WHERE id = ?')->execute([$rid]);
                    $_SESSION['doctor_msg'] = 'تم تنفيذ التذكير.';
                } elseif ($rAction === 'delete') {
                    $db->prepare('DELETE FROM doctor_follow_up_reminders WHERE id = ?')->execute([$rid]);
                    $_SESSION['doctor_msg'] = 'تم حذف التذكير.';
                } elseif ($rAction === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
                    $rdate = trim($_POST['reminder_date'] ?? '');
                    $note = trim($_POST['note'] ?? '');
                    if ($rdate !== '') {
                        $db->prepare('UPDATE doctor_follow_up_reminders SET reminder_date = ?, note = ? WHERE id = ?')->execute([$rdate, $note ?: null, $rid]);
                        $_SESSION['doctor_msg'] = 'تم تحديث التذكير.';
                    }
                }
                header('Location: doctor.php?page=reminders');
                exit;
            }
        } catch (Throwable $e) {}
    }
}
// المواعيد - إضافة
if ($page === 'appointments' && ($_GET['action'] ?? '') === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $pid = (int)($_POST['patient_id'] ?? 0);
    $adate = trim($_POST['appointment_date'] ?? '');
    $atime = trim($_POST['appointment_time'] ?? '');
    $duration = (int)($_POST['duration_minutes'] ?? 30);
    $note = trim($_POST['note'] ?? '');
    if ($pid > 0 && $adate !== '' && $atime !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $adate)) {
        $duration = max(15, min(120, $duration));
        try {
            $db->query('SELECT id FROM doctor_appointments LIMIT 1');
            $timeVal = preg_match('/^\d{1,2}:\d{2}(:\d{2})?$/', $atime) ? $atime : ($atime . ':00');
            if (substr_count($timeVal, ':') === 1) $timeVal .= ':00';
            $startNew = strtotime($adate . ' ' . $timeVal);
            $endNew = $startNew + ($duration * 60);
            $overlapStmt = $db->prepare('SELECT appointment_time, duration_minutes FROM doctor_appointments WHERE doctor_account_id = ? AND appointment_date = ? AND status IN ("scheduled","confirmed")');
            $overlapStmt->execute([$doctorAuth->accountId(), $adate]);
            $hasOverlap = false;
            foreach ($overlapStmt->fetchAll() as $ex) {
                $startEx = strtotime($adate . ' ' . ($ex['appointment_time'] ?? '00:00:00'));
                $endEx = $startEx + ((int)($ex['duration_minutes'] ?? 30) * 60);
                if ($startNew < $endEx && $startEx < $endNew) {
                    $hasOverlap = true;
                    break;
                }
            }
            if ($hasOverlap) {
                $suggestion = null;
                for ($i = 1; $i <= 24; $i++) {
                    $candStart = $startNew + ($i * 15 * 60);
                    $candEnd = $candStart + ($duration * 60);
                    $ok = true;
                    $overlapStmt->execute([$doctorAuth->accountId(), $adate]);
                    foreach ($overlapStmt->fetchAll() as $ex) {
                        $startEx = strtotime($adate . ' ' . ($ex['appointment_time'] ?? '00:00:00'));
                        $endEx = $startEx + ((int)($ex['duration_minutes'] ?? 30) * 60);
                        if ($candStart < $endEx && $startEx < $candEnd) {
                            $ok = false;
                            break;
                        }
                    }
                    if ($ok) {
                        $suggestion = date('H:i', $candStart);
                        break;
                    }
                }
                $_SESSION['doctor_msg'] = $suggestion
                    ? ('⚠️ يوجد تعارض في هذا الوقت. الوقت المقترح: ' . $suggestion)
                    : '⚠️ يوجد تعارض في هذا الوقت. يرجى اختيار وقت آخر.';
                header('Location: doctor.php?page=appointments&date=' . urlencode($adate));
                exit;
            }
            $stmt = $db->prepare('INSERT INTO doctor_appointments (doctor_account_id, patient_id, appointment_date, appointment_time, duration_minutes, note) VALUES (?, ?, ?, ?, ?, ?)');
            $stmt->execute([$doctorAuth->accountId(), $pid, $adate, $timeVal, $duration, $note ?: null]);
            $_SESSION['doctor_msg'] = 'تم حجز الموعد.';
        } catch (Throwable $e) {}
        header('Location: doctor.php?page=appointments&date=' . urlencode($adate));
        exit;
    }
}
// المواعيد - تأكيد/تم/إلغاء/لم يحضر/تعديل/نسخ
if ($page === 'appointments' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && isset($_POST['id'])) {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $aid = (int)($_POST['id'] ?? 0);
    $aptDate = trim($_POST['date'] ?? date('Y-m-d'));
    if ($aid > 0 && preg_match('/^\d{4}-\d{2}-\d{2}$/', $aptDate)) {
        try {
            $db->query('SELECT id FROM doctor_appointments LIMIT 1');
            $stmt = $db->prepare('SELECT * FROM doctor_appointments WHERE id = ? AND doctor_account_id = ?');
            $stmt->execute([$aid, $doctorAuth->accountId()]);
            $apt = $stmt->fetch();
            if ($apt) {
                $act = $_POST['action'] ?? '';
                if ($act === 'confirm') {
                    $db->prepare('UPDATE doctor_appointments SET status = ? WHERE id = ?')->execute(['confirmed', $aid]);
                    $_SESSION['doctor_msg'] = 'تم تأكيد الموعد.';
                } elseif ($act === 'complete') {
                    $db->prepare('UPDATE doctor_appointments SET status = ? WHERE id = ?')->execute(['completed', $aid]);
                    $_SESSION['doctor_msg'] = 'تم تنفيذ الموعد.';
                } elseif ($act === 'cancel') {
                    $db->prepare('UPDATE doctor_appointments SET status = ? WHERE id = ?')->execute(['cancelled', $aid]);
                    $_SESSION['doctor_msg'] = 'تم إلغاء الموعد.';
                } elseif ($act === 'no_show') {
                    $db->prepare('UPDATE doctor_appointments SET status = ? WHERE id = ?')->execute(['no_show', $aid]);
                    $_SESSION['doctor_msg'] = 'تم تسجيل عدم الحضور.';
                } elseif ($act === 'copy') {
                    $toDate = trim($_POST['to_date'] ?? date('Y-m-d', strtotime($aptDate . ' +1 day')));
                    if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $toDate)) {
                        $db->prepare('INSERT INTO doctor_appointments (doctor_account_id, patient_id, appointment_date, appointment_time, duration_minutes, note) VALUES (?, ?, ?, ?, ?, ?)')
                            ->execute([$doctorAuth->accountId(), $apt['patient_id'], $toDate, $apt['appointment_time'], $apt['duration_minutes'], $apt['note']]);
                        $_SESSION['doctor_msg'] = 'تم نسخ الموعد لـ ' . $toDate . '.';
                        $aptDate = $toDate;
                    }
                }
                header('Location: doctor.php?page=appointments&date=' . urlencode($aptDate));
                exit;
            }
        } catch (Throwable $e) {}
    }
}
// المواعيد - تعديل (POST)
if ($page === 'appointments' && ($_GET['action'] ?? '') === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $aid = (int)($_POST['apt_id'] ?? 0);
    $aptDate = trim($_POST['date'] ?? date('Y-m-d'));
    $atime = trim($_POST['appointment_time'] ?? '');
    $duration = (int)($_POST['duration_minutes'] ?? 30);
    $note = trim($_POST['note'] ?? '');
    if ($aid > 0 && $atime !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $aptDate)) {
        $duration = max(15, min(120, $duration));
        try {
            $stmt = $db->prepare('SELECT id FROM doctor_appointments WHERE id = ? AND doctor_account_id = ?');
            $stmt->execute([$aid, $doctorAuth->accountId()]);
            if ($stmt->fetch()) {
                $timeVal = preg_match('/^\d{1,2}:\d{2}(:\d{2})?$/', $atime) ? $atime : ($atime . ':00');
                if (substr_count($timeVal, ':') === 1) $timeVal .= ':00';
                $db->prepare('UPDATE doctor_appointments SET appointment_time = ?, duration_minutes = ?, note = ? WHERE id = ?')
                    ->execute([$timeVal, $duration, $note ?: null, $aid]);
                $_SESSION['doctor_msg'] = 'تم تحديث الموعد.';
            }
        } catch (Throwable $e) {}
        header('Location: doctor.php?page=appointments&date=' . urlencode($aptDate));
        exit;
    }
}
// المرضى - إضافة مريض جديد من بوابة الطبيب
if ($page === 'patients' && ($_GET['action'] ?? '') === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullName = trim($_POST['full_name'] ?? '');
    $gender = $_POST['gender'] ?? null;
    $dob = $_POST['date_of_birth'] ?? null;
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $nationalId = trim($_POST['national_id'] ?? '');
    $address = trim($_POST['address'] ?? '');
    $bloodType = trim($_POST['blood_type'] ?? '');
    $chronicText = trim($_POST['chronic_conditions'] ?? '');
    $allergyText = trim($_POST['allergies'] ?? '');

    if ($fullName !== '') {
        [$quotaOk, $quotaMsg] = \App\Core\TenantPolicy::monthlyNewPatientQuotaOk($db, $tenantId);
        if (!$quotaOk) {
            $_SESSION['doctor_error'] = $quotaMsg;
            header('Location: doctor.php?page=patients');
            exit;
        }

        $code = 'P' . time();
        if ($dob === '') {
            $dob = null;
        }
        $newPatientId = 0;
        try {
            $db->query('SELECT email FROM patients LIMIT 1');
            $stmt = $db->prepare(
                'INSERT INTO patients (patient_code, full_name, gender, date_of_birth, phone, email, national_id, address, tenant_id)
                 VALUES (:code, :name, :gender, :dob, :phone, :email, :nid, :addr, :tid)'
            );
            $stmt->execute([
                'code' => $code,
                'name' => $fullName,
                'gender' => $gender ?: null,
                'dob' => $dob,
                'phone' => $phone ?: null,
                'email' => $email ?: null,
                'nid' => $nationalId ?: null,
                'addr' => $address ?: null,
                'tid' => $tenantId,
            ]);
            $newPatientId = (int)$db->lastInsertId();
        } catch (Throwable $e) {
            try {
                $stmt = $db->prepare(
                    'INSERT INTO patients (patient_code, full_name, gender, date_of_birth, phone, national_id, address, tenant_id)
                     VALUES (:code, :name, :gender, :dob, :phone, :nid, :addr, :tid)'
                );
                $stmt->execute([
                    'code' => $code,
                    'name' => $fullName,
                    'gender' => $gender ?: null,
                    'dob' => $dob,
                    'phone' => $phone ?: null,
                    'nid' => $nationalId ?: null,
                    'addr' => $address ?: null,
                    'tid' => $tenantId,
                ]);
                $newPatientId = (int)$db->lastInsertId();
            } catch (Throwable $e2) {
                try {
                    $stmt = $db->prepare(
                        'INSERT INTO patients (patient_code, full_name, gender, date_of_birth, phone, national_id, address)
                         VALUES (:code, :name, :gender, :dob, :phone, :nid, :addr)'
                    );
                    $stmt->execute([
                        'code' => $code,
                        'name' => $fullName,
                        'gender' => $gender ?: null,
                        'dob' => $dob,
                        'phone' => $phone ?: null,
                        'nid' => $nationalId ?: null,
                        'addr' => $address ?: null,
                    ]);
                    $newPatientId = (int)$db->lastInsertId();
                } catch (Throwable $e3) {
                    $newPatientId = 0;
                }
            }
        }

        if ($newPatientId > 0) {
            try {
                $db->query('SELECT default_doctor_id FROM patients LIMIT 1');
                $db->prepare('UPDATE patients SET default_doctor_id = ? WHERE id = ?')->execute([$doctorId, $newPatientId]);
            } catch (Throwable $e) {}

            try {
                $db->query('SELECT id FROM patient_medical_notes LIMIT 1');
                if ($bloodType !== '') {
                    $stmt = $db->prepare('INSERT INTO patient_medical_notes (patient_id, doctor_account_id, note_type, content) VALUES (?, ?, ?, ?)');
                    $stmt->execute([$newPatientId, $doctorAuth->accountId(), 'general', 'فصيلة الدم: ' . $bloodType]);
                }
                if ($chronicText !== '') {
                    $stmt = $db->prepare('INSERT INTO patient_medical_notes (patient_id, doctor_account_id, note_type, content) VALUES (?, ?, ?, ?)');
                    $stmt->execute([$newPatientId, $doctorAuth->accountId(), 'diagnosis', $chronicText]);
                }
                if ($allergyText !== '') {
                    $stmt = $db->prepare('INSERT INTO patient_medical_notes (patient_id, doctor_account_id, note_type, content) VALUES (?, ?, ?, ?)');
                    $stmt->execute([$newPatientId, $doctorAuth->accountId(), 'allergy', $allergyText]);
                }
            } catch (Throwable $e) {}

            $_SESSION['doctor_msg'] = 'تم إضافة المريض بنجاح.';
            header('Location: doctor.php?page=results&patient_id=' . $newPatientId);
            exit;
        }
    }
    $_SESSION['doctor_msg'] = 'تعذر إضافة المريض.';
    header('Location: doctor.php?page=patients');
    exit;
}
// مفضلة - إضافة/إزالة
if (
    $page === 'patients'
    && $_SERVER['REQUEST_METHOD'] === 'POST'
    && (($_POST['action'] ?? '') === 'favorite')
    && isset($_POST['patient_id'])
) {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $fpid = (int)($_POST['patient_id'] ?? 0);
    $add = (($_POST['add'] ?? '1') === '1');
    if ($fpid > 0) {
        try {
            $db->query('SELECT doctor_account_id FROM doctor_favorite_patients LIMIT 1');
            if ($add) {
                $db->prepare('INSERT IGNORE INTO doctor_favorite_patients (doctor_account_id, patient_id) VALUES (?, ?)')->execute([$doctorAuth->accountId(), $fpid]);
            } else {
                $db->prepare('DELETE FROM doctor_favorite_patients WHERE doctor_account_id = ? AND patient_id = ?')->execute([$doctorAuth->accountId(), $fpid]);
            }
        } catch (Throwable $e) {}
        header('Location: doctor.php?page=patients' . (($q = trim($_POST['q'] ?? $_GET['q'] ?? '')) !== '' ? '&q=' . urlencode($q) : ''));
        exit;
    }
}

// إنشاء رابط مشاركة النتائج
if ($page === 'results' && $_SERVER['REQUEST_METHOD'] === 'POST' && (($_POST['action'] ?? '') === 'share') && isset($_POST['order_id'])) {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $shareOrderId = (int)($_POST['order_id'] ?? 0);
    try {
        $stmt = $db->prepare("SELECT o.id FROM lab_orders o WHERE o.id = ? $tenantCond $doctorCond");
        $stmt->execute([$shareOrderId]);
        if ($stmt->fetch()) {
            $db->query('SELECT id FROM report_share_links LIMIT 1');
            $token = bin2hex(random_bytes(16));
            $expires = date('Y-m-d H:i:s', time() + (7 * 24 * 3600));
            $db->prepare('INSERT INTO report_share_links (order_id, token, expires_at) VALUES (?, ?, ?)')->execute([$shareOrderId, $token, $expires]);
            $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
            $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/index.php'));
            if ($scriptDir === '/' || $scriptDir === '\\') $scriptDir = '';
            $shareUrl = rtrim($baseUrl . $scriptDir, '/') . '/index.php?page=print_result&share_token=' . urlencode($token);
            $_SESSION['doctor_share_url'] = $shareUrl;
            $_SESSION['doctor_share_msg'] = 'تم إنشاء الرابط. صالح لمدة 7 أيام.';
        }
    } catch (Throwable $e) {}
    header('Location: doctor.php?page=results&order_id=' . $shareOrderId);
    exit;
}

// تفعيل/إلغاء 2FA - من الملف الشخصي
if ($page === 'profile' && ($_GET['action'] ?? '') === 'enable_2fa' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once __DIR__ . '/src/Core/TOTP.php';
    try {
        $db->query('SELECT two_factor_enabled FROM doctor_accounts LIMIT 1');
        $secret = \App\Core\TOTP::generateSecret();
        $db->prepare('UPDATE doctor_accounts SET two_factor_enabled = 1, two_factor_secret = ?, two_factor_verified_at = NULL WHERE id = ?')
            ->execute([$secret, $doctorAuth->accountId()]);
        $_SESSION['doctor_2fa_secret_setup'] = $secret;
        $_SESSION['doctor_profile_msg'] = 'تم تفعيل 2FA. يرجى مسح QR أو إدخال الرمز في تطبيق المصادقة ثم التحقق.';
    } catch (Throwable $e) {
        $_SESSION['doctor_profile_error'] = 'فشل تفعيل 2FA.';
    }
    header('Location: doctor.php?page=profile&setup_2fa=1');
    exit;
}
if ($page === 'profile' && ($_GET['action'] ?? '') === 'verify_2fa' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once __DIR__ . '/src/Core/TOTP.php';
    $code = trim($_POST['totp_code'] ?? '');
    try {
        $stmt = $db->prepare('SELECT two_factor_secret FROM doctor_accounts WHERE id = ?');
        $stmt->execute([$doctorAuth->accountId()]);
        $row = $stmt->fetch();
        $secret = $row ? trim((string)$row['two_factor_secret']) : '';
        if ($secret && \App\Core\TOTP::verify($secret, $code)) {
            $db->prepare('UPDATE doctor_accounts SET two_factor_verified_at = NOW() WHERE id = ?')->execute([$doctorAuth->accountId()]);
            unset($_SESSION['doctor_2fa_secret_setup']);
            $_SESSION['doctor_profile_msg'] = 'تم تفعيل التحقق الثنائي 2FA بنجاح.';
        } else {
            $_SESSION['doctor_profile_error'] = 'رمز التحقق غير صحيح.';
        }
    } catch (Throwable $e) {
        $_SESSION['doctor_profile_error'] = 'فشل التحقق.';
    }
    header('Location: doctor.php?page=profile');
    exit;
}
if ($page === 'profile' && ($_GET['action'] ?? '') === 'disable_2fa' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $confirm = trim($_POST['password'] ?? '');
    try {
        $stmt = $db->prepare('SELECT password_hash FROM doctor_accounts WHERE id = ?');
        $stmt->execute([$doctorAuth->accountId()]);
        $acc = $stmt->fetch();
        if ($acc && password_verify($confirm, $acc['password_hash'])) {
            $db->prepare('UPDATE doctor_accounts SET two_factor_enabled = 0, two_factor_secret = NULL, two_factor_verified_at = NULL WHERE id = ?')
                ->execute([$doctorAuth->accountId()]);
            $_SESSION['doctor_profile_msg'] = 'تم إلغاء التحقق الثنائي.';
        } else {
            $_SESSION['doctor_profile_error'] = 'كلمة المرور غير صحيحة.';
        }
    } catch (Throwable $e) {}
    header('Location: doctor.php?page=profile');
    exit;
}
// رفع صورة الملف الشخصي
if ($page === 'profile' && ($_GET['action'] ?? '') === 'upload_photo' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $aid = $doctorAuth->accountId();
    $uploadDir = __DIR__ . '/uploads/doctor_photos/';
    if (!is_dir($uploadDir)) @mkdir($uploadDir, 0755, true);
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['photo'];
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
        $maxSize = 2 * 1024 * 1024;
        if (in_array($file['type'], $allowedTypes, true) && $file['size'] <= $maxSize) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)) ?: 'jpg';
            $fileName = $aid . '_' . time() . '.' . $ext;
            $filePath = $uploadDir . $fileName;
            if (move_uploaded_file($file['tmp_name'], $filePath)) {
                try {
                    $stmt = $db->prepare('SELECT photo FROM doctor_accounts WHERE id = ?');
                    $stmt->execute([$aid]);
                    $old = $stmt->fetch();
                    if ($old && !empty($old['photo']) && strpos($old['photo'], 'uploads/doctor_photos/') === 0) {
                        $oldPath = __DIR__ . '/' . $old['photo'];
                        if (file_exists($oldPath)) @unlink($oldPath);
                    }
                    $photoRel = 'uploads/doctor_photos/' . $fileName;
                    $db->prepare('UPDATE doctor_accounts SET photo = ? WHERE id = ?')->execute([$photoRel, $aid]);
                    $_SESSION['doctor_profile_msg'] = 'تم تحميل الصورة بنجاح.';
                } catch (Throwable $e) {
                    @unlink($filePath);
                    $_SESSION['doctor_profile_error'] = 'فشل حفظ الصورة.';
                }
            } else {
                $_SESSION['doctor_profile_error'] = 'فشل تحميل الملف.';
            }
        } else {
            $_SESSION['doctor_profile_error'] = 'نوع الملف غير مدعوم أو الحجم كبير جداً (الحد الأقصى 2MB).';
        }
    } else {
        $_SESSION['doctor_profile_error'] = 'لم يتم اختيار صورة.';
    }
    header('Location: doctor.php?page=profile');
    exit;
}

// تحديث الهاتف وإشعارات واتساب
if ($page === 'profile' && ($_GET['action'] ?? '') === 'update_notifications' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->query('SELECT phone FROM doctor_accounts LIMIT 1');
        $phone = trim($_POST['phone'] ?? '');
        $whatsappNotify = isset($_POST['whatsapp_notify_critical']) ? 1 : 0;
        $whatsappAppointments = isset($_POST['whatsapp_notify_appointments']) ? 1 : 0;
        $patientRemind = isset($_POST['patient_whatsapp_remind']) ? 1 : 0;
        $waInstance = trim($_POST['whatsapp_instance_id'] ?? '');
        $waToken = trim($_POST['whatsapp_access_token'] ?? '');
        $aid = $doctorAuth->accountId();
        try {
            $db->query('SELECT whatsapp_notify_appointments FROM doctor_accounts LIMIT 1');
            $cols = ['phone' => $phone ?: null, 'whatsapp_notify_critical' => $whatsappNotify, 'whatsapp_notify_appointments' => $whatsappAppointments];
            try {
                $db->query('SELECT patient_whatsapp_remind FROM doctor_accounts LIMIT 1');
                $cols['patient_whatsapp_remind'] = $patientRemind;
            } catch (Throwable $z) {}
            try {
                $db->query('SELECT whatsapp_instance_id FROM doctor_accounts LIMIT 1');
                $cols['whatsapp_instance_id'] = $waInstance ?: null;
                $cols['whatsapp_access_token'] = $waToken ?: null;
            } catch (Throwable $z) {}
            $sets = array_map(function($k) { return "$k = ?"; }, array_keys($cols));
            $db->prepare('UPDATE doctor_accounts SET ' . implode(', ', $sets) . ' WHERE id = ?')
                ->execute(array_merge(array_values($cols), [$aid]));
        } catch (Throwable $x) {
            $db->prepare('UPDATE doctor_accounts SET phone = ?, whatsapp_notify_critical = ?, whatsapp_notify_appointments = ? WHERE id = ?')
                ->execute([$phone ?: null, $whatsappNotify, $whatsappAppointments, $aid]);
            try {
                $db->prepare('UPDATE doctor_accounts SET patient_whatsapp_remind = ? WHERE id = ?')->execute([$patientRemind, $aid]);
            } catch (Throwable $y) {}
            try {
                $db->prepare('UPDATE doctor_accounts SET whatsapp_instance_id = ?, whatsapp_access_token = ? WHERE id = ?')->execute([$waInstance ?: null, $waToken ?: null, $aid]);
            } catch (Throwable $y) {}
        }
        $_SESSION['doctor_profile_msg'] = 'تم تحديث إعدادات الإشعارات.';
    } catch (Throwable $e) {
        $_SESSION['doctor_profile_error'] = 'فشل التحديث.';
    }
    header('Location: doctor.php?page=profile');
    exit;
}

// تغيير كلمة المرور - من الملف الشخصي
if ($page === 'profile' && ($_GET['action'] ?? '') === 'change_password' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $current = $_POST['current_password'] ?? '';
    $newPass = trim($_POST['new_password'] ?? '');
    $confirm = trim($_POST['confirm_password'] ?? '');
    $policyCheck = \App\Core\Auth::validatePasswordStrength($newPass, $config['security']['password_policy'] ?? []);
    if (!$policyCheck['valid']) {
        $_SESSION['doctor_profile_error'] = implode(' ', $policyCheck['errors']);
    } elseif ($newPass !== $confirm) {
        $_SESSION['doctor_profile_error'] = 'كلمة المرور الجديدة غير متطابقة.';
    } elseif ($current !== '' && $newPass !== '') {
        try {
            $stmt = $db->prepare('SELECT password_hash FROM doctor_accounts WHERE id = ?');
            $stmt->execute([$doctorAuth->accountId()]);
            $acc = $stmt->fetch();
            if ($acc && password_verify($current, $acc['password_hash'])) {
                $hash = password_hash($newPass, PASSWORD_BCRYPT);
                $db->prepare('UPDATE doctor_accounts SET password_hash = ? WHERE id = ?')->execute([$hash, $doctorAuth->accountId()]);
                $_SESSION['doctor_profile_msg'] = 'تم تغيير كلمة المرور بنجاح.';
            } else {
                $_SESSION['doctor_profile_error'] = 'كلمة المرور الحالية غير صحيحة.';
            }
        } catch (Throwable $e) {
            $_SESSION['doctor_profile_error'] = 'حدث خطأ.';
        }
    }
    header('Location: doctor.php?page=profile');
    exit;
}

// قوالب رسائل (واتساب)
if ($page === 'profile' && ($_GET['action'] ?? '') === 'save_message_templates' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $aid = $doctorAuth->accountId();
    try {
        $db->query('SELECT id FROM doctor_message_templates LIMIT 1');
        foreach (['booking_whatsapp' => 'tpl_booking', 'critical_whatsapp' => 'tpl_critical'] as $key => $postName) {
            $body = trim((string)($_POST[$postName] ?? ''));
            $db->prepare(
                'INSERT INTO doctor_message_templates (doctor_account_id, template_key, body) VALUES (?,?,?)
                 ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = CURRENT_TIMESTAMP'
            )->execute([$aid, $key, $body]);
        }
        $_SESSION['doctor_profile_msg'] = 'تم حفظ القوالب.';
    } catch (Throwable $e) {
        $_SESSION['doctor_profile_error'] = 'تعذر الحفظ — شغّل ترحيل قاعدة البيانات (run_038).';
    }
    header('Location: doctor.php?page=profile');
    exit;
}

// حذف ملاحظة طبية
if ($page === 'results' && $_SERVER['REQUEST_METHOD'] === 'POST' && (($_POST['action'] ?? '') === 'delete_note') && isset($_POST['id']) && isset($_POST['patient_id'])) {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $noteId = (int)($_POST['id'] ?? 0);
    $pid = (int)($_POST['patient_id'] ?? 0);
    if ($noteId > 0 && $pid > 0) {
        try {
            $db->query('SELECT id FROM patient_medical_notes LIMIT 1');
            $stmt = $db->prepare('DELETE FROM patient_medical_notes WHERE id = ? AND patient_id = ? AND doctor_account_id = ?');
            $stmt->execute([$noteId, $pid, $doctorAuth->accountId()]);
            if ($stmt->rowCount() > 0) {
                $_SESSION['doctor_note_msg'] = 'تم حذف الملاحظة.';
            } else {
                $_SESSION['doctor_note_error'] = 'تعذر حذف الملاحظة.';
            }
        } catch (Throwable $e) {
            $_SESSION['doctor_note_error'] = 'فشل الحذف.';
        }
    }
    header('Location: doctor.php?page=results&patient_id=' . $pid);
    exit;
}

// تعديل ملاحظة طبية
if ($page === 'results' && ($_GET['action'] ?? '') === 'edit_note' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $noteId = (int)($_POST['note_id'] ?? 0);
    $pid = (int)($_POST['patient_id'] ?? 0);
    $noteType = in_array(trim($_POST['note_type'] ?? 'general'), ['general','lab_review','diagnosis','follow_up','allergy','medication']) ? trim($_POST['note_type']) : 'general';
    $content = trim($_POST['content'] ?? '');
    if ($noteId > 0 && $pid > 0 && $content !== '') {
        try {
            $db->query('SELECT id FROM patient_medical_notes LIMIT 1');
            $stmt = $db->prepare('UPDATE patient_medical_notes SET note_type = ?, content = ? WHERE id = ? AND patient_id = ? AND doctor_account_id = ?');
            $stmt->execute([$noteType, $content, $noteId, $pid, $doctorAuth->accountId()]);
            if ($stmt->rowCount() > 0) {
                $_SESSION['doctor_note_msg'] = 'تم تحديث الملاحظة.';
            } else {
                $_SESSION['doctor_note_error'] = 'تعذر تحديث الملاحظة.';
            }
        } catch (Throwable $e) {
            $_SESSION['doctor_note_error'] = 'فشل التحديث.';
        }
    }
    header('Location: doctor.php?page=results&patient_id=' . $pid);
    exit;
}

// إضافة تشخيص
if ($page === 'results' && ($_GET['action'] ?? '') === 'add_diagnosis' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $pid = (int)($_POST['patient_id'] ?? 0);
    $dname = trim($_POST['diagnosis_name'] ?? '');
    $dcode = trim($_POST['diagnosis_code'] ?? '');
    $dtype = in_array(trim($_POST['diagnosis_type'] ?? 'custom'), ['icd10','custom','suspected']) ? trim($_POST['diagnosis_type']) : 'custom';
    $orderId = (int)($_POST['order_id'] ?? 0) ?: null;
    $notes = trim($_POST['notes'] ?? '');
    if ($pid > 0 && $dname !== '') {
        try {
            $db->query('SELECT id FROM patient_diagnoses LIMIT 1');
            $stmt = $db->prepare('INSERT INTO patient_diagnoses (patient_id, doctor_account_id, diagnosis_code, diagnosis_name, diagnosis_type, order_id, notes, diagnosed_at) VALUES (?, ?, ?, ?, ?, ?, ?, CURDATE())');
            $stmt->execute([$pid, $doctorAuth->accountId(), $dcode ?: null, $dname, $dtype, $orderId, $notes ?: null]);
            $_SESSION['doctor_msg'] = 'تم إضافة التشخيص.';
        } catch (Throwable $e) {
            $_SESSION['doctor_error'] = 'فشل الحفظ.';
        }
    }
    header('Location: doctor.php?page=results&patient_id=' . $pid);
    exit;
}
// حذف تشخيص
if ($page === 'results' && $_SERVER['REQUEST_METHOD'] === 'POST' && (($_POST['action'] ?? '') === 'delete_diagnosis') && isset($_POST['id']) && isset($_POST['patient_id'])) {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $did = (int)($_POST['id'] ?? 0);
    $pid = (int)($_POST['patient_id'] ?? 0);
    if ($did > 0 && $pid > 0) {
        try {
            $db->query('SELECT id FROM patient_diagnoses LIMIT 1');
            $stmt = $db->prepare('DELETE FROM patient_diagnoses WHERE id = ? AND patient_id = ? AND doctor_account_id = ?');
            $stmt->execute([$did, $pid, $doctorAuth->accountId()]);
            $_SESSION['doctor_msg'] = 'تم حذف التشخيص.';
        } catch (Throwable $e) {}
    }
    header('Location: doctor.php?page=results&patient_id=' . $pid);
    exit;
}

// إضافة ملاحظة طبية
if ($page === 'results' && ($_GET['action'] ?? '') === 'add_note' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $pid = (int)($_POST['patient_id'] ?? 0);
    $noteType = in_array(trim($_POST['note_type'] ?? 'general'), ['general','lab_review','diagnosis','follow_up','allergy','medication']) ? trim($_POST['note_type']) : 'general';
    $content = trim($_POST['content'] ?? '');
    if ($pid > 0 && $content !== '') {
        try {
            $db->query('SELECT id FROM patient_medical_notes LIMIT 1');
            $stmt = $db->prepare('INSERT INTO patient_medical_notes (patient_id, doctor_account_id, note_type, content) VALUES (?, ?, ?, ?)');
            $stmt->execute([$pid, $doctorAuth->accountId(), $noteType, $content]);
            $_SESSION['doctor_note_msg'] = 'تم حفظ الملاحظة.';
        } catch (Throwable $e) {
            $_SESSION['doctor_note_error'] = 'فشل الحفظ.';
        }
    }
    header('Location: doctor.php?page=results&patient_id=' . $pid);
    exit;
}

// إنشاء طلب تحاليل من بوابة الطبيب (يرسل مباشرة للمختبر)
if ($page === 'results' && ($_GET['action'] ?? '') === 'create_order' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null);
    $patientId = (int)($_POST['patient_id'] ?? 0);
    $priority = in_array($_POST['priority'] ?? '', ['normal', 'high', 'urgent'], true) ? $_POST['priority'] : 'normal';
    $sampleType = trim((string)($_POST['sample_type'] ?? 'blood'));
    $allowedSampleTypes = ['blood', 'urine', 'stool', 'swab', 'serum', 'plasma', 'other'];
    if (!in_array($sampleType, $allowedSampleTypes, true)) $sampleType = 'blood';
    $testIds = array_values(array_filter(array_map('intval', (array)($_POST['tests'] ?? [])), static fn($v) => $v > 0));

    if ($doctorId <= 0) {
        $_SESSION['doctor_error'] = 'هذا الحساب غير مرتبط بطبيب. يرجى ربط الحساب من إدارة حسابات الأطباء.';
        header('Location: doctor.php?page=results&patient_id=' . $patientId);
        exit;
    }
    if ($patientId <= 0 || empty($testIds)) {
        $_SESSION['doctor_error'] = 'يرجى اختيار مريض وفحص واحد على الأقل.';
        header('Location: doctor.php?page=results&patient_id=' . $patientId);
        exit;
    }

    try {
        // تحقق ملكية المريض للمختبر الحالي
        try {
            $db->query('SELECT tenant_id FROM patients LIMIT 1');
            $stmt = $db->prepare('SELECT id FROM patients WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$patientId, $tenantId]);
            if (!$stmt->fetch()) {
                $_SESSION['doctor_error'] = 'المريض غير موجود ضمن مختبرك.';
                header('Location: doctor.php?page=results&patient_id=' . $patientId);
                exit;
            }
        } catch (Throwable $e) {
            $stmt = $db->prepare('SELECT id FROM patients WHERE id = ?');
            $stmt->execute([$patientId]);
            if (!$stmt->fetch()) {
                $_SESSION['doctor_error'] = 'المريض غير موجود.';
                header('Location: doctor.php?page=results&patient_id=' . $patientId);
                exit;
            }
        }

        $db->beginTransaction();

        $orderNumber = 'DO-' . date('ymd-His') . '-' . random_int(100, 999);
        $creatorUserId = null;
        try {
            $stmt = $db->prepare('SELECT created_by FROM doctor_accounts WHERE id = ?');
            $stmt->execute([$doctorAuth->accountId()]);
            $creatorUserId = (int)($stmt->fetchColumn() ?: 0);
        } catch (Throwable $e) {}
        if ($creatorUserId <= 0) {
            try {
                $stmt = $db->prepare('SELECT id FROM users WHERE tenant_id = ? ORDER BY id ASC LIMIT 1');
                $stmt->execute([$tenantId]);
                $creatorUserId = (int)($stmt->fetchColumn() ?: 0);
            } catch (Throwable $e) {}
        }
        if ($creatorUserId <= 0) {
            try {
                $creatorUserId = (int)$db->query('SELECT id FROM users ORDER BY id ASC LIMIT 1')->fetchColumn();
            } catch (Throwable $e) {
                $creatorUserId = 0;
            }
        }
        if ($creatorUserId <= 0) {
            throw new Exception('no_creator_user');
        }

        $branchId = null;
        $branchName = null;
        try {
            $stmt = $db->prepare('SELECT id, name FROM branches WHERE is_active = 1 AND tenant_id = ? ORDER BY id ASC LIMIT 1');
            $stmt->execute([$tenantId]);
            $branch = $stmt->fetch();
            if ($branch) {
                $branchId = (int)$branch['id'];
                $branchName = $branch['name'];
            }
        } catch (Throwable $e) {}

        $hasPriority = false;
        try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $hasPriority = true; } catch (Throwable $e) {}

        try {
            if ($hasPriority) {
                $stmt = $db->prepare('INSERT INTO lab_orders
                    (order_number, patient_id, doctor_id, order_date, status, priority, total_amount, discount_amount, net_amount, payment_status, branch_id, branch_name, created_by, tenant_id)
                    VALUES (:num, :pid, :doc, NOW(), :status, :priority, 0, 0, 0, :pay, :bid, :bname, :uid, :tid)');
                $stmt->execute([
                    'num' => $orderNumber,
                    'pid' => $patientId,
                    'doc' => $doctorId,
                    'status' => 'new',
                    'priority' => $priority,
                    'pay' => 'unpaid',
                    'bid' => $branchId,
                    'bname' => $branchName,
                    'uid' => $creatorUserId,
                    'tid' => $tenantId
                ]);
            } else {
                $stmt = $db->prepare('INSERT INTO lab_orders
                    (order_number, patient_id, doctor_id, order_date, status, total_amount, discount_amount, net_amount, payment_status, branch_id, branch_name, created_by, tenant_id)
                    VALUES (:num, :pid, :doc, NOW(), :status, 0, 0, 0, :pay, :bid, :bname, :uid, :tid)');
                $stmt->execute([
                    'num' => $orderNumber,
                    'pid' => $patientId,
                    'doc' => $doctorId,
                    'status' => 'new',
                    'pay' => 'unpaid',
                    'bid' => $branchId,
                    'bname' => $branchName,
                    'uid' => $creatorUserId,
                    'tid' => $tenantId
                ]);
            }
        } catch (Throwable $e) {
            // fallback لبنيات قديمة
            $stmt = $db->prepare('INSERT INTO lab_orders
                (order_number, patient_id, doctor_id, order_date, status, total_amount, discount_amount, net_amount, payment_status, branch_id, branch_name, created_by)
                VALUES (:num, :pid, :doc, NOW(), :status, 0, 0, 0, :pay, :bid, :bname, :uid)');
            $stmt->execute([
                'num' => $orderNumber,
                'pid' => $patientId,
                'doc' => $doctorId,
                'status' => 'new',
                'pay' => 'unpaid',
                'bid' => $branchId,
                'bname' => $branchName,
                'uid' => $creatorUserId
            ]);
        }

        $orderId = (int)$db->lastInsertId();

        $placeholders = implode(',', array_fill(0, count($testIds), '?'));
        $testTenantAnd = '';
        $testParams = $testIds;
        try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testTenantAnd = ' AND tenant_id = ?'; $testParams[] = $tenantId; } catch (Throwable $e) {}
        $stmt = $db->prepare("SELECT id, default_price FROM tests WHERE id IN ($placeholders)" . $testTenantAnd);
        $stmt->execute($testParams);
        $testRows = $stmt->fetchAll();
        if (count($testRows) !== count($testIds)) {
            throw new Exception('tests_not_allowed');
        }
        $prices = [];
        foreach ($testRows as $tr) $prices[(int)$tr['id']] = (float)($tr['default_price'] ?? 0);

        $sampleCode = 'SD-' . date('ymdHis') . '-' . random_int(100, 999);
        try {
            $db->query('SELECT barcode FROM samples LIMIT 1');
            $stmt = $db->prepare('INSERT INTO samples (sample_code, barcode, order_id, sample_type, collection_datetime, received_datetime, status)
                                  VALUES (?, ?, ?, ?, NOW(), NOW(), ?)');
            $stmt->execute([$sampleCode, $sampleCode, $orderId, $sampleType, 'received']);
        } catch (Throwable $e) {
            $stmt = $db->prepare('INSERT INTO samples (sample_code, order_id, sample_type, collection_datetime, received_datetime, status)
                                  VALUES (?, ?, ?, NOW(), NOW(), ?)');
            $stmt->execute([$sampleCode, $orderId, $sampleType, 'received']);
        }
        $sampleId = (int)$db->lastInsertId();

        $itemStmt = $db->prepare('INSERT INTO order_items (order_id, test_id, panel_id, sample_id, price, status)
                                  VALUES (:oid, :tid, NULL, :sid, :price, :status)');
        $total = 0.0;
        foreach ($testIds as $tid) {
            $price = (float)($prices[$tid] ?? 0);
            $total += $price;
            $itemStmt->execute([
                'oid' => $orderId,
                'tid' => $tid,
                'sid' => $sampleId,
                'price' => $price,
                'status' => 'pending'
            ]);
        }
        $db->prepare('UPDATE lab_orders SET total_amount = ?, net_amount = ? WHERE id = ?')->execute([$total, $total, $orderId]);

        $db->commit();
        $_SESSION['doctor_msg'] = 'تم إرسال طلب التحاليل إلى المختبر بنجاح.';
        header('Location: doctor.php?page=results&order_id=' . $orderId);
        exit;
    } catch (Throwable $e) {
        if ($db->inTransaction()) $db->rollBack();
        $_SESSION['doctor_error'] = ($e->getMessage() === 'tests_not_allowed')
            ? 'بعض الفحوصات غير متاحة لمختبرك.'
            : (($e->getMessage() === 'no_creator_user')
                ? 'لا يوجد مستخدم مختبر مرتبط لإنشاء الطلب. راجع مدير النظام.'
                : 'فشل إنشاء الطلب. حاول مرة أخرى.');
        header('Location: doctor.php?page=results&patient_id=' . $patientId);
        exit;
    }
}

// طباعة النتائج - صفحة منفصلة
if ($page === 'print') {
    include __DIR__ . '/modules/doctor/print.php';
    exit;
}

// الحسابات المالية - إضافة دفعة
if ($page === 'accounts' && ($_GET['action'] ?? '') === 'add_payment' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $accountId = (int)($_POST['account_id'] ?? 0);
    $amount = (float)(str_replace(',', '.', $_POST['amount'] ?? '0'));
    $paymentMethod = trim($_POST['payment_method'] ?? 'cash');
    $receiptNumber = trim($_POST['receipt_number'] ?? '');
    $notes = trim($_POST['notes'] ?? '');
    $invoiceId = (int)($_POST['invoice_id'] ?? 0);
    
    if ($accountId > 0 && $amount > 0) {
        try {
            $db->query('SELECT id FROM patient_accounts LIMIT 1');
            $db->query('SELECT id FROM account_transactions LIMIT 1');
            $db->query('SELECT id FROM account_payments LIMIT 1');
            
            $db->beginTransaction();
            
            // جلب الحساب
            $stmt = $db->prepare('SELECT * FROM patient_accounts WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$accountId, $tenantId]);
            $account = $stmt->fetch();
            
            if ($account) {
                $balanceBefore = (float)$account['account_balance'];
                $balanceAfter = $balanceBefore + $amount;
                
                // تحديث الرصيد
                $stmt = $db->prepare('UPDATE patient_accounts SET account_balance = ? WHERE id = ?');
                $stmt->execute([$balanceAfter, $accountId]);
                
                // إنشاء معاملة مالية
                $stmt = $db->prepare('INSERT INTO account_transactions 
                    (account_id, transaction_type, amount, balance_before, balance_after, description, payment_method, receipt_number, notes, created_by, doctor_account_id)
                    VALUES (?, "payment", ?, ?, ?, ?, ?, ?, ?, ?, ?)');
                $description = 'دفعة مالية' . ($invoiceId > 0 ? ' (فاتورة #' . $invoiceId . ')' : '');
                $stmt->execute([
                    $accountId, $amount, $balanceBefore, $balanceAfter, 
                    $description, $paymentMethod, $receiptNumber ?: null, $notes ?: null,
                    null, $doctorAuth->accountId()
                ]);
                $transactionId = (int)$db->lastInsertId();
                
                // إنشاء سجل الدفعة
                $stmt = $db->prepare('INSERT INTO account_payments 
                    (account_id, invoice_id, transaction_id, amount, payment_method, payment_date, receipt_number, notes, created_by, doctor_account_id)
                    VALUES (?, ?, ?, ?, ?, NOW(), ?, ?, ?, ?)');
                $stmt->execute([
                    $accountId, $invoiceId ?: null, $transactionId, $amount, $paymentMethod,
                    $receiptNumber ?: null, $notes ?: null, null, $doctorAuth->accountId()
                ]);
                
                // تحديث الفاتورة إن وجدت
                if ($invoiceId > 0) {
                    try {
                        $db->query('SELECT id FROM account_invoices LIMIT 1');
                        $stmt = $db->prepare('SELECT * FROM account_invoices WHERE id = ? AND account_id = ?');
                        $stmt->execute([$invoiceId, $accountId]);
                        $invoice = $stmt->fetch();
                        if ($invoice) {
                            $newPaid = (float)$invoice['paid_amount'] + $amount;
                            $remaining = (float)$invoice['total_amount'] - $newPaid;
                            $status = $remaining <= 0 ? 'paid' : ($newPaid > 0 ? 'partial' : 'pending');
                            
                            $stmt = $db->prepare('UPDATE account_invoices SET paid_amount = ?, remaining_amount = ?, status = ? WHERE id = ?');
                            $stmt->execute([$newPaid, $remaining, $status, $invoiceId]);
                        }
                    } catch (Throwable $e) {}
                }
                
                $db->commit();
                $_SESSION['doctor_account_msg'] = 'تم إضافة الدفعة بنجاح. الرصيد الجديد: ' . number_format($balanceAfter, 2) . ' د.ع';
            } else {
                $_SESSION['doctor_account_error'] = 'الحساب غير موجود';
            }
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $_SESSION['doctor_account_error'] = 'فشل إضافة الدفعة: ' . $e->getMessage();
        }
    }
    header('Location: doctor.php?page=accounts&account_id=' . $accountId);
    exit;
}

// الحسابات المالية - إضافة معاملة
if ($page === 'accounts' && ($_GET['action'] ?? '') === 'add_transaction' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $accountId = (int)($_POST['account_id'] ?? 0);
    $transactionType = $_POST['transaction_type'] ?? 'deposit';
    $amount = (float)(str_replace(',', '.', $_POST['amount'] ?? '0'));
    $description = trim($_POST['description'] ?? '');
    
    if ($accountId > 0 && $amount > 0 && in_array($transactionType, ['deposit', 'withdrawal', 'refund', 'adjustment', 'discount'])) {
        try {
            $db->query('SELECT id FROM patient_accounts LIMIT 1');
            $db->query('SELECT id FROM account_transactions LIMIT 1');
            
            $db->beginTransaction();
            
            $stmt = $db->prepare('SELECT * FROM patient_accounts WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$accountId, $tenantId]);
            $account = $stmt->fetch();
            
            if ($account) {
                $balanceBefore = (float)$account['account_balance'];
                $balanceAfter = $balanceBefore;
                
                if (in_array($transactionType, ['deposit', 'refund'])) {
                    $balanceAfter = $balanceBefore + $amount;
                } elseif (in_array($transactionType, ['withdrawal', 'adjustment', 'discount'])) {
                    $balanceAfter = $balanceBefore - $amount;
                }
                
                // تحديث الرصيد
                $stmt = $db->prepare('UPDATE patient_accounts SET account_balance = ? WHERE id = ?');
                $stmt->execute([$balanceAfter, $accountId]);
                
                // إنشاء المعاملة
                $stmt = $db->prepare('INSERT INTO account_transactions 
                    (account_id, transaction_type, amount, balance_before, balance_after, description, created_by, doctor_account_id)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([
                    $accountId, $transactionType, $amount, $balanceBefore, $balanceAfter,
                    $description ?: null, null, $doctorAuth->accountId()
                ]);
                
                $db->commit();
                $_SESSION['doctor_account_msg'] = 'تم إضافة المعاملة بنجاح. الرصيد الجديد: ' . number_format($balanceAfter, 2) . ' د.ع';
            }
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $_SESSION['doctor_account_error'] = 'فشل إضافة المعاملة: ' . $e->getMessage();
        }
    }
    header('Location: doctor.php?page=accounts&account_id=' . $accountId);
    exit;
}

// الحسابات المالية - تسوية الرصيد
if ($page === 'accounts' && ($_GET['action'] ?? '') === 'adjust_balance' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $accountId = (int)($_POST['account_id'] ?? 0);
    $newBalance = (float)(str_replace(',', '.', $_POST['new_balance'] ?? '0'));
    $description = trim($_POST['description'] ?? '');
    
    if ($accountId > 0 && $description !== '') {
        try {
            $db->query('SELECT id FROM patient_accounts LIMIT 1');
            $db->query('SELECT id FROM account_transactions LIMIT 1');
            
            $db->beginTransaction();
            
            $stmt = $db->prepare('SELECT * FROM patient_accounts WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$accountId, $tenantId]);
            $account = $stmt->fetch();
            
            if ($account) {
                $balanceBefore = (float)$account['account_balance'];
                $difference = $newBalance - $balanceBefore;
                
                // تحديث الرصيد
                $stmt = $db->prepare('UPDATE patient_accounts SET account_balance = ? WHERE id = ?');
                $stmt->execute([$newBalance, $accountId]);
                
                // إنشاء معاملة تسوية
                $stmt = $db->prepare('INSERT INTO account_transactions 
                    (account_id, transaction_type, amount, balance_before, balance_after, description, created_by, doctor_account_id)
                    VALUES (?, "adjustment", ?, ?, ?, ?, ?, ?)');
                $stmt->execute([
                    $accountId, abs($difference), $balanceBefore, $newBalance,
                    'تسوية الرصيد: ' . $description, null, $doctorAuth->accountId()
                ]);
                
                $db->commit();
                $_SESSION['doctor_account_msg'] = 'تم تسوية الرصيد بنجاح. الرصيد الجديد: ' . number_format($newBalance, 2) . ' د.ع';
            }
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $_SESSION['doctor_account_error'] = 'فشل تسوية الرصيد: ' . $e->getMessage();
        }
    }
    header('Location: doctor.php?page=accounts&account_id=' . $accountId);
    exit;
}

// الحسابات المالية - إنشاء كشفية جديدة
if ($page === 'accounts' && ($_GET['action'] ?? '') === 'create_account' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $patientId = (int)($_POST['patient_id'] ?? 0);
    $initialBalance = (float)(str_replace(',', '.', $_POST['initial_balance'] ?? '0'));
    $notes = trim($_POST['notes'] ?? '');
    
    if ($patientId > 0) {
        try {
            $db->query('SELECT id FROM patient_accounts LIMIT 1');
            
            // التحقق من وجود حساب مسبق
            $stmt = $db->prepare('SELECT id FROM patient_accounts WHERE patient_id = ? AND tenant_id = ?');
            $stmt->execute([$patientId, $tenantId]);
            if ($stmt->fetch()) {
                $_SESSION['doctor_account_error'] = 'هذا المريض لديه حساب مالي بالفعل';
            } else {
                // التحقق من أن المريض موجود ومرتبط بالطبيب
                $tenantPat = '';
                try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $tenantPat = ' AND p.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
                $stmt = $db->prepare("SELECT p.id FROM patients p WHERE p.id = ? $tenantPat 
                    AND EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id $tenantCond $doctorCond)");
                $stmt->execute([$patientId]);
                $patient = $stmt->fetch();
                
                if ($patient) {
                    $db->beginTransaction();
                    
                    // إنشاء الحساب
                    $stmt = $db->prepare('INSERT INTO patient_accounts 
                        (patient_id, tenant_id, account_balance, currency, notes, created_by) 
                        VALUES (?, ?, ?, "IQD", ?, ?)');
                    $stmt->execute([$patientId, $tenantId, $initialBalance, $notes ?: null, $doctorAuth->accountId()]);
                    $accountId = (int)$db->lastInsertId();
                    
                    // إنشاء معاملة أولية إذا كان الرصيد غير صفر
                    if ($initialBalance != 0) {
                        try {
                            $db->query('SELECT id FROM account_transactions LIMIT 1');
                            $stmt = $db->prepare('INSERT INTO account_transactions 
                                (account_id, transaction_type, amount, balance_before, balance_after, description, created_by, doctor_account_id)
                                VALUES (?, ?, ?, 0, ?, ?, ?, ?)');
                            $transactionType = $initialBalance > 0 ? 'deposit' : 'adjustment';
                            $description = 'رصيد ابتدائي' . ($notes ? ': ' . $notes : '');
                            $stmt->execute([
                                $accountId, $transactionType, abs($initialBalance), $initialBalance,
                                $description, null, $doctorAuth->accountId()
                            ]);
                        } catch (Throwable $e) {}
                    }
                    
                    $db->commit();
                    $_SESSION['doctor_account_msg'] = 'تم إنشاء الكشفية بنجاح! الرصيد الابتدائي: ' . number_format($initialBalance, 2) . ' د.ع';
                    header('Location: doctor.php?page=accounts&account_id=' . $accountId);
                    exit;
                } else {
                    $_SESSION['doctor_account_error'] = 'المريض غير موجود أو غير مرتبط بك';
                }
            }
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $_SESSION['doctor_account_error'] = 'فشل إنشاء الكشفية: ' . $e->getMessage();
        }
    } else {
        $_SESSION['doctor_account_error'] = 'يرجى اختيار مريض';
    }
    header('Location: doctor.php?page=accounts');
    exit;
}

$moduleFile = __DIR__ . '/modules/doctor/' . $page . '.php';
if (file_exists($moduleFile)) {
    include $moduleFile;
} else {
    include __DIR__ . '/modules/doctor/dashboard.php';
}
