<?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'];

$search = trim($_GET['search'] ?? '');
$statusFilter = $_GET['status'] ?? '';

// جلب التحاليل
$labResults = [];
$where = ['clr.doctor_id = ?', 'clr.tenant_id = ?'];
$params = [$doctorId, $tenantId];

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

if ($statusFilter !== '') {
    $where[] = 'clr.status = ?';
    $params[] = $statusFilter;
}

try {
    $stmt = $db->prepare(
        'SELECT clr.*, 
         p.full_name as patient_name, p.patient_code, p.phone as patient_phone,
         lo.order_number, lo.order_date,
         GROUP_CONCAT(DISTINCT t.name SEPARATOR ", ") as test_names
         FROM clinic_lab_requests clr
         JOIN patients p ON clr.patient_id = p.id
         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 ' . implode(' AND ', $where) . '
         GROUP BY clr.id
         ORDER BY clr.request_date DESC'
    );
    $stmt->execute($params);
    $labResults = $stmt->fetchAll();
} catch (Throwable $e) {
    $labResults = [];
}

// جلب المرفقات (تحاليل مرفقة في الزيارات)
$attachedResults = [];
try {
    $stmt = $db->prepare(
        'SELECT va.*, pv.visit_date, p.full_name as patient_name, p.patient_code
         FROM visit_attachments va
         JOIN patient_visits pv ON va.visit_id = pv.id
         JOIN patients p ON pv.patient_id = p.id
         WHERE pv.doctor_id = ? AND va.attachment_type = "lab_result"
         ORDER BY va.created_at DESC'
    );
    $stmt->execute([$doctorId]);
    $attachedResults = $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>التحاليل الطبية</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;
        }
        .filter-box {
            background: white;
            padding: 20px;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        .result-card {
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            margin-bottom: 15px;
        }
        .result-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 2px solid #f0f0f0;
        }
        .result-info h3 {
            margin: 0 0 5px 0;
            color: #333;
        }
        .result-info p {
            margin: 5px 0;
            color: #666;
            font-size: 14px;
        }
        .section-title {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin: 30px 0 20px 0;
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
    </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="filter-box">
        <form method="get" action="index.php">
            <input type="hidden" name="page" value="doctor_lab_results">
            <div style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                <input type="text" name="search" placeholder="بحث (اسم المريض، كود)..." value="<?= htmlspecialchars($search) ?>" style="padding: 10px; flex: 1; min-width: 200px;">
                <select name="status" style="padding: 10px;">
                    <option value="">كل الحالات</option>
                    <option value="pending" <?= $statusFilter === 'pending' ? 'selected' : '' ?>>معلق</option>
                    <option value="sent" <?= $statusFilter === 'sent' ? 'selected' : '' ?>>تم الإرسال</option>
                    <option value="received" <?= $statusFilter === 'received' ? 'selected' : '' ?>>تم الاستلام</option>
                    <option value="completed" <?= $statusFilter === 'completed' ? 'selected' : '' ?>>مكتمل</option>
                </select>
                <button type="submit" class="btn">بحث</button>
                <?php if ($search || $statusFilter): ?>
                    <a href="index.php?page=doctor_lab_results" class="btn">إلغاء</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
    
    <div class="section-title">🔬 طلبات التحاليل (<?= count($labResults) ?>)</div>
    
    <?php if (empty($labResults)): ?>
        <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 ($labResults as $result): ?>
            <div class="result-card">
                <div class="result-header">
                    <div class="result-info">
                        <h3>👤 <?= htmlspecialchars($result['patient_name']) ?></h3>
                        <p>كود المريض: <?= htmlspecialchars($result['patient_code'] ?? '-') ?> | هاتف: <?= htmlspecialchars($result['patient_phone'] ?? '-') ?></p>
                        <p><strong>التحاليل:</strong> <?= htmlspecialchars($result['test_names'] ?? '-') ?></p>
                        <p>تاريخ الطلب: <?= date('Y-m-d H:i', strtotime($result['request_date'])) ?></p>
                        <?php if ($result['clinical_notes']): ?>
                            <p><strong>ملاحظات سريرية:</strong> <?= htmlspecialchars($result['clinical_notes']) ?></p>
                        <?php endif; ?>
                    </div>
                    <div>
                        <span class="badge badge-<?= $result['status'] === 'completed' ? 'success' : ($result['status'] === 'pending' ? 'warning' : 'info') ?>">
                            <?php
                            $statusText = [
                                'pending' => 'معلق',
                                'sent' => 'تم الإرسال',
                                'received' => 'تم الاستلام',
                                'completed' => 'مكتمل',
                                'cancelled' => 'ملغي'
                            ];
                            echo $statusText[$result['status']] ?? $result['status'];
                            ?>
                        </span>
                    </div>
                </div>
                <div style="display: flex; gap: 10px; margin-top: 15px;">
                    <?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-primary">📄 عرض النتيجة</a>
                    <?php endif; ?>
                    <a href="index.php?page=doctor_patients&action=view&id=<?= $result['patient_id'] ?>" class="btn">عرض ملف المريض</a>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
    
    <?php if (!empty($attachedResults)): ?>
        <div class="section-title">📎 تحاليل مرفقة في الزيارات (<?= count($attachedResults) ?>)</div>
        
        <?php foreach ($attachedResults as $attachment): ?>
            <div class="result-card">
                <div class="result-header">
                    <div class="result-info">
                        <h3>👤 <?= htmlspecialchars($attachment['patient_name']) ?></h3>
                        <p>كود المريض: <?= htmlspecialchars($attachment['patient_code'] ?? '-') ?></p>
                        <p><strong>الملف:</strong> <?= htmlspecialchars($attachment['file_name']) ?></p>
                        <p>تاريخ الرفع: <?= date('Y-m-d H:i', strtotime($attachment['created_at'])) ?></p>
                        <?php if ($attachment['description']): ?>
                            <p><strong>الوصف:</strong> <?= htmlspecialchars($attachment['description']) ?></p>
                        <?php endif; ?>
                    </div>
                </div>
                <div style="margin-top: 15px;">
                    <a href="<?= htmlspecialchars($attachment['file_path']) ?>" target="_blank" class="btn btn-primary">📄 عرض الملف</a>
                    <a href="index.php?page=doctor_patients&action=view&id=<?= $attachment['patient_id'] ?? '' ?>" class="btn">عرض ملف المريض</a>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</body>
</html>
