<?php
/**
 * مرضى الطبيب
 */

// التحقق من تسجيل دخول الطبيب
if (!isset($_SESSION['doctor_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'doctor') {
    header('Location: index.php?page=doctor_login');
    exit;
}

$doctorId = (int)$_SESSION['doctor_id'];
$tenantId = (int)$_SESSION['doctor_tenant_id'];

$action = $_GET['action'] ?? 'index';
$search = trim($_GET['search'] ?? '');

// جلب مرضى الطبيب
$patients = [];
$where = ['pv.doctor_id = ?', 'pv.tenant_id = ?'];
$params = [$doctorId, $tenantId];

if ($search !== '') {
    $where[] = '(p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ?)';
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

try {
    $stmt = $db->prepare(
        'SELECT DISTINCT p.*, 
         COUNT(DISTINCT pv.id) as visit_count,
         MAX(pv.visit_date) as last_visit_date
         FROM patients p
         JOIN patient_visits pv ON pv.patient_id = p.id
         WHERE ' . implode(' AND ', $where) . '
         GROUP BY p.id
         ORDER BY last_visit_date DESC'
    );
    $stmt->execute($params);
    $patients = $stmt->fetchAll();
} catch (Throwable $e) {
    $patients = [];
}

// عرض المريض
if ($action === 'view' && isset($_GET['id'])) {
    $patientId = (int)$_GET['id'];
    
    // التحقق من أن المريض من مرضى الطبيب
    try {
        $stmt = $db->prepare(
            'SELECT p.* FROM patients p
             JOIN patient_visits pv ON pv.patient_id = p.id
             WHERE p.id = ? AND pv.doctor_id = ? AND pv.tenant_id = ?
             LIMIT 1'
        );
        $stmt->execute([$patientId, $doctorId, $tenantId]);
        $patient = $stmt->fetch();
    } catch (Throwable $e) {
        $patient = null;
    }
    
    if (!$patient) {
        echo '<div class="alert alert-danger">المريض غير موجود أو غير مرتبط بك</div>';
        echo '<a href="index.php?page=doctor_patients" class="btn">العودة</a>';
        exit;
    }
    
    // جلب زيارات المريض
    $visits = [];
    try {
        $stmt = $db->prepare(
            'SELECT * FROM patient_visits 
             WHERE patient_id = ? AND doctor_id = ?
             ORDER BY visit_date DESC'
        );
        $stmt->execute([$patientId, $doctorId]);
        $visits = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب التحاليل المرتبطة
    $labResults = [];
    try {
        $stmt = $db->prepare(
            'SELECT clr.*, lo.order_number, lo.order_date,
             GROUP_CONCAT(t.name SEPARATOR ", ") as test_names
             FROM clinic_lab_requests clr
             LEFT JOIN lab_orders lo ON clr.lab_order_id = lo.id
             LEFT JOIN clinic_lab_request_items clri ON clri.request_id = clr.id
             LEFT JOIN tests t ON clri.test_id = t.id
             WHERE clr.patient_id = ? AND clr.doctor_id = ?
             GROUP BY clr.id
             ORDER BY clr.request_date DESC'
        );
        $stmt->execute([$patientId, $doctorId]);
        $labResults = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب المرفقات (تحاليل مرفقة)
    $attachments = [];
    try {
        $stmt = $db->prepare(
            'SELECT va.*, pv.visit_date
             FROM visit_attachments va
             JOIN patient_visits pv ON va.visit_id = pv.id
             WHERE pv.patient_id = ? AND pv.doctor_id = ?
             ORDER BY va.created_at DESC'
        );
        $stmt->execute([$patientId, $doctorId]);
        $attachments = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    ?>
    <!DOCTYPE html>
    <html lang="ar" dir="rtl">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ملف المريض - <?= htmlspecialchars($patient['full_name']) ?></title>
        <link rel="stylesheet" href="styles.css">
        <link rel="stylesheet" href="portal.css">
        <style>
            .patient-header {
                background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
                color: white;
                padding: 20px;
                border-radius: 12px;
                margin-bottom: 30px;
            }
            .info-card {
                background: white;
                padding: 20px;
                border-radius: 12px;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                margin-bottom: 20px;
            }
            .info-card h3 {
                margin: 0 0 15px 0;
                color: #333;
                border-bottom: 2px solid #f0f0f0;
                padding-bottom: 10px;
            }
            .info-table {
                width: 100%;
            }
            .info-table th {
                text-align: right;
                padding: 8px;
                color: #666;
                width: 150px;
            }
            .info-table td {
                padding: 8px;
                color: #333;
            }
            .visit-item {
                padding: 15px;
                border-bottom: 1px solid #f0f0f0;
            }
            .visit-item:last-child {
                border-bottom: none;
            }
            .lab-result-item {
                padding: 15px;
                border-bottom: 1px solid #f0f0f0;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .attachment-item {
                padding: 10px;
                border: 1px solid #e0e0e0;
                border-radius: 8px;
                margin-bottom: 10px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .nav-menu {
                background: white;
                padding: 15px;
                border-radius: 12px;
                margin-bottom: 20px;
                display: flex;
                gap: 10px;
                flex-wrap: wrap;
            }
            .nav-menu a {
                padding: 10px 20px;
                background: #f0f0f0;
                border-radius: 8px;
                text-decoration: none;
                color: #333;
            }
            .nav-menu a:hover {
                background: #667eea;
                color: white;
            }
        </style>
    </head>
    <body>
        <div class="nav-menu">
            <a href="index.php?page=doctor_dashboard">🏠 الرئيسية</a>
            <a href="index.php?page=doctor_patients">👥 مرضاي</a>
            <a href="index.php?page=doctor_appointments">📅 مواعيدي</a>
            <a href="index.php?page=doctor_visits">📋 زياراتي</a>
            <a href="index.php?page=doctor_lab_results">🔬 التحاليل</a>
        </div>
        
        <div class="patient-header">
            <h1>👤 <?= htmlspecialchars($patient['full_name']) ?></h1>
            <p>كود المريض: <?= htmlspecialchars($patient['patient_code'] ?? '-') ?></p>
        </div>
        
        <div class="info-card">
            <h3>البيانات الشخصية</h3>
            <table class="info-table">
                <tr><th>الاسم:</th><td><?= htmlspecialchars($patient['full_name']) ?></td></tr>
                <tr><th>الجنس:</th><td><?= $patient['gender'] === 'M' ? 'ذكر' : ($patient['gender'] === 'F' ? 'أنثى' : '-') ?></td></tr>
                <tr><th>تاريخ الميلاد:</th><td><?= $patient['date_of_birth'] ? date('Y-m-d', strtotime($patient['date_of_birth'])) : '-' ?></td></tr>
                <tr><th>الهاتف:</th><td><?= htmlspecialchars($patient['phone'] ?? '-') ?></td></tr>
                <tr><th>العنوان:</th><td><?= htmlspecialchars($patient['address'] ?? '-') ?></td></tr>
                <?php if (!empty($patient['blood_type'])): ?>
                    <tr><th>فصيلة الدم:</th><td><?= htmlspecialchars($patient['blood_type']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($patient['allergies'])): ?>
                    <tr><th>الحساسيات:</th><td><?= htmlspecialchars($patient['allergies']) ?></td></tr>
                <?php endif; ?>
                <?php if (!empty($patient['chronic_diseases'])): ?>
                    <tr><th>أمراض مزمنة:</th><td><?= htmlspecialchars($patient['chronic_diseases']) ?></td></tr>
                <?php endif; ?>
            </table>
        </div>
        
        <div class="info-card">
            <h3>🔬 التحاليل الطبية</h3>
            <?php if (empty($labResults) && empty($attachments)): ?>
                <p style="color: #666; text-align: center; padding: 20px;">لا توجد تحاليل</p>
            <?php else: ?>
                <?php foreach ($labResults as $result): ?>
                    <div class="lab-result-item">
                        <div>
                            <div style="font-weight: bold;"><?= htmlspecialchars($result['test_names'] ?? 'تحاليل') ?></div>
                            <div style="font-size: 12px; color: #666; margin-top: 5px;">
                                تاريخ الطلب: <?= date('Y-m-d H:i', strtotime($result['request_date'])) ?>
                            </div>
                            <div style="font-size: 12px; color: #666;">
                                الحالة: 
                                <span class="badge badge-<?= $result['status'] === 'completed' ? 'success' : 'warning' ?>">
                                    <?= $result['status'] === 'completed' ? 'مكتمل' : ($result['status'] === 'pending' ? 'معلق' : 'قيد المعالجة') ?>
                                </span>
                            </div>
                        </div>
                        <div>
                            <?php if ($result['status'] === 'completed' && $result['lab_order_id']): ?>
                                <a href="index.php?page=print_result&order=<?= $result['lab_order_id'] ?>" target="_blank" class="btn btn-sm">عرض النتيجة</a>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
                
                <?php foreach ($attachments as $attachment): ?>
                    <?php if ($attachment['attachment_type'] === 'lab_result'): ?>
                        <div class="attachment-item">
                            <div>
                                <div style="font-weight: bold;">📄 <?= htmlspecialchars($attachment['file_name']) ?></div>
                                <div style="font-size: 12px; color: #666;">
                                    تاريخ الرفع: <?= date('Y-m-d H:i', strtotime($attachment['created_at'])) ?>
                                </div>
                            </div>
                            <div>
                                <a href="<?= htmlspecialchars($attachment['file_path']) ?>" target="_blank" class="btn btn-sm">عرض</a>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        
        <div class="info-card">
            <h3>📋 تاريخ الزيارات</h3>
            <?php if (empty($visits)): ?>
                <p style="color: #666; text-align: center; padding: 20px;">لا توجد زيارات سابقة</p>
            <?php else: ?>
                <?php foreach ($visits as $visit): ?>
                    <div class="visit-item">
                        <div style="font-weight: bold; margin-bottom: 5px;">
                            <?= date('Y-m-d H:i', strtotime($visit['visit_date'])) ?>
                        </div>
                        <?php if ($visit['chief_complaint']): ?>
                            <div style="margin-bottom: 5px;">
                                <strong>الشكوى:</strong> <?= htmlspecialchars(mb_substr($visit['chief_complaint'], 0, 100)) ?>
                            </div>
                        <?php endif; ?>
                        <?php if ($visit['diagnosis']): ?>
                            <div style="margin-bottom: 5px;">
                                <strong>التشخيص:</strong> <?= htmlspecialchars(mb_substr($visit['diagnosis'], 0, 100)) ?>
                            </div>
                        <?php endif; ?>
                        <div>
                            <a href="index.php?page=doctor_visits&action=view&id=<?= $visit['id'] ?>" class="btn btn-sm">عرض التفاصيل</a>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// عرض القائمة
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مرضاي</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="portal.css">
    <style>
        .nav-menu {
            background: white;
            padding: 15px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .nav-menu a {
            padding: 10px 20px;
            background: #f0f0f0;
            border-radius: 8px;
            text-decoration: none;
            color: #333;
        }
        .nav-menu a:hover {
            background: #667eea;
            color: white;
        }
        .search-box {
            background: white;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        .patient-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .patient-card:hover {
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        .patient-info h3 {
            margin: 0 0 5px 0;
            color: #333;
        }
        .patient-info p {
            margin: 5px 0;
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="nav-menu">
        <a href="index.php?page=doctor_dashboard">🏠 الرئيسية</a>
        <a href="index.php?page=doctor_patients">👥 مرضاي</a>
        <a href="index.php?page=doctor_appointments">📅 مواعيدي</a>
        <a href="index.php?page=doctor_visits">📋 زياراتي</a>
        <a href="index.php?page=doctor_lab_results">🔬 التحاليل</a>
    </div>
    
    <div class="search-box">
        <form method="get" action="index.php">
            <input type="hidden" name="page" value="doctor_patients">
            <input type="text" name="search" placeholder="بحث (اسم، كود، هاتف)..." value="<?= htmlspecialchars($search) ?>" style="width: 300px; padding: 10px;">
            <button type="submit" class="btn">بحث</button>
            <?php if ($search): ?>
                <a href="index.php?page=doctor_patients" class="btn">إلغاء</a>
            <?php endif; ?>
        </form>
    </div>
    
    <h2 style="margin-bottom: 20px;">مرضاي (<?= count($patients) ?>)</h2>
    
    <?php if (empty($patients)): ?>
        <div style="text-align: center; padding: 40px; background: white; border-radius: 12px;">
            <p style="color: #666; font-size: 18px;">لا يوجد مرضى</p>
        </div>
    <?php else: ?>
        <?php foreach ($patients as $patient): ?>
            <div class="patient-card">
                <div class="patient-info">
                    <h3><?= htmlspecialchars($patient['full_name']) ?></h3>
                    <p>كود: <?= htmlspecialchars($patient['patient_code'] ?? '-') ?> | هاتف: <?= htmlspecialchars($patient['phone'] ?? '-') ?></p>
                    <p>عدد الزيارات: <?= $patient['visit_count'] ?> | آخر زيارة: <?= $patient['last_visit_date'] ? date('Y-m-d', strtotime($patient['last_visit_date'])) : '-' ?></p>
                </div>
                <div>
                    <a href="index.php?page=doctor_patients&action=view&id=<?= $patient['id'] ?>" class="btn btn-primary">عرض الملف</a>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</body>
</html>
