<?php

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\Tenant;

$action = $_GET['action'] ?? 'index';
$tenantId = Tenant::id();

if (!($auth instanceof Auth) || !$auth->can('patients.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى هذه الصفحة';
    return;
}

if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    if (!($auth instanceof Auth) || !$auth->can('patients.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة المرضى';
        return;
    }
    $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'] ?? '');

    if ($fullName !== '') {
        $code = 'P' . time();

        if ($dob === '') {
            $dob = null;
        }

        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
            ]);
        } 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
                ]);
            } catch (Throwable $e2) {
                $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
                ]);
            }
        }
        if (isset($auditLog)) {
            $auditLog->log(
                'patient_created',
                'patient',
                (int)$db->lastInsertId(),
                null,
                json_encode([
                    'patient_code' => $code,
                    'full_name' => $fullName,
                    'gender' => $gender,
                    'phone' => $phone
                ], JSON_UNESCAPED_UNICODE),
                $_SESSION['user_id'] ?? null
            );
        }
    }

    header('Location: index.php?page=patients');
    exit;
}

if ($action === 'delete' && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    Csrf::enforce($_POST['_csrf'] ?? null);
    if (!($auth instanceof Auth) || !$auth->can('patients.delete')) {
        http_response_code(403);
        echo 'غير مسموح بحذف المرضى';
        return;
    }
    $delId = (int)$_POST['id'];
    if ($delId > 0) {
        $stmt = $db->prepare('SELECT id FROM patients WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$delId, $tenantId]);
        $patient = $stmt->fetch();
        if ($patient) {
            $orderCount = 0;
            try {
                $stmt = $db->prepare('SELECT COUNT(*) FROM lab_orders WHERE patient_id = ?');
                $stmt->execute([$delId]);
                $orderCount = (int)$stmt->fetchColumn();
            } catch (Throwable $e) {}
            if ($orderCount > 0) {
                header('Location: index.php?page=patients&err=has_orders&id=' . $delId);
                exit;
            }
            try {
                $db->query('SELECT patient_id FROM patient_attachments LIMIT 1');
                $db->prepare('DELETE FROM patient_attachments WHERE patient_id = ?')->execute([$delId]);
            } catch (Throwable $e) {}
            try {
                $db->query('SELECT patient_id FROM service_ratings LIMIT 1');
                $db->prepare('DELETE FROM service_ratings WHERE patient_id = ?')->execute([$delId]);
            } catch (Throwable $e) {}
            try {
                $db->query('SELECT patient_id FROM loyalty_transactions LIMIT 1');
                $db->prepare('DELETE FROM loyalty_transactions WHERE patient_id = ?')->execute([$delId]);
            } catch (Throwable $e) {}
            $db->prepare('DELETE FROM patients WHERE id = ? AND tenant_id = ?')->execute([$delId, $tenantId]);
            if (isset($auditLog)) {
                $auditLog->log('patient_deleted', 'patient', $delId, json_encode(['id' => $delId], JSON_UNESCAPED_UNICODE), null, $_SESSION['user_id'] ?? null);
            }
        }
    }
    header('Location: index.php?page=patients');
    exit;
}

if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $editId = (int)($_POST['id'] ?? 0);
    if ($editId > 0) {
        $stmt = $db->prepare('SELECT * FROM patients WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$editId, $tenantId]);
        $editPatient = $stmt->fetch();
        if (!$editPatient) {
            header('Location: index.php?page=patients');
            exit;
        }
        $fullName = trim($_POST['full_name'] ?? '');
        $gender = $_POST['gender'] ?? null;
        $dob = $_POST['date_of_birth'] ?? '';
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $nationalId = trim($_POST['national_id'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $portalCode = trim($_POST['portal_code'] ?? '');
        $defaultDoctorId = (int)($_POST['default_doctor_id'] ?? 0);

        if ($fullName !== '') {
            try {
                $oldData = json_encode(['full_name' => $editPatient['full_name'], 'phone' => $editPatient['phone'] ?? ''], JSON_UNESCAPED_UNICODE);
                try {
                    $db->query('SELECT email FROM patients LIMIT 1');
                    $stmt = $db->prepare('UPDATE patients SET full_name=?, gender=?, date_of_birth=?, phone=?, email=?, national_id=?, address=? WHERE id = ?');
                    $stmt->execute([$fullName, $gender ?: null, $dob ?: null, $phone ?: null, $email ?: null, $nationalId ?: null, $address ?: null, $editId]);
                } catch (Throwable $ex) {
                    $stmt = $db->prepare('UPDATE patients SET full_name=?, gender=?, date_of_birth=?, phone=?, national_id=?, address=? WHERE id = ?');
                    $stmt->execute([$fullName, $gender ?: null, $dob ?: null, $phone ?: null, $nationalId ?: null, $address ?: null, $editId]);
                }
                try { $db->query('SELECT default_doctor_id FROM patients LIMIT 1'); $db->prepare('UPDATE patients SET portal_code=?, default_doctor_id=? WHERE id = ?')->execute([$portalCode ?: null, $defaultDoctorId > 0 ? $defaultDoctorId : null, $editId]); } catch (Throwable $e) {}
                if (isset($auditLog)) {
                    $auditLog->log('patient_updated', 'patient', $editId, $oldData, json_encode(['full_name' => $fullName, 'phone' => $phone], JSON_UNESCAPED_UNICODE), $_SESSION['user_id'] ?? null);
                }
                header('Location: index.php?page=patients&action=view&id=' . $editId);
                exit;
            } catch (Throwable $e) {}
        }
    }
}

if ($action === 'edit') {
    $editId = (int)($_GET['id'] ?? 0);
    if ($editId > 0) {
        $stmt = $db->prepare('SELECT * FROM patients WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$editId, $tenantId]);
        $editPatient = $stmt->fetch();
        $doctors = [];
        try {
            $db->query('SELECT tenant_id FROM doctors LIMIT 1');
            $stmt = $db->prepare('SELECT id, full_name FROM doctors WHERE tenant_id = ? ORDER BY full_name');
            $stmt->execute([$tenantId]);
            $doctors = $stmt->fetchAll();
        } catch (Throwable $e) {
            try { $doctors = $db->query('SELECT id, full_name FROM doctors ORDER BY full_name')->fetchAll(); } catch (Throwable $e2) {}
        }
        if ($editPatient) {
            $pc = $editPatient['portal_code'] ?? '';
            if (empty($pc) && isset($editPatient['id'])) {
                $pc = strtoupper(substr(md5($editPatient['patient_code'] . $editPatient['id']), 0, 6));
            }
            ?>
            <div class="page-header"><h1>تعديل بيانات المريض</h1><a href="index.php?page=patients&action=view&id=<?php echo (int)$editId; ?>" class="btn-secondary">← رجوع للملف</a></div>
            <div class="section-card patients-form-card">
            <form method="post" class="form-grid">
                <input type="hidden" name="id" value="<?php echo (int)$editId; ?>">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <div><label>الاسم الكامل <span class="required">*</span></label><input type="text" name="full_name" required value="<?php echo htmlspecialchars($editPatient['full_name'], ENT_QUOTES, 'UTF-8'); ?>"></div>
                <div><label>الجنس</label><select name="gender"><option value="">غير محدد</option><option value="M" <?php echo ($editPatient['gender'] ?? '') === 'M' ? 'selected' : ''; ?>>ذكر</option><option value="F" <?php echo ($editPatient['gender'] ?? '') === 'F' ? 'selected' : ''; ?>>أنثى</option></select></div>
                <div><label>تاريخ الميلاد</label><input type="date" name="date_of_birth" value="<?php echo htmlspecialchars($editPatient['date_of_birth'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"></div>
                <div><label>الهاتف</label><input type="tel" name="phone" value="<?php echo htmlspecialchars($editPatient['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"></div>
                <?php try { $db->query('SELECT email FROM patients LIMIT 1'); ?><div><label>البريد الإلكتروني</label><input type="email" name="email" value="<?php echo htmlspecialchars($editPatient['email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"></div><?php } catch (Throwable $e) {} ?>
                <div><label>الرقم الوطني</label><input type="text" name="national_id" value="<?php echo htmlspecialchars($editPatient['national_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"></div>
                <div class="full-width"><label>العنوان</label><input type="text" name="address" value="<?php echo htmlspecialchars($editPatient['address'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"></div>
                <?php try { $db->query('SELECT default_doctor_id FROM patients LIMIT 1'); ?>
                <div><label>الطبيب المعتاد</label><select name="default_doctor_id"><option value="">-- اختر --</option><?php foreach ($doctors as $d): ?><option value="<?php echo (int)$d['id']; ?>" <?php echo (($editPatient['default_doctor_id'] ?? 0) == $d['id'] ? 'selected' : ''); ?>><?php echo htmlspecialchars($d['full_name'], ENT_QUOTES, 'UTF-8'); ?></option><?php endforeach; ?></select></div>
                <div><label>رمز البوابة</label><input type="text" name="portal_code" value="<?php echo htmlspecialchars($pc, ENT_QUOTES, 'UTF-8'); ?>" placeholder="لدخول المريض لعرض النتائج"></div>
                <?php } catch (Throwable $e) {} ?>
                <div class="full-width form-actions"><button type="submit" class="btn-primary">حفظ التعديلات</button><a href="index.php?page=patients&action=view&id=<?php echo (int)$editId; ?>" class="btn-secondary">إلغاء</a></div>
            </form>
            </div>
            <?php
            return;
        }
    }
}

if ($action === 'create') {
    ?>
    <div class="page-header">
        <h1>إضافة مريض جديد</h1>
        <a href="index.php?page=patients" class="btn-secondary">← رجوع</a>
    </div>
    <div class="section-card patients-form-card">
        <form method="post" class="form-grid">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
            <div><label>الاسم الكامل <span class="required">*</span></label><input type="text" name="full_name" required placeholder="الاسم ثلاثي"></div>
            <div><label>الجنس</label><select name="gender"><option value="">غير محدد</option><option value="M">ذكر</option><option value="F">أنثى</option></select></div>
            <div><label>تاريخ الميلاد</label><input type="date" name="date_of_birth"></div>
            <div><label>رقم الهاتف</label><input type="tel" name="phone" placeholder="07XX XXX XXXX"></div>
            <?php try { $db->query('SELECT email FROM patients LIMIT 1'); ?><div><label>البريد الإلكتروني</label><input type="email" name="email" placeholder="example@email.com"></div><?php } catch (Throwable $e) {} ?>
            <div><label>الرقم الوطني</label><input type="text" name="national_id" placeholder="رقم الهوية"></div>
            <div class="full-width"><label>العنوان</label><input type="text" name="address" placeholder="المحافظة، المدينة، الحي"></div>
            <div class="full-width form-actions"><button type="submit" class="btn-primary">حفظ المريض</button><a href="index.php?page=patients" class="btn-secondary">إلغاء</a></div>
        </form>
    </div>
    <?php
    return;
}

if ($action === 'upload' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::enforce($_POST['_csrf'] ?? null);
    $uploadId = (int)($_GET['id'] ?? 0);
    if ($uploadId > 0 && isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        try {
            $db->query('SELECT id FROM patient_attachments LIMIT 1');
        } catch (Throwable $e) {
            header('Location: index.php?page=patients&action=view&id=' . $uploadId);
            exit;
        }
        $dir = __DIR__ . '/../uploads/patient_' . $uploadId;
        if (!is_dir($dir)) mkdir($dir, 0755, true);
        $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, ['pdf','jpg','jpeg','png'])) {
            header('Location: index.php?page=patients&action=view&id=' . $uploadId . '&err=type');
            exit;
        }
        $fname = date('Ymd_His') . '_' . preg_replace('/[^a-z0-9_\-\.]/i', '', $_FILES['file']['name']);
        $path = $dir . '/' . $fname;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
            $stmt = $db->prepare('INSERT INTO patient_attachments (patient_id, file_name, file_path, file_type, uploaded_by) VALUES (?, ?, ?, ?, ?)');
            $stmt->execute([$uploadId, $_FILES['file']['name'], 'uploads/patient_' . $uploadId . '/' . $fname, $_FILES['file']['type'], $_SESSION['user_id'] ?? null]);
        }
        header('Location: index.php?page=patients&action=view&id=' . $uploadId);
        exit;
    }
}

$viewId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($viewId > 0 && ($action === 'view' || $action === 'profile')) {
    $patient = null;
    $visits = [];
    $attachments = [];
    try {
        $stmt = $db->prepare('SELECT * FROM patients WHERE id = ? AND tenant_id = ?');
        $stmt->execute([$viewId, $tenantId]);
        $patient = $stmt->fetch();
        if ($patient) {
            $patient['doctor_name'] = null;
            try {
                $stmt = $db->prepare('SELECT d.full_name FROM doctors d JOIN patients p ON p.default_doctor_id = d.id WHERE p.id = ?');
                $stmt->execute([$viewId]);
                $dr = $stmt->fetch();
                if ($dr) $patient['doctor_name'] = $dr['full_name'];
            } catch (Throwable $e) {}
        }
        if ($patient) {
            $visitsSql = 'SELECT o.id, o.order_number, o.order_date, o.status, o.net_amount, o.payment_status,
                        d.full_name AS doctor_name, b.name AS branch_name
                 FROM lab_orders o
                 LEFT JOIN doctors d ON d.id = o.doctor_id
                 LEFT JOIN branches b ON b.id = o.branch_id
                 WHERE o.patient_id = ?';
            try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $visitsSql .= ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
            $visitsSql .= ' ORDER BY o.order_date DESC LIMIT 50';
            $stmt = $db->prepare($visitsSql);
            $stmt->execute([$viewId]);
            $visits = $stmt->fetchAll();
            try {
                $stmt = $db->prepare('SELECT id, file_name, file_path, created_at FROM patient_attachments WHERE patient_id = ? ORDER BY id DESC');
                $stmt->execute([$viewId]);
                $attachments = $stmt->fetchAll();
            } catch (Throwable $e) {}
        }
    } catch (Throwable $e) {}
    if ($patient) {
        $qrData = 'PATIENT:' . $patient['patient_code'] . (isset($patient['portal_code']) && $patient['portal_code'] ? ':' . $patient['portal_code'] : '');
        $portalBase = '';
        if (!empty($_SERVER['HTTP_HOST'])) {
            $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
            $portalBase = $scheme . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? ''), '/\\');
            try {
                $tId = (int)($_SESSION['tenant_id'] ?? 1);
                $st = $db->prepare('SELECT slug FROM tenants WHERE id = ? LIMIT 1');
                $st->execute([$tId]);
                $tRow = $st->fetch();
                if ($tRow && ($tRow['slug'] ?? '') !== 'main') {
                    $portalBase .= '/index.php?page=patient_portal&qr=' . urlencode($qrData) . '&tenant=' . urlencode($tRow['slug']);
                } else {
                    $portalBase .= '/index.php?page=patient_portal&qr=' . urlencode($qrData);
                }
            } catch (Throwable $e) {}
        }
        if ($portalBase === '') $portalBase = $qrData;
        $qrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=' . urlencode($portalBase);
        ?>
        <div class="page-header">
            <h1>ملف المريض</h1>
            <div style="display:flex;gap:10px;flex-wrap:wrap;">
                <?php if (isset($auth) && $auth->can('orders.create')): ?><a href="index.php?page=orders&action=create&patient_id=<?php echo (int)$viewId; ?>" class="btn-primary">طلب جديد</a><?php endif; ?>
                <?php if (isset($auth) && $auth->can('patients.create')): ?><a href="index.php?page=patients&action=edit&id=<?php echo (int)$viewId; ?>" class="btn-secondary">تعديل</a><?php endif; ?>
                <?php if (isset($auth) && $auth->can('patients.delete')): ?>
                <form method="post" action="index.php?page=patients&action=delete" style="display:inline;" onsubmit="return confirm('هل أنت متأكد من حذف بيانات المريض؟');">
                    <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="id" value="<?php echo (int)$viewId; ?>">
                    <button type="submit" class="btn-action btn-action--delete">حذف</button>
                </form>
                <?php endif; ?>
                <a href="index.php?page=patients" class="btn-secondary">← رجوع</a>
            </div>
        </div>
        <div class="section-card patient-profile-card">
            <div class="patient-profile-header">
                <div class="patient-profile-qr">
                    <img src="<?php echo htmlspecialchars($qrUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="QR" width="120" height="120">
                    <p>كود QR للمريض</p>
                    <?php if ($portalBase !== '' && strpos($portalBase, 'http') === 0): ?><small style="color:var(--text-muted);">امسح لدخول البوابة مباشرة</small><?php endif; ?>
                </div>
                <div class="patient-profile-info">
                    <h2 class="patient-profile-name"><?php echo htmlspecialchars($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?></h2>
                    <p class="patient-profile-code"><code><?php echo htmlspecialchars($patient['patient_code'], ENT_QUOTES, 'UTF-8'); ?></code></p>
                    <dl class="patient-profile-dl">
                        <dt>الجنس</dt><dd><?php echo $patient['gender'] === 'M' ? 'ذكر' : ($patient['gender'] === 'F' ? 'أنثى' : '—'); ?></dd>
                        <dt>تاريخ الميلاد</dt><dd><?php echo htmlspecialchars($patient['date_of_birth'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></dd>
                        <dt>الهاتف</dt><dd><?php echo htmlspecialchars($patient['phone'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></dd>
                        <?php if (!empty($patient['email'])): ?><dt>البريد</dt><dd><?php echo htmlspecialchars($patient['email'], ENT_QUOTES, 'UTF-8'); ?></dd><?php endif; ?>
                        <dt>العنوان</dt><dd><?php echo htmlspecialchars($patient['address'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></dd>
                        <dt>الطبيب المعتاد</dt><dd><?php echo htmlspecialchars($patient['doctor_name'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></dd>
                        <?php if (!empty($patient['portal_code'])): ?><dt>رمز البوابة</dt><dd><code><?php echo htmlspecialchars($patient['portal_code'], ENT_QUOTES, 'UTF-8'); ?></code></dd><?php endif; ?>
                    </dl>
                </div>
            </div>
        </div>
        <?php
        $trendTests = [];
        $trendData = [];
        try {
            $stmt = $db->prepare(
                'SELECT DISTINCT t.id, t.name, t.unit, t.reference_range FROM tests t
                 JOIN order_items oi ON oi.test_id = t.id
                 JOIN lab_orders o ON o.id = oi.order_id
                 JOIN results r ON r.order_item_id = oi.id
                 WHERE o.patient_id = ? AND r.result_value IS NOT NULL AND r.result_value != "" AND r.result_value REGEXP "^[0-9]+\.?[0-9]*$"
                 ORDER BY t.name LIMIT 30'
            );
            $stmt->execute([$viewId]);
            $trendTests = $stmt->fetchAll();
        } catch (Throwable $e) {}
        $selectedTestId = (int)($_GET['trend_test'] ?? 0);
        if ($selectedTestId > 0 && in_array($selectedTestId, array_column($trendTests, 'id'), true)) {
            $stmt = $db->prepare(
                'SELECT o.order_date, r.result_value, t.unit, t.reference_range FROM results r
                 JOIN order_items oi ON oi.id = r.order_item_id
                 JOIN lab_orders o ON o.id = oi.order_id
                 JOIN tests t ON t.id = oi.test_id
                 WHERE o.patient_id = ? AND oi.test_id = ? AND r.result_value IS NOT NULL AND r.result_value != ""
                 ORDER BY o.order_date ASC'
            );
            $stmt->execute([$viewId, $selectedTestId]);
            $trendData = $stmt->fetchAll();
        }
        if (count($trendTests) > 0): ?>
        <div class="section-card" style="margin-top:20px;">
            <h3>📈 تطور النتائج عبر الزمن</h3>
            <form method="get" style="margin-bottom:16px;">
                <input type="hidden" name="page" value="patients">
                <input type="hidden" name="action" value="view">
                <input type="hidden" name="id" value="<?php echo (int)$viewId; ?>">
                <label>اختر فحص:</label>
                <select name="trend_test" onchange="this.form.submit()">
                    <option value="">— اختر فحص —</option>
                    <?php foreach ($trendTests as $tt): ?>
                    <option value="<?php echo (int)$tt['id']; ?>" <?php echo $selectedTestId === (int)$tt['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($tt['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                </select>
            </form>
            <?php if (count($trendData) > 0): ?>
            <?php
            $chartLabels = array_map(fn($r) => $r['order_date'], $trendData);
            $chartValues = array_map(function($r) {
                $v = $r['result_value'];
                return is_numeric($v) ? (float)$v : null;
            }, $trendData);
            $refRange = $trendData[0]['reference_range'] ?? '';
            $trendTestName = 'النتيجة';
            foreach ($trendTests as $tt) { if ((int)$tt['id'] === $selectedTestId) { $trendTestName = $tt['name']; break; } }
            ?>
            <div style="position:relative;height:220px;">
                <canvas id="trendChart" style="max-height:220px;"></canvas>
            </div>
            <p style="font-size:0.85rem;color:var(--text-muted);margin-top:8px;">المدى المرجعي: <?php echo htmlspecialchars($refRange ?: '—', ENT_QUOTES, 'UTF-8'); ?> — الوحدة: <?php echo htmlspecialchars($trendData[0]['unit'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></p>
            <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>
            <script>
            (function(){
                var ctx = document.getElementById('trendChart');
                if (ctx && typeof Chart !== 'undefined') {
                    new Chart(ctx.getContext('2d'), {
                        type: 'line',
                        data: {
                            labels: <?php echo json_encode($chartLabels); ?>,
                            datasets: [{
                                label: <?php echo json_encode($trendTestName); ?>,
                                data: <?php echo json_encode($chartValues); ?>,
                                borderColor: '#0d9488',
                                backgroundColor: 'rgba(13,148,136,0.1)',
                                fill: true,
                                tension: 0.2
                            }]
                        },
                        options: {
                            responsive: true,
                            maintainAspectRatio: false,
                            scales: { y: { beginAtZero: false } },
                            plugins: { legend: { display: false } }
                        }
                    });
                }
            })();
            </script>
            <?php else: ?>
            <p>لا توجد نتائج رقمية لهذا الفحص بعد.</p>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        <div class="section-card" style="margin-top:20px;">
            <h3>سجل الزيارات (<?php echo count($visits); ?> طلب)</h3>
            <?php if (count($visits) >= 2): ?>
            <form method="get" style="margin-bottom:16px;display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
                <input type="hidden" name="page" value="patients">
                <input type="hidden" name="action" value="view">
                <input type="hidden" name="id" value="<?php echo (int)$viewId; ?>">
                <label>مقارنة زيارتين:</label>
                <select name="compare_a">
                    <option value="">— زيارة 1 —</option>
                    <?php foreach ($visits as $v): ?>
                    <option value="<?php echo (int)$v['id']; ?>" <?php echo (int)($_GET['compare_a'] ?? 0) === (int)$v['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($v['order_number'] . ' ' . $v['order_date'], ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="compare_b">
                    <option value="">— زيارة 2 —</option>
                    <?php foreach ($visits as $v): ?>
                    <option value="<?php echo (int)$v['id']; ?>" <?php echo (int)($_GET['compare_b'] ?? 0) === (int)$v['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($v['order_number'] . ' ' . $v['order_date'], ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="btn-secondary">عرض المقارنة</button>
            </form>
            <?php
            $compareA = (int)($_GET['compare_a'] ?? 0);
            $compareB = (int)($_GET['compare_b'] ?? 0);
            if ($compareA > 0 && $compareB > 0 && $compareA !== $compareB):
                $stmt = $db->prepare('SELECT t.name, r.result_value, r.flag, t.unit, t.reference_range FROM order_items oi JOIN tests t ON t.id = oi.test_id LEFT JOIN results r ON r.order_item_id = oi.id WHERE oi.order_id = ? ORDER BY t.name');
                $stmt->execute([$compareA]); $resA = $stmt->fetchAll();
                $stmt->execute([$compareB]); $resB = $stmt->fetchAll();
                $ordA = null; $ordB = null;
                foreach ($visits as $v) { if ((int)$v['id'] === $compareA) $ordA = $v; if ((int)$v['id'] === $compareB) $ordB = $v; }
                $mapA = []; foreach ($resA as $r) $mapA[$r['name']] = $r;
                $mapB = []; foreach ($resB as $r) $mapB[$r['name']] = $r;
                $allTests = array_unique(array_merge(array_keys($mapA), array_keys($mapB)));
                sort($allTests);
            ?>
            <div class="table-wrapper" style="margin-top:16px;">
                <table class="table">
                    <thead>
                        <tr>
                            <th>الفحص</th>
                            <th><?php echo htmlspecialchars(($ordA['order_number'] ?? '') . ' - ' . ($ordA['order_date'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></th>
                            <th><?php echo htmlspecialchars(($ordB['order_number'] ?? '') . ' - ' . ($ordB['order_date'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></th>
                            <th>الوحدة / المدى</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($allTests as $tn): $a = $mapA[$tn] ?? null; $b = $mapB[$tn] ?? null; $ref = ($a ? $a['reference_range'] : null) ?: ($b ? $b['reference_range'] : null); ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($tn, ENT_QUOTES, 'UTF-8'); ?></strong></td>
                            <td><?php echo $a ? htmlspecialchars($a['result_value'] ?? '—', ENT_QUOTES, 'UTF-8') . ($a['flag'] ? ' <span class="badge badge-'.$a['flag'].'">'.$a['flag'].'</span>' : '') : '—'; ?></td>
                            <td><?php echo $b ? htmlspecialchars($b['result_value'] ?? '—', ENT_QUOTES, 'UTF-8') . ($b['flag'] ? ' <span class="badge badge-'.$b['flag'].'">'.$b['flag'].'</span>' : '') : '—'; ?></td>
                            <td style="font-size:0.85rem;color:var(--text-muted);"><?php echo htmlspecialchars(($a ? $a['unit'] : ($b ? $b['unit'] : '')) . ($ref ? ' | ' . $ref : ''), ENT_QUOTES, 'UTF-8'); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
            <?php endif; ?>
            <div class="table-wrapper">
                <table class="table">
                    <thead><tr><th>رقم الطلب</th><th>التاريخ</th><th>الطبيب</th><th>المبلغ</th><th>الدفع</th><th>إجراءات</th></tr></thead>
                    <tbody>
                    <?php foreach ($visits as $v): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($v['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars($v['order_date'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars($v['doctor_name'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><?php echo htmlspecialchars($v['net_amount'], ENT_QUOTES, 'UTF-8'); ?></td>
                            <td><span class="badge badge-<?php echo htmlspecialchars($v['payment_status'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo $v['payment_status'] === 'paid' ? 'مدفوعة' : ($v['payment_status'] === 'partial' ? 'جزئي' : 'غير مدفوعة'); ?></span></td>
                            <td>
                                <a href="index.php?page=results&order_id=<?php echo (int)$v['id']; ?>">نتائج</a>
                                <a href="index.php?page=print_result&order_id=<?php echo (int)$v['id']; ?>" target="_blank">طباعة</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="section-card">
            <h3>رفع تقرير أو مرفق</h3>
            <p class="text-muted" style="font-size:0.9rem;margin:0 0 12px;">PDF أو صورة (JPG, PNG)</p>
            <form method="post" enctype="multipart/form-data" action="index.php?page=patients&action=upload&id=<?php echo (int)$viewId; ?>" class="upload-form">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <input type="file" name="file" accept=".pdf,.jpg,.jpeg,.png" required>
                <button type="submit" class="btn-primary" style="margin-top:8px;">رفع</button>
            </form>
        </div>
        <?php if (count($attachments) > 0): ?>
        <div class="section-card">
            <h3>المرفقات (<?php echo count($attachments); ?>)</h3>
            <ul class="attachments-list">
            <?php foreach ($attachments as $a): ?>
                <li><a href="<?php echo htmlspecialchars($a['file_path'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" target="_blank" class="attachment-link">📄 <?php echo htmlspecialchars($a['file_name'], ENT_QUOTES, 'UTF-8'); ?></a> <span class="attachment-date"><?php echo htmlspecialchars($a['created_at'], ENT_QUOTES, 'UTF-8'); ?></span></li>
            <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>
        <?php
        return;
    }
}

$patients = [];
$exportCsv = isset($_GET['export']) && $_GET['export'] === 'csv';
$patientSearch = trim($_GET['q'] ?? '');
$pageNum = max(1, (int)($_GET['p'] ?? 1));
$perPage = 30;
$offset = ($pageNum - 1) * $perPage;
$totalPatients = 0;
$newPatientsLast7 = 0;

try {
    $cntSql = 'SELECT COUNT(*) FROM patients WHERE tenant_id = ?';
    $cntParams = [$tenantId];
    if ($patientSearch !== '') {
        $searchLike = '%' . $patientSearch . '%';
        try { $db->query('SELECT email FROM patients LIMIT 1'); $cntSql .= ' AND (full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ? OR national_id LIKE ? OR email LIKE ?)'; $cntParams = array_merge($cntParams, [$searchLike, $searchLike, $searchLike, $searchLike, $searchLike]); } catch (Throwable $ex) { $cntSql .= ' AND (full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ? OR national_id LIKE ?)'; $cntParams = array_merge($cntParams, [$searchLike, $searchLike, $searchLike, $searchLike]); }
    }
    $stmt = $db->prepare($cntSql);
    $stmt->execute($cntParams);
    $totalPatients = (int)$stmt->fetchColumn();
    $stmt7 = $db->prepare('SELECT COUNT(*) FROM patients WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND tenant_id = ?');
    $stmt7->execute([$tenantId]);
    $newPatientsLast7 = (int)$stmt7->fetchColumn();
} catch (Throwable $e) {
    try { $totalPatients = (int)$db->query('SELECT COUNT(*) FROM patients')->fetchColumn(); } catch (Throwable $e2) {}
}

try {
    $sql = 'SELECT id, patient_code, full_name, gender, phone, created_at
         FROM patients
         WHERE tenant_id = ?';
    $listParams = [$tenantId];
    if ($patientSearch !== '') {
        $searchLike = '%' . $patientSearch . '%';
        try { $db->query('SELECT email FROM patients LIMIT 1'); $sql .= ' AND (full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ? OR national_id LIKE ? OR email LIKE ?)'; $listParams = array_merge($listParams, [$searchLike, $searchLike, $searchLike, $searchLike, $searchLike]); } catch (Throwable $ex) { $sql .= ' AND (full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ? OR national_id LIKE ?)'; $listParams = array_merge($listParams, [$searchLike, $searchLike, $searchLike, $searchLike]); }
    }
    $sql .= ' ORDER BY id DESC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;
    $stmt = $db->prepare($sql);
    $stmt->execute($listParams);
    $patients = $stmt->fetchAll();
} catch (Throwable $e) {
    try {
        $sql = 'SELECT id, patient_code, full_name, gender, phone, created_at FROM patients';
        $fp = [];
        if ($patientSearch !== '') {
            $sql .= ' WHERE full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ?';
            $like = '%' . $patientSearch . '%';
            $fp = [$like, $like, $like];
        }
        $sql .= ' ORDER BY id DESC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset;
        $stmt = $fp ? $db->prepare($sql) : $db->query($sql);
        if ($fp) $stmt->execute($fp);
        $patients = $stmt->fetchAll();
    } catch (Throwable $e2) {}
}
$totalPages = $totalPatients > 0 ? (int)ceil($totalPatients / $perPage) : 1;

if ($exportCsv) {
    $expPatients = [];
    try {
        $stmt = $db->prepare('SELECT id, patient_code, full_name, gender, phone, national_id, created_at FROM patients WHERE tenant_id = ? ORDER BY id DESC');
        $stmt->execute([$tenantId]);
        $expPatients = $stmt->fetchAll();
    } catch (Throwable $e) {
        try { $expPatients = $db->query('SELECT id, patient_code, full_name, gender, phone, national_id, created_at FROM patients ORDER BY id DESC')->fetchAll(); } catch (Throwable $e2) {}
    }
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="patients_' . date('Y-m-d_His') . '.csv"');
    echo "\xEF\xBB\xBF";
    echo "الكود,الاسم,الجنس,الهاتف,الرقم الوطني,تاريخ الإضافة\n";
    foreach ($expPatients as $p) {
        $g = $p['gender'] === 'M' ? 'ذكر' : ($p['gender'] === 'F' ? 'أنثى' : '-');
        $line = [$p['patient_code'], $p['full_name'], $g, $p['phone'] ?? '', $p['national_id'] ?? '', $p['created_at'] ?? ''];
        $escaped = [];
        foreach ($line as $v) {
            $v = (string)$v;
            if (strpbrk($v, ",\"\n\r") !== false) $v = '"' . str_replace('"', '""', $v) . '"';
            $escaped[] = $v;
        }
        echo implode(',', $escaped) . "\n";
    }
    exit;
}
$baseListUrl = 'index.php?page=patients' . ($patientSearch ? '&q=' . urlencode($patientSearch) : '');
?>
<?php if (isset($_GET['err']) && $_GET['err'] === 'has_orders'): ?>
<div class="alert alert-warning" style="margin-bottom:16px;">لا يمكن حذف المريض لوجود طلبات سابقة مرتبطة به.</div>
<?php endif; ?>
<div class="patients-page">
    <header class="patients-header">
        <h1>إدارة المرضى</h1>
        <div class="patients-actions">
            <form method="get" class="patients-search-form">
                <input type="hidden" name="page" value="patients">
                <input type="search" name="q" placeholder="بحث بالاسم، الكود، الهاتف، الرقم الوطني..." value="<?php echo htmlspecialchars($patientSearch, ENT_QUOTES, 'UTF-8'); ?>" class="patients-search-input">
                <button type="submit" class="btn-secondary">بحث</button>
                <?php if ($patientSearch): ?><a href="index.php?page=patients" class="btn-secondary">مسح</a><?php endif; ?>
            </form>
            <?php if (isset($auth) && $auth->can('patients.create')): ?><a href="index.php?page=patients&action=create" class="btn-primary">+ مريض جديد</a><?php endif; ?>
            <a href="index.php?page=patients&export=csv<?php echo $patientSearch ? '&q='.urlencode($patientSearch) : ''; ?>" class="btn-secondary">تصدير CSV</a>
        </div>
    </header>

    <section class="patients-stats">
        <div class="patients-stat-card">
            <span class="patients-stat-value"><?php echo number_format($totalPatients); ?></span>
            <span class="patients-stat-label">إجمالي المرضى</span>
        </div>
        <div class="patients-stat-card">
            <span class="patients-stat-value"><?php echo $newPatientsLast7; ?></span>
            <span class="patients-stat-label">جدد خلال 7 أيام</span>
        </div>
    </section>

    <div class="section-card">
        <div class="table-wrapper">
        <table class="table patients-table">
            <thead>
                <tr>
                    <th>الكود</th>
                    <th>الاسم</th>
                    <th>الجنس</th>
                    <th>الهاتف</th>
                    <th>تاريخ الإضافة</th>
                    <th style="width:220px;">إجراءات</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($patients as $p): ?>
                <tr>
                    <td><code class="patient-code"><?php echo htmlspecialchars($p['patient_code'], ENT_QUOTES, 'UTF-8'); ?></code></td>
                    <td><strong><?php echo htmlspecialchars($p['full_name'], ENT_QUOTES, 'UTF-8'); ?></strong></td>
                    <td><?php echo $p['gender'] === 'M' ? 'ذكر' : ($p['gender'] === 'F' ? 'أنثى' : '—'); ?></td>
                    <td><?php echo htmlspecialchars($p['phone'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($p['created_at'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td class="patients-row-actions">
                        <a href="index.php?page=patients&action=view&id=<?php echo (int)$p['id']; ?>" class="btn-action btn-action--view" title="عرض الملف">عرض</a>
                        <?php if (isset($auth) && $auth->can('patients.create')): ?><a href="index.php?page=patients&action=edit&id=<?php echo (int)$p['id']; ?>" class="btn-action btn-action--edit" title="تعديل">تعديل</a><?php endif; ?>
                        <?php if (isset($auth) && $auth->can('orders.create')): ?><a href="index.php?page=orders&action=create&patient_id=<?php echo (int)$p['id']; ?>" class="btn-action btn-action--order" title="إنشاء طلب">طلب جديد</a><?php endif; ?>
                        <?php if (isset($auth) && $auth->can('patients.delete')): ?>
                        <form method="post" action="index.php?page=patients&action=delete" style="display:inline;" onsubmit="return confirm('هل أنت متأكد من حذف بيانات المريض؟');">
                            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="id" value="<?php echo (int)$p['id']; ?>">
                            <button type="submit" class="btn-action btn-action--delete" title="حذف المريض">حذف</button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php if (empty($patients)): ?>
        <p class="patients-empty">لا توجد نتائج. <?php if ($patientSearch): ?><a href="index.php?page=patients">عرض الكل</a><?php else: ?><a href="index.php?page=patients&action=create">إضافة مريض جديد</a><?php endif; ?></p>
        <?php endif; ?>
    </div>

    <?php if ($totalPages > 1): ?>
    <nav class="patients-pagination">
        <?php if ($pageNum > 1): ?><a href="<?php echo $baseListUrl; ?>&p=<?php echo $pageNum - 1; ?>" class="btn-secondary">← السابق</a><?php endif; ?>
        <span class="patients-pagination-info">صفحة <?php echo $pageNum; ?> من <?php echo $totalPages; ?></span>
        <?php if ($pageNum < $totalPages): ?><a href="<?php echo $baseListUrl; ?>&p=<?php echo $pageNum + 1; ?>" class="btn-secondary">التالي →</a><?php endif; ?>
    </nav>
    <?php endif; ?>
</div>
