<?php
/**
 * قائمة المرضى - المرضى الذين أُحيلوا للطبيب
 */
$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

$q = trim($_GET['q'] ?? '');
$patients = [];
$export = isset($_GET['export']) && $_GET['export'] === 'csv';
$favoritesOnly = isset($_GET['favorites']) && $_GET['favorites'] === '1';
$sortBy = $_GET['sort'] ?? 'last_order';
$sortOpts = ['last_order' => 'آخر طلب', 'name' => 'الاسم', 'orders' => 'عدد الطلبات'];

$favoriteIds = [];
try {
    $db->query('SELECT patient_id FROM doctor_favorite_patients LIMIT 1');
    $stmt = $db->prepare('SELECT patient_id FROM doctor_favorite_patients WHERE doctor_account_id = ?');
    $stmt->execute([$doctorAuth->accountId()]);
    $favoriteIds = array_column($stmt->fetchAll(), 'patient_id');
} catch (Throwable $e) {}

try {
    $notesSub = '';
    try { $db->query('SELECT id FROM patient_medical_notes LIMIT 1'); $notesSub = ', (SELECT COUNT(*) FROM patient_medical_notes n WHERE n.patient_id = p.id) AS notes_count'; } catch (Throwable $e) { $notesSub = ', 0 AS notes_count'; }
    $criticalSub = '';
    try { $db->query('SELECT id FROM results LIMIT 1'); $criticalSub = ', (SELECT COUNT(*) FROM results r JOIN order_items oi ON oi.id = r.order_item_id JOIN lab_orders o2 ON o2.id = oi.order_id WHERE o2.patient_id = p.id AND o2.tenant_id = ' . (int)$tenantId . ' AND o2.doctor_id = ' . (int)$doctorId . ' AND r.flag = \'C\' AND o2.order_date >= DATE_SUB(CURDATE(), INTERVAL 180 DAY)) AS critical_count'; } catch (Throwable $e) { $criticalSub = ', 0 AS critical_count'; }
    $sql = "SELECT p.id, p.patient_code, p.full_name, p.gender, p.date_of_birth, p.phone,
                   COUNT(DISTINCT o.id) AS orders_count,
                   MAX(o.order_date) AS last_order_date
                   $notesSub $criticalSub
            FROM patients p
            LEFT JOIN lab_orders o ON o.patient_id = p.id $tenantCond $doctorCond
            WHERE 1=1";
    $params = [];
    $tenantPat = '';
    try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $tenantPat = ' AND p.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
    $sql .= $tenantPat;
    if ($q !== '') {
        $sql .= ' AND (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ?)';
        $like = '%' . $q . '%';
        $params = array_merge($params, [$like, $like, $like]);
    }
    if ($favoritesOnly && !empty($favoriteIds)) {
        $sql .= ' AND p.id IN (' . implode(',', array_map('intval', $favoriteIds)) . ')';
    } elseif ($favoritesOnly) {
        $sql .= ' AND 1=0';
    }
    $orderBy = 'last_order_date DESC';
    if ($sortBy === 'name') $orderBy = 'p.full_name ASC';
    elseif ($sortBy === 'orders') $orderBy = 'orders_count DESC';
    $sql .= ' GROUP BY p.id ORDER BY ' . $orderBy . ' LIMIT ' . ($export ? '5000' : '200');
    $stmt = $params ? $db->prepare($sql) : $db->query($sql);
    if ($params) $stmt->execute($params);
    $patients = $stmt->fetchAll();
} catch (Throwable $e) {}

if ($export && !empty($patients)) {
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="patients_' . date('Y-m-d') . '.csv"');
    echo "\xEF\xBB\xBF";
    echo "الرقم,الاسم,الجنس,تاريخ الميلاد,الهاتف,عدد الطلبات,آخر طلب\n";
    foreach ($patients as $p) {
        $line = [
            $p['patient_code'],
            $p['full_name'],
            ($p['gender'] ?? '') === 'M' ? 'ذكر' : (($p['gender'] ?? '') === 'F' ? 'أنثى' : '-'),
            $p['date_of_birth'] ? date('Y-m-d', strtotime($p['date_of_birth'])) : '-',
            $p['phone'] ?? '-',
            (int)$p['orders_count'],
            $p['last_order_date'] ? date('Y-m-d', strtotime($p['last_order_date'])) : '-'
        ];
        echo '"' . implode('","', array_map(function($v) { return str_replace('"', '""', $v); }, $line)) . "\"\n";
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/svg+xml" href="favicon.svg">
    <title>المرضى - Smart Doctor</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content">
    <div class="page-header">
        <h1>المرضى</h1>
        <div style="display:flex;gap:12px;flex-wrap:wrap;align-items:center;">
            <form method="get" style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;">
                <input type="hidden" name="page" value="patients">
                <input type="search" name="q" placeholder="بحث بالاسم أو الرقم أو الهاتف..." value="<?php echo htmlspecialchars($q, ENT_QUOTES, 'UTF-8'); ?>" style="min-width:220px;">
                <select name="sort" onchange="this.form.submit()" style="min-width:120px;">
                    <?php foreach ($sortOpts as $k => $v): ?><option value="<?php echo $k; ?>" <?php echo $sortBy === $k ? 'selected' : ''; ?>><?php echo $v; ?></option><?php endforeach; ?>
                </select>
                <label><input type="checkbox" name="favorites" value="1" <?php echo $favoritesOnly ? 'checked' : ''; ?> onchange="this.form.submit()"> المفضلة فقط</label>
                <button type="submit">بحث</button>
            </form>
            <a href="doctor.php?page=patients&export=csv<?php echo $q ? '&q=' . urlencode($q) : ''; echo $favoritesOnly ? '&favorites=1' : ''; echo $sortBy !== 'last_order' ? '&sort=' . urlencode($sortBy) : ''; ?>" class="btn-secondary">📥 تصدير CSV</a>
            <a href="doctor.php?page=reminders" class="btn-secondary">⏰ التذكيرات</a>
        </div>
    </div>

    <?php if (isset($_SESSION['doctor_msg'])): ?>
    <div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['doctor_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_msg']); ?></div>
    <?php endif; ?>

    <div class="card" style="margin-bottom:20px;">
        <h3 style="margin:0 0 12px;">➕ إضافة مريض جديد</h3>
        <form method="post" action="doctor.php?page=patients&action=create" class="form-grid">
            <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>
            <div>
                <label>الرقم الوطني</label>
                <input type="text" name="national_id" placeholder="رقم الهوية (اختياري)">
            </div>
            <div>
                <label>العنوان</label>
                <input type="text" name="address" placeholder="المحافظة، المدينة، الحي">
            </div>
            <div>
                <label>فصيلة الدم</label>
                <input type="text" name="blood_type" placeholder="مثال: O+">
            </div>
            <div>
                <label>أمراض مزمنة</label>
                <input type="text" name="chronic_conditions" placeholder="سكر، ضغط، قلب...">
            </div>
            <div>
                <label>حساسية أدوية</label>
                <input type="text" name="allergies" placeholder="بنسلين، مسكنات...">
            </div>
            <div class="full-width" style="text-align:left;">
                <button type="submit" class="btn-primary">حفظ المريض</button>
            </div>
        </form>
        <div class="doctor-inline-search-wrap">
            <p class="doctor-smart-hint">أو ابحث عن مريض مسجل:</p>
            <form method="get" class="doctor-inline-patient-search" onsubmit="return false;">
                <input type="hidden" name="page" value="patients">
                <input type="search" id="doctorInlinePatientFilter" name="q" placeholder="بحث سريع بالاسم أو الكود أو الهاتف..." class="doctor-inline-patient-input" autocomplete="off">
            </form>
        </div>
    </div>

    <?php if (empty($patients)): ?>
    <div class="card">
        <p style="text-align:center;color:var(--text-muted);padding:40px;"><?php echo $q ? 'لم يتم العثور على مرضى.' : 'لا يوجد مرضى مسجلين حتى الآن.'; ?></p>
    </div>
    <?php else: ?>
    <div class="card" style="padding:0;overflow:hidden;">
        <div class="table-wrapper" style="max-height:calc(100vh - 300px);overflow-y:auto;">
            <table class="table doctor-patients-table">
                <thead style="position:sticky;top:0;z-index:10;background:var(--bg-card);">
                    <tr>
                        <th style="width:40px;text-align:center;">⭐</th>
                        <th style="min-width:120px;">الرقم</th>
                        <th style="min-width:180px;">الاسم</th>
                        <th style="width:80px;text-align:center;">الجنس</th>
                        <th style="min-width:140px;">تاريخ الميلاد</th>
                        <th style="min-width:130px;">الهاتف</th>
                        <th style="width:100px;text-align:center;">الطلبات</th>
                        <th style="min-width:120px;">آخر طلب</th>
                        <th style="min-width:280px;">إجراء</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($patients as $p):
                    $pid = (int)$p['id'];
                    $isFav = in_array($pid, $favoriteIds);
                ?>
                <tr class="doctor-patient-row" style="transition:background 0.2s ease;">
                    <td style="text-align:center;">
                        <form method="post" action="doctor.php?page=patients" style="display:inline;">
                            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="action" value="favorite">
                            <input type="hidden" name="patient_id" value="<?php echo $pid; ?>">
                            <input type="hidden" name="add" value="<?php echo $isFav ? '0' : '1'; ?>">
                            <input type="hidden" name="q" value="<?php echo htmlspecialchars($q, ENT_QUOTES, 'UTF-8'); ?>">
                            <button type="submit"
                                    title="<?php echo $isFav ? 'إزالة من المفضلة' : 'إضافة للمفضلة'; ?>"
                                    style="font-size:1.2rem;text-decoration:none;display:inline-block;transition:transform 0.2s;background:none;border:none;padding:0;cursor:pointer;">
                                <?php echo $isFav ? '⭐' : '☆'; ?>
                            </button>
                        </form>
                    </td>
                    <td>
                        <code style="background:var(--bg-secondary);padding:4px 8px;border-radius:6px;font-size:0.85rem;font-weight:600;color:var(--primary);">
                            <?php echo htmlspecialchars($p['patient_code'], ENT_QUOTES, 'UTF-8'); ?>
                        </code>
                    </td>
                    <td>
                        <strong style="font-size:1rem;color:var(--text-primary);">
                            <?php echo htmlspecialchars($p['full_name'], ENT_QUOTES, 'UTF-8'); ?>
                        </strong>
                    </td>
                    <td style="text-align:center;">
                        <span style="padding:4px 10px;background:<?php echo ($p['gender'] ?? '') === 'M' ? '#dbeafe' : '#fce7f3'; ?>;color:<?php echo ($p['gender'] ?? '') === 'M' ? '#1e40af' : '#9f1239'; ?>;border-radius:12px;font-size:0.85rem;font-weight:500;">
                            <?php echo ($p['gender'] ?? '') === 'M' ? '👨 ذكر' : (($p['gender'] ?? '') === 'F' ? '👩 أنثى' : '-'); ?>
                        </span>
                    </td>
                    <td>
                        <?php if ($p['date_of_birth']): 
                            $age = date_diff(date_create($p['date_of_birth']), date_create('today'))->y;
                        ?>
                        <div style="display:flex;flex-direction:column;gap:2px;">
                            <span style="font-size:0.9rem;"><?php echo date('Y-m-d', strtotime($p['date_of_birth'])); ?></span>
                            <span style="color:var(--text-muted);font-size:0.8rem;"><?php echo $age; ?> سنة</span>
                        </div>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">-</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($p['phone'])): 
                            $waUrl = function_exists('doctor_wa_link') ? doctor_wa_link($p['phone'], '') : '';
                            ?>
                        <a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $p['phone']), ENT_QUOTES, 'UTF-8'); ?>" 
                           title="اتصال"
                           style="color:var(--primary);text-decoration:none;display:inline-flex;align-items:center;gap:4px;padding:4px 8px;border-radius:6px;transition:background 0.2s;"
                           onmouseover="this.style.background='var(--bg-hover)'"
                           onmouseout="this.style.background='transparent'">
                            📞 <?php echo htmlspecialchars($p['phone'], ENT_QUOTES, 'UTF-8'); ?>
                        </a>
                        <?php if ($waUrl): ?><a href="<?php echo htmlspecialchars($waUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" title="واتساب مجاني" style="color:#25D366;margin-right:4px;">💬</a><?php endif; ?>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">-</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align:center;">
                        <span style="display:inline-flex;align-items:center;justify-content:center;min-width:32px;height:32px;background:var(--bg-secondary);border-radius:50%;font-weight:600;font-size:0.9rem;">
                            <?php echo (int)$p['orders_count']; ?>
                        </span>
                    </td>
                    <td>
                        <?php if ($p['last_order_date']): 
                            $lastOrderDate = strtotime($p['last_order_date']);
                            $daysAgo = floor((time() - $lastOrderDate) / 86400);
                        ?>
                        <div style="display:flex;flex-direction:column;gap:2px;">
                            <span style="font-size:0.9rem;"><?php echo date('Y-m-d', $lastOrderDate); ?></span>
                            <?php if ($daysAgo <= 7): ?>
                            <span style="color:#22c55e;font-size:0.75rem;">منذ <?php echo $daysAgo; ?> يوم</span>
                            <?php elseif ($daysAgo <= 30): ?>
                            <span style="color:#f59e0b;font-size:0.75rem;">منذ <?php echo $daysAgo; ?> يوم</span>
                            <?php else: ?>
                            <span style="color:var(--text-muted);font-size:0.75rem;">منذ <?php echo $daysAgo; ?> يوم</span>
                            <?php endif; ?>
                        </div>
                        <?php else: ?>
                        <span style="color:var(--text-muted);">-</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="doctor-patients-actions-cell">
                            <?php if (!empty($p['critical_count']) && (int)$p['critical_count'] > 0): ?>
                            <span class="doctor-patient-action-badge critical" title="نتائج حرجة: <?php echo (int)$p['critical_count']; ?>">
                                ⚠️ <?php echo (int)$p['critical_count']; ?>
                            </span>
                            <?php endif; ?>
                            <?php if (!empty($p['notes_count']) && (int)$p['notes_count'] > 0): ?>
                            <span class="doctor-patient-action-badge notes" title="ملاحظات طبية: <?php echo (int)$p['notes_count']; ?>">
                                📝 <?php echo (int)$p['notes_count']; ?>
                            </span>
                            <?php endif; ?>
                            <a href="doctor.php?page=results&patient_id=<?php echo $pid; ?>" 
                               class="doctor-patient-profile-btn btn-primary btn-sm"
                               title="عرض بروفايل المريض والنتائج">
                                👤 بروفايل
                            </a>
                            <a href="doctor.php?page=accounts&patient_id=<?php echo $pid; ?>" 
                               class="btn-secondary btn-sm doctor-account-btn"
                               title="كشفية المريض المالية">
                                💰 كشفية
                            </a>
                            <button type="button" 
                                    onclick="window.DoctorQuickCopy && window.DoctorQuickCopy.copyPatientInfo(<?php echo $pid; ?>)" 
                                    class="btn-secondary btn-sm doctor-copy-btn"
                                    title="نسخ بيانات المريض">
                                📋
                            </button>
                            <a href="doctor.php?page=results&patient_id=<?php echo $pid; ?>#reminder" 
                               class="doctor-patient-reminder-btn"
                               title="تذكير متابعة">
                                ⏰
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <div style="padding:16px;background:var(--bg-secondary);border-top:1px solid var(--border);text-align:center;color:var(--text-muted);font-size:0.9rem;">
            إجمالي المرضى: <strong><?php echo count($patients); ?></strong>
        </div>
    </div>
    <?php endif; ?>
</main>
<script>
(function(){
    var input = document.getElementById('doctorInlinePatientFilter');
    var table = document.querySelector('table.table');
    if (!input || !table) return;
    var rows = Array.prototype.slice.call(table.querySelectorAll('tbody tr'));
    input.addEventListener('input', function(){
        var q = this.value.trim().toLowerCase();
        rows.forEach(function(row){
            var text = (row.textContent || '').toLowerCase();
            row.style.display = (!q || text.indexOf(q) !== -1) ? '' : 'none';
        });
    });
})();
</script>
</body>
</html>
