<?php
/**
 * Smart Doctor - بوابة الأطباء
 * واجهة منفصلة لتسجيل دخول الأطباء وعرض مرضاهم ونتائج التحاليل والإحصائيات
 */
ob_start();

$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';

$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;
    }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        if ($doctorAuth->attempt($username, $password)) {
            header('Location: doctor.php?page=dashboard');
            exit;
        }
        $loginError = 'اسم المستخدم أو كلمة المرور غير صحيحة';
    }
    ?>
    <!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 (isset($loginError)): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($loginError, ENT_QUOTES, 'UTF-8'); ?></div>
            <?php endif; ?>
            <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>
            <p style="text-align:center;margin-top:20px;font-size:0.9rem;">
                <a href="index.php" style="color:#14b8a6;">← العودة لنظام المختبر</a>
            </p>
        </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) {} }
}

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

// تحميل الوحدة المطلوبة
$doctorPages = ['dashboard', 'patients', 'results', 'statistics', 'profile', 'search', 'trend', 'print', 'reminders', 'appointments', 'alerts', 'tasks', 'templates', 'share', 'accounts'];
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;
}

// تغيير كلمة المرور - من الملف الشخصي
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_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';
}
