<?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/DoctorAuth.php';
require_once __DIR__ . '/src/Core/Tenant.php';
require_once __DIR__ . '/src/Core/TOTP.php';

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

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$doctorAuth = new \App\Core\DoctorAuth($db);

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

// تسجيل الدخول
if ($page === 'login') {
    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') {
        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) {
                header('Location: doctor.php?page=dashboard');
                exit;
            }
            if ($attempt === '2fa_required') {
                header('Location: doctor.php?page=login&step=2fa');
                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'] ?? null;
    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">
                <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">
                <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') {
    $doctorAuth->logout();
    header('Location: doctor.php?page=login');
    exit;
}

// التحقق من الدخول لجميع الصفحات الأخرى
if (!$doctorAuth->check()) {
    header('Location: doctor.php?page=login');
    exit;
}

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

try { $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/023_doctor_reminders_favorites.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT id FROM doctor_search_history LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/024_doctor_enhancements.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT id FROM doctor_appointments LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/025_doctor_appointments.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT booking_token FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/026_doctor_booking_link.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT photo FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/027_doctor_profile_photo.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT two_factor_enabled FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/028_doctor_2fa.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT phone FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/031_doctor_phone_whatsapp.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT id FROM patient_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/029_patient_accounts.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT whatsapp_notify_appointments FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/030_doctor_whatsapp_appointments.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT id FROM doctor_alerts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/032_doctor_alerts.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try {
    $db->query('SELECT id FROM doctor_alerts LIMIT 1');
    $f = __DIR__ . '/migrations/run_036_doctor_alerts_columns.php';
    if (file_exists($f)) require $f;
} catch (Throwable $e) {}
try { $db->query('SELECT id FROM patient_appointment_reminders LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/033_patient_appointment_reminders.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT id FROM whatsapp_send_queue LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/034_doctor_whatsapp_queue.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT whatsapp_instance_id FROM doctor_accounts LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/034a_doctor_whatsapp_columns.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}
try { $db->query('SELECT reminder_entity_type FROM whatsapp_send_queue LIMIT 1'); } catch (Throwable $e) {
    $f = __DIR__ . '/migrations/035_whatsapp_queue_reminder_fields.sql';
    if (file_exists($f)) foreach (array_filter(array_map('trim', explode(';', file_get_contents($f)))) as $s) { if (!empty($s) && strpos($s, '--') !== 0) try { $db->exec($s); } catch (Throwable $x) {} }
}

$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') {
    $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' && isset($_GET['action']) && isset($_GET['id'])) {
    $rid = (int)$_GET['id'];
    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) {
                if (($_GET['action'] ?? '') === 'done') {
                    $db->prepare('UPDATE doctor_follow_up_reminders SET is_done = 1 WHERE id = ?')->execute([$rid]);
                    $_SESSION['doctor_msg'] = 'تم تنفيذ التذكير.';
                } elseif (($_GET['action'] ?? '') === 'delete') {
                    $db->prepare('DELETE FROM doctor_follow_up_reminders WHERE id = ?')->execute([$rid]);
                    $_SESSION['doctor_msg'] = 'تم حذف التذكير.';
                } elseif (($_GET['action'] ?? '') === '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') {
    $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');
            $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, $atime . ':00', $duration, $note ?: null]);
            $_SESSION['doctor_msg'] = 'تم حجز الموعد.';
        } catch (Throwable $e) {}
        header('Location: doctor.php?page=appointments&date=' . urlencode($adate));
        exit;
    }
}
// المواعيد - تأكيد/تم/إلغاء/لم يحضر/تعديل/نسخ
if ($page === 'appointments' && isset($_GET['action']) && isset($_GET['id'])) {
    $aid = (int)$_GET['id'];
    $aptDate = trim($_GET['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 = $_GET['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($_GET['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') {
    $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 !== '') {
        $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' && ($_GET['action'] ?? '') === 'favorite' && isset($_GET['patient_id'])) {
    $fpid = (int)$_GET['patient_id'];
    $add = ($_GET['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($_GET['q'] ?? '')) !== '' ? '&q=' . urlencode($q) : ''));
        exit;
    }
}

// إنشاء رابط مشاركة النتائج
if ($page === 'results' && ($_GET['action'] ?? '') === 'share' && isset($_GET['order_id'])) {
    $shareOrderId = (int)$_GET['order_id'];
    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') {
    $current = $_POST['current_password'] ?? '';
    $newPass = trim($_POST['new_password'] ?? '');
    $confirm = trim($_POST['confirm_password'] ?? '');
    if (strlen($newPass) < 6) {
        $_SESSION['doctor_profile_error'] = 'كلمة المرور الجديدة 6 أحرف على الأقل.';
    } 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 === 'results' && ($_GET['action'] ?? '') === 'delete_note' && isset($_GET['id']) && isset($_GET['patient_id'])) {
    $noteId = (int)$_GET['id'];
    $pid = (int)$_GET['patient_id'];
    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') {
    $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') {
    $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' && ($_GET['action'] ?? '') === 'delete_diagnosis' && isset($_GET['id']) && isset($_GET['patient_id'])) {
    $did = (int)$_GET['id'];
    $pid = (int)$_GET['patient_id'];
    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') {
    $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 === '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';
}
