<?php
/**
 * السجلات الطبية الإلكترونية (EMR)
 * Patient Visits Management
 */

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

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

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

// معالجة الحذف
if ($action === 'delete' && isset($_GET['id'])) {
    if (!($auth instanceof Auth) || !$auth->can('visits.delete')) {
        http_response_code(403);
        echo 'غير مسموح بحذف الزيارات';
        return;
    }
    $delId = (int)$_GET['id'];
    if ($delId > 0) {
        try {
            $stmt = $db->prepare('SELECT id FROM patient_visits WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$delId, $tenantId]);
            $visit = $stmt->fetch();
            
            if ($visit) {
                $db->prepare('DELETE FROM patient_visits WHERE id = ? AND tenant_id = ?')->execute([$delId, $tenantId]);
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'visit_deleted',
                        'patient_visit',
                        $delId,
                        json_encode(['id' => $delId], JSON_UNESCAPED_UNICODE),
                        null,
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['visits_msg'] = 'تم حذف الزيارة بنجاح';
            }
        } catch (Throwable $e) {
            $_SESSION['visits_error'] = 'خطأ في حذف الزيارة: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=patient_visits');
    exit;
}

// معالجة التعديل
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('visits.update')) {
        http_response_code(403);
        echo 'غير مسموح بتعديل الزيارات';
        return;
    }
    $editId = (int)($_POST['id'] ?? 0);
    if ($editId > 0) {
        try {
            $stmt = $db->prepare('SELECT * FROM patient_visits WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$editId, $tenantId]);
            $editVisit = $stmt->fetch();
        } catch (Throwable $e) {
            $editVisit = false;
        }
        
        if ($editVisit) {
            $chiefComplaint = trim($_POST['chief_complaint'] ?? '');
            $history = trim($_POST['history_of_present_illness'] ?? '');
            $examination = trim($_POST['physical_examination'] ?? '');
            $diagnosis = trim($_POST['diagnosis'] ?? '');
            $diagnosisCode = trim($_POST['diagnosis_code'] ?? '');
            $treatmentPlan = trim($_POST['treatment_plan'] ?? '');
            $notes = trim($_POST['notes'] ?? '');
            $nextVisitDate = trim($_POST['next_visit_date'] ?? '');
            $visitStatus = $_POST['visit_status'] ?? 'in_progress';
            
            try {
                $stmt = $db->prepare(
                    'UPDATE patient_visits SET 
                     chief_complaint = ?, history_of_present_illness = ?, physical_examination = ?,
                     diagnosis = ?, diagnosis_code = ?, treatment_plan = ?, notes = ?,
                     next_visit_date = ?, visit_status = ?
                     WHERE id = ? AND tenant_id = ?'
                );
                $stmt->execute([
                    $chiefComplaint ?: null, $history ?: null, $examination ?: null,
                    $diagnosis ?: null, $diagnosisCode ?: null, $treatmentPlan ?: null,
                    $notes ?: null, $nextVisitDate ?: null, $visitStatus,
                    $editId, $tenantId
                ]);
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'visit_updated',
                        'patient_visit',
                        $editId,
                        json_encode(['visit_number' => $editVisit['visit_number']], JSON_UNESCAPED_UNICODE),
                        null,
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['visits_msg'] = 'تم تحديث الزيارة بنجاح';
            } catch (Throwable $e) {
                $_SESSION['visits_error'] = 'خطأ في تحديث الزيارة: ' . $e->getMessage();
            }
        }
    }
    header('Location: index.php?page=patient_visits&action=view&id=' . $editId);
    exit;
}

// معالجة الإضافة
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('visits.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة الزيارات';
        return;
    }
    
    $appointmentId = !empty($_POST['appointment_id']) ? (int)$_POST['appointment_id'] : null;
    $clinicId = (int)($_POST['clinic_id'] ?? 0);
    $doctorId = (int)($_POST['doctor_id'] ?? 0);
    $patientId = (int)($_POST['patient_id'] ?? 0);
    $visitDate = trim($_POST['visit_date'] ?? date('Y-m-d H:i:s'));
    $visitType = $_POST['visit_type'] ?? 'consultation';
    $chiefComplaint = trim($_POST['chief_complaint'] ?? '');
    $diagnosis = trim($_POST['diagnosis'] ?? '');
    
    if ($clinicId > 0 && $doctorId > 0 && $patientId > 0) {
        $visitNumber = 'VISIT-' . date('YmdHis') . rand(100, 999);
        
        try {
            $stmt = $db->prepare(
                'INSERT INTO patient_visits 
                 (visit_number, appointment_id, clinic_id, doctor_id, patient_id, visit_date, 
                  visit_type, chief_complaint, diagnosis, visit_status, created_by, tenant_id)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, "in_progress", ?, ?)'
            );
            $stmt->execute([
                $visitNumber, $appointmentId, $clinicId, $doctorId, $patientId, $visitDate,
                $visitType, $chiefComplaint ?: null, $diagnosis ?: null,
                $_SESSION['user_id'] ?? 1, $tenantId
            ]);
            
            $newId = (int)$db->lastInsertId();
            
            // تحديث حالة الموعد إذا كان مرتبطاً
            if ($appointmentId) {
                try {
                    $db->prepare('UPDATE appointments SET status = "in_progress" WHERE id = ?')->execute([$appointmentId]);
                } catch (Throwable $e) {}
            }
            
            if (isset($auditLog)) {
                $auditLog->log(
                    'visit_created',
                    'patient_visit',
                    $newId,
                    null,
                    json_encode([
                        'visit_number' => $visitNumber,
                        'patient_id' => $patientId,
                        'doctor_id' => $doctorId
                    ], JSON_UNESCAPED_UNICODE),
                    $_SESSION['user_id'] ?? null
                );
            }
            $_SESSION['visits_msg'] = 'تم إنشاء الزيارة بنجاح';
            header('Location: index.php?page=patient_visits&action=view&id=' . $newId);
            exit;
        } catch (Throwable $e) {
            $_SESSION['visits_error'] = 'خطأ في إنشاء الزيارة: ' . $e->getMessage();
        }
    } else {
        $_SESSION['visits_error'] = 'يرجى إدخال جميع البيانات المطلوبة';
    }
    header('Location: index.php?page=patient_visits&action=create');
    exit;
}

// جلب البيانات
$msg = $_SESSION['visits_msg'] ?? null;
$error = $_SESSION['visits_error'] ?? null;
unset($_SESSION['visits_msg'], $_SESSION['visits_error']);

// جلب العيادات والأطباء
$clinics = [];
$doctors = [];
try {
    $stmt = $db->prepare('SELECT id, name FROM clinics WHERE tenant_id = ? AND is_active = 1 ORDER BY name');
    $stmt->execute([$tenantId]);
    $clinics = $stmt->fetchAll();
    
    if (!empty($clinics)) {
        $clinicIds = array_column($clinics, 'id');
        $placeholders = implode(',', array_fill(0, count($clinicIds), '?'));
        $stmt = $db->prepare("SELECT id, full_name, clinic_id FROM clinic_doctors WHERE clinic_id IN ($placeholders) AND is_active = 1 ORDER BY full_name");
        $stmt->execute($clinicIds);
        $doctors = $stmt->fetchAll();
    }
} catch (Throwable $e) {}

// عرض القائمة
if ($action === 'index') {
    $search = trim($_GET['search'] ?? '');
    $dateFilter = trim($_GET['date'] ?? '');
    $doctorFilter = !empty($_GET['doctor_id']) ? (int)$_GET['doctor_id'] : 0;
    
    $where = ['v.tenant_id = ?'];
    $params = [$tenantId];
    
    if ($search !== '') {
        $where[] = '(p.full_name LIKE ? OR p.patient_code LIKE ? OR v.visit_number LIKE ?)';
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    if ($dateFilter !== '') {
        $where[] = 'DATE(v.visit_date) = ?';
        $params[] = $dateFilter;
    } else {
        $where[] = 'DATE(v.visit_date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)';
    }
    
    if ($doctorFilter > 0) {
        $where[] = 'v.doctor_id = ?';
        $params[] = $doctorFilter;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT v.*, 
             p.full_name as patient_name, p.patient_code,
             d.full_name as doctor_name, d.specialty as doctor_specialty,
             c.name as clinic_name
             FROM patient_visits v
             JOIN patients p ON v.patient_id = p.id
             JOIN clinic_doctors d ON v.doctor_id = d.id
             JOIN clinics c ON v.clinic_id = c.id
             WHERE ' . implode(' AND ', $where) . '
             ORDER BY v.visit_date DESC
             LIMIT 200'
        );
        $stmt->execute($params);
        $visits = $stmt->fetchAll();
    } catch (Throwable $e) {
        $visits = [];
    }
    
    ?>
    <div class="page-header">
        <h1>الزيارات الطبية</h1>
        <?php if ($auth->can('visits.create')): ?>
            <a href="index.php?page=patient_visits&action=create" class="btn btn-primary">+ زيارة جديدة</a>
        <?php endif; ?>
    </div>
    
    <?php if ($msg): ?>
        <div class="alert alert-success"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <div class="search-box">
        <form method="get" action="index.php">
            <input type="hidden" name="page" value="patient_visits">
            <div style="display: flex; gap: 10px; flex-wrap: wrap; align-items: center;">
                <input type="text" name="search" placeholder="بحث (اسم المريض، كود)..." value="<?= htmlspecialchars($search) ?>" style="width: 200px;">
                <input type="date" name="date" value="<?= htmlspecialchars($dateFilter) ?>" style="padding: 8px;">
                <select name="doctor_id" style="padding: 8px;">
                    <option value="">كل الأطباء</option>
                    <?php foreach ($doctors as $doctor): ?>
                        <option value="<?= $doctor['id'] ?>" <?= $doctorFilter == $doctor['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($doctor['full_name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="btn">بحث</button>
                <?php if ($search || $dateFilter || $doctorFilter): ?>
                    <a href="index.php?page=patient_visits" class="btn">إلغاء</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
    
    <table class="data-table">
        <thead>
            <tr>
                <th>رقم الزيارة</th>
                <th>التاريخ</th>
                <th>المريض</th>
                <th>الطبيب</th>
                <th>العيادة</th>
                <th>التشخيص</th>
                <th>الحالة</th>
                <th>الإجراءات</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($visits)): ?>
                <tr>
                    <td colspan="8" style="text-align: center; padding: 20px;">لا توجد زيارات</td>
                </tr>
            <?php else: ?>
                <?php foreach ($visits as $visit): ?>
                    <tr>
                        <td><?= htmlspecialchars($visit['visit_number']) ?></td>
                        <td><?= date('Y-m-d H:i', strtotime($visit['visit_date'])) ?></td>
                        <td>
                            <a href="index.php?page=patients&action=view&id=<?= $visit['patient_id'] ?>">
                                <?= htmlspecialchars($visit['patient_name']) ?>
                            </a>
                        </td>
                        <td><?= htmlspecialchars($visit['doctor_name']) ?></td>
                        <td><?= htmlspecialchars($visit['clinic_name']) ?></td>
                        <td><?= htmlspecialchars(mb_substr($visit['diagnosis'] ?? '-', 0, 50)) ?></td>
                        <td>
                            <span class="badge badge-<?= $visit['visit_status'] === 'completed' ? 'success' : 'warning' ?>">
                                <?= $visit['visit_status'] === 'completed' ? 'مكتملة' : 'قيد التنفيذ' ?>
                            </span>
                        </td>
                        <td>
                            <a href="index.php?page=patient_visits&action=view&id=<?= $visit['id'] ?>" class="btn btn-sm">عرض</a>
                            <?php if ($auth->can('visits.update')): ?>
                                <a href="index.php?page=patient_visits&action=edit&id=<?= $visit['id'] ?>" class="btn btn-sm">تعديل</a>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
        </tbody>
    </table>
    <?php
}

// عرض/تعديل زيارة
elseif ($action === 'view' || $action === 'edit') {
    $id = (int)($_GET['id'] ?? 0);
    if ($id <= 0) {
        header('Location: index.php?page=patient_visits');
        exit;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT v.*, 
             p.full_name as patient_name, p.patient_code, p.phone as patient_phone,
             d.full_name as doctor_name, d.specialty as doctor_specialty,
             c.name as clinic_name, a.appointment_number
             FROM patient_visits v
             JOIN patients p ON v.patient_id = p.id
             JOIN clinic_doctors d ON v.doctor_id = d.id
             JOIN clinics c ON v.clinic_id = c.id
             LEFT JOIN appointments a ON v.appointment_id = a.id
             WHERE v.id = ? AND v.tenant_id = ?'
        );
        $stmt->execute([$id, $tenantId]);
        $visit = $stmt->fetch();
    } catch (Throwable $e) {
        $visit = false;
    }
    
    if (!$visit) {
        echo '<div class="alert alert-danger">الزيارة غير موجودة</div>';
        echo '<a href="index.php?page=patient_visits" class="btn">العودة</a>';
        return;
    }
    
    // جلب الوصفات
    $prescriptions = [];
    try {
        $stmt = $db->prepare('SELECT * FROM prescriptions WHERE visit_id = ? ORDER BY prescription_date DESC');
        $stmt->execute([$id]);
        $prescriptions = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب المرفقات
    $attachments = [];
    try {
        $stmt = $db->prepare('SELECT * FROM visit_attachments WHERE visit_id = ? ORDER BY created_at DESC');
        $stmt->execute([$id]);
        $attachments = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    // جلب طلبات التحاليل المرتبطة
    $labRequests = [];
    try {
        $stmt = $db->prepare(
            'SELECT clr.*, GROUP_CONCAT(t.name SEPARATOR ", ") as test_names
             FROM clinic_lab_requests clr
             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.visit_id = ?
             GROUP BY clr.id
             ORDER BY clr.request_date DESC'
        );
        $stmt->execute([$id]);
        $labRequests = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    if ($action === 'edit') {
        ?>
        <div class="page-header">
            <h1>تعديل الزيارة</h1>
            <a href="index.php?page=patient_visits&action=view&id=<?= $id ?>" class="btn">عودة</a>
        </div>
        
        <form method="post" action="index.php?page=patient_visits&action=edit" class="form-card">
            <input type="hidden" name="id" value="<?= $id ?>">
            
            <h3>معلومات الزيارة</h3>
            <div class="form-group">
                <label>الشكوى الرئيسية</label>
                <textarea name="chief_complaint" rows="3"><?= htmlspecialchars($visit['chief_complaint'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group">
                <label>تاريخ المرض الحالي</label>
                <textarea name="history_of_present_illness" rows="3"><?= htmlspecialchars($visit['history_of_present_illness'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group">
                <label>الفحص السريري</label>
                <textarea name="physical_examination" rows="3"><?= htmlspecialchars($visit['physical_examination'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group">
                <label>التشخيص</label>
                <textarea name="diagnosis" rows="2"><?= htmlspecialchars($visit['diagnosis'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group">
                <label>كود التشخيص (ICD-10)</label>
                <input type="text" name="diagnosis_code" value="<?= htmlspecialchars($visit['diagnosis_code'] ?? '') ?>" placeholder="مثل: I10">
            </div>
            
            <div class="form-group">
                <label>خطة العلاج</label>
                <textarea name="treatment_plan" rows="3"><?= htmlspecialchars($visit['treatment_plan'] ?? '') ?></textarea>
            </div>
            
            <div class="form-group">
                <label>ملاحظات</label>
                <textarea name="notes" rows="2"><?= htmlspecialchars($visit['notes'] ?? '') ?></textarea>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>موعد الزيارة القادمة</label>
                    <input type="date" name="next_visit_date" value="<?= $visit['next_visit_date'] ? date('Y-m-d', strtotime($visit['next_visit_date'])) : '' ?>">
                </div>
                <div class="form-group">
                    <label>حالة الزيارة</label>
                    <select name="visit_status">
                        <option value="in_progress" <?= $visit['visit_status'] === 'in_progress' ? 'selected' : '' ?>>قيد التنفيذ</option>
                        <option value="completed" <?= $visit['visit_status'] === 'completed' ? 'selected' : '' ?>>مكتملة</option>
                        <option value="cancelled" <?= $visit['visit_status'] === 'cancelled' ? 'selected' : '' ?>>ملغية</option>
                    </select>
                </div>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                <a href="index.php?page=patient_visits&action=view&id=<?= $id ?>" class="btn">إلغاء</a>
            </div>
        </form>
        <?php
    } else {
        ?>
        <div class="page-header">
            <h1>تفاصيل الزيارة</h1>
            <div>
                <?php if ($auth->can('visits.update')): ?>
                    <a href="index.php?page=patient_visits&action=edit&id=<?= $id ?>" class="btn">تعديل</a>
                <?php endif; ?>
                <?php if ($auth->can('prescriptions.create')): ?>
                    <a href="index.php?page=prescriptions&action=create&visit_id=<?= $id ?>" class="btn btn-primary">+ إضافة وصفة</a>
                <?php endif; ?>
                <a href="index.php?page=patient_visits" class="btn">العودة</a>
            </div>
        </div>
        
        <div class="info-card">
            <h3>معلومات الزيارة</h3>
            <table class="info-table">
                <tr><th>رقم الزيارة:</th><td><?= htmlspecialchars($visit['visit_number']) ?></td></tr>
                <tr><th>التاريخ:</th><td><?= date('Y-m-d H:i', strtotime($visit['visit_date'])) ?></td></tr>
                <tr><th>النوع:</th>
                    <td>
                        <?php
                        $types = ['consultation' => 'استشارة', 'follow_up' => 'متابعة', 'emergency' => 'طوارئ', 'lab_follow_up' => 'متابعة تحاليل'];
                        echo $types[$visit['visit_type']] ?? $visit['visit_type'];
                        ?>
                    </td>
                </tr>
                <?php if ($visit['appointment_number']): ?>
                    <tr><th>الموعد المرتبط:</th><td><?= htmlspecialchars($visit['appointment_number']) ?></td></tr>
                <?php endif; ?>
                <tr><th>الحالة:</th>
                    <td>
                        <span class="badge badge-<?= $visit['visit_status'] === 'completed' ? 'success' : 'warning' ?>">
                            <?= $visit['visit_status'] === 'completed' ? 'مكتملة' : 'قيد التنفيذ' ?>
                        </span>
                    </td>
                </tr>
            </table>
        </div>
        
        <div class="info-card">
            <h3>المريض</h3>
            <table class="info-table">
                <tr><th>الاسم:</th><td><a href="index.php?page=patients&action=view&id=<?= $visit['patient_id'] ?>"><?= htmlspecialchars($visit['patient_name']) ?></a></td></tr>
                <tr><th>الكود:</th><td><?= htmlspecialchars($visit['patient_code']) ?></td></tr>
                <tr><th>الهاتف:</th><td><?= htmlspecialchars($visit['patient_phone'] ?? '-') ?></td></tr>
            </table>
        </div>
        
        <div class="info-card">
            <h3>الطبيب والعيادة</h3>
            <table class="info-table">
                <tr><th>الطبيب:</th><td><?= htmlspecialchars($visit['doctor_name']) ?></td></tr>
                <tr><th>الاختصاص:</th><td><?= htmlspecialchars($visit['doctor_specialty'] ?? '-') ?></td></tr>
                <tr><th>العيادة:</th><td><?= htmlspecialchars($visit['clinic_name']) ?></td></tr>
            </table>
        </div>
        
        <?php if ($visit['chief_complaint']): ?>
            <div class="info-card">
                <h3>الشكوى الرئيسية</h3>
                <p><?= nl2br(htmlspecialchars($visit['chief_complaint'])) ?></p>
            </div>
        <?php endif; ?>
        
        <?php if ($visit['history_of_present_illness']): ?>
            <div class="info-card">
                <h3>تاريخ المرض الحالي</h3>
                <p><?= nl2br(htmlspecialchars($visit['history_of_present_illness'])) ?></p>
            </div>
        <?php endif; ?>
        
        <?php if ($visit['physical_examination']): ?>
            <div class="info-card">
                <h3>الفحص السريري</h3>
                <p><?= nl2br(htmlspecialchars($visit['physical_examination'])) ?></p>
            </div>
        <?php endif; ?>
        
        <?php if ($visit['diagnosis']): ?>
            <div class="info-card">
                <h3>التشخيص</h3>
                <p><?= nl2br(htmlspecialchars($visit['diagnosis'])) ?></p>
                <?php if ($visit['diagnosis_code']): ?>
                    <p><strong>كود التشخيص:</strong> <?= htmlspecialchars($visit['diagnosis_code']) ?></p>
                <?php endif; ?>
            </div>
        <?php endif; ?>
        
        <?php if ($visit['treatment_plan']): ?>
            <div class="info-card">
                <h3>خطة العلاج</h3>
                <p><?= nl2br(htmlspecialchars($visit['treatment_plan'])) ?></p>
            </div>
        <?php endif; ?>
        
        <?php if ($visit['notes']): ?>
            <div class="info-card">
                <h3>ملاحظات</h3>
                <p><?= nl2br(htmlspecialchars($visit['notes'])) ?></p>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($prescriptions)): ?>
            <div class="info-card">
                <h3>الوصفات الطبية (<?= count($prescriptions) ?>)</h3>
                <?php foreach ($prescriptions as $prescription): ?>
                    <div style="padding: 15px; border-bottom: 1px solid #f0f0f0; margin-bottom: 10px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <strong>رقم الوصفة:</strong> <?= htmlspecialchars($prescription['prescription_number']) ?><br>
                                <strong>التاريخ:</strong> <?= date('Y-m-d H:i', strtotime($prescription['prescription_date'])) ?><br>
                                <span class="badge badge-<?= $prescription['is_dispensed'] ? 'success' : 'warning' ?>">
                                    <?= $prescription['is_dispensed'] ? 'تم الصرف' : 'لم يتم الصرف' ?>
                                </span>
                            </div>
                            <div>
                                <a href="index.php?page=prescriptions&action=view&id=<?= $prescription['id'] ?>" class="btn btn-sm">عرض</a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($labRequests)): ?>
            <div class="info-card">
                <h3>🔬 طلبات التحاليل (<?= count($labRequests) ?>)</h3>
                <?php foreach ($labRequests as $labReq): ?>
                    <div style="padding: 15px; border-bottom: 1px solid #f0f0f0; margin-bottom: 10px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <strong>التحاليل:</strong> <?= htmlspecialchars($labReq['test_names'] ?? '-') ?><br>
                                <strong>التاريخ:</strong> <?= date('Y-m-d H:i', strtotime($labReq['request_date'])) ?><br>
                                <span class="badge badge-<?= $labReq['status'] === 'completed' ? 'success' : 'warning' ?>">
                                    <?= $labReq['status'] === 'completed' ? 'مكتمل' : 'قيد المعالجة' ?>
                                </span>
                            </div>
                            <div>
                                <?php if ($labReq['status'] === 'completed' && $labReq['lab_order_id']): ?>
                                    <a href="index.php?page=print_result&order=<?= $labReq['lab_order_id'] ?>" target="_blank" class="btn btn-sm">عرض النتيجة</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($attachments)): ?>
            <div class="info-card">
                <h3>📎 المرفقات (<?= count($attachments) ?>)</h3>
                <?php foreach ($attachments as $attachment): ?>
                    <div style="padding: 10px; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 10px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <strong><?= htmlspecialchars($attachment['file_name']) ?></strong><br>
                                <small style="color: #666;"><?= date('Y-m-d H:i', strtotime($attachment['created_at'])) ?></small>
                                <?php if ($attachment['description']): ?>
                                    <br><small><?= htmlspecialchars($attachment['description']) ?></small>
                                <?php endif; ?>
                            </div>
                            <div>
                                <a href="<?= htmlspecialchars($attachment['file_path']) ?>" target="_blank" class="btn btn-sm">عرض</a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <?php
    }
}

// إضافة زيارة جديدة
elseif ($action === 'create') {
    // جلب المواعيد القادمة
    $appointments = [];
    try {
        $stmt = $db->prepare(
            'SELECT a.*, p.full_name as patient_name 
             FROM appointments a
             JOIN patients p ON a.patient_id = p.id
             WHERE a.status IN ("scheduled", "confirmed") AND a.tenant_id = ?
             ORDER BY a.appointment_date, a.appointment_time
             LIMIT 50'
        );
        $stmt->execute([$tenantId]);
        $appointments = $stmt->fetchAll();
    } catch (Throwable $e) {}
    
    ?>
    <div class="page-header">
        <h1>زيارة جديدة</h1>
        <a href="index.php?page=patient_visits" class="btn">العودة</a>
    </div>
    
    <form method="post" action="index.php?page=patient_visits&action=create" class="form-card">
        <h3>معلومات الزيارة</h3>
        <div class="form-group">
            <label>الموعد المرتبط (اختياري)</label>
            <select name="appointment_id">
                <option value="">-- بدون موعد --</option>
                <?php foreach ($appointments as $apt): ?>
                    <option value="<?= $apt['id'] ?>">
                        <?= date('Y-m-d H:i', strtotime($apt['appointment_date'] . ' ' . $apt['appointment_time'])) ?> - 
                        <?= htmlspecialchars($apt['patient_name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="form-group">
            <label>العيادة *</label>
            <select name="clinic_id" id="clinic_select" required onchange="loadDoctors(this.value)">
                <option value="">-- اختر العيادة --</option>
                <?php foreach ($clinics as $clinic): ?>
                    <option value="<?= $clinic['id'] ?>"><?= htmlspecialchars($clinic['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        
        <div class="form-group">
            <label>الطبيب *</label>
            <select name="doctor_id" id="doctor_select" required>
                <option value="">-- اختر العيادة أولاً --</option>
            </select>
        </div>
        
        <div class="form-group">
            <label>المريض *</label>
            <input type="text" id="patient_search" placeholder="ابحث عن المريض..." style="width: 100%; padding: 8px; margin-bottom: 10px;">
            <select name="patient_id" id="patient_select" required>
                <option value="">-- اختر المريض --</option>
            </select>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label>تاريخ ووقت الزيارة *</label>
                <input type="datetime-local" name="visit_date" value="<?= date('Y-m-d\TH:i') ?>" required>
            </div>
            <div class="form-group">
                <label>نوع الزيارة</label>
                <select name="visit_type">
                    <option value="consultation">استشارة</option>
                    <option value="follow_up">متابعة</option>
                    <option value="emergency">طوارئ</option>
                    <option value="lab_follow_up">متابعة تحاليل</option>
                </select>
            </div>
        </div>
        
        <div class="form-group">
            <label>الشكوى الرئيسية</label>
            <textarea name="chief_complaint" rows="3"></textarea>
        </div>
        
        <div class="form-group">
            <label>التشخيص</label>
            <textarea name="diagnosis" rows="2"></textarea>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">إنشاء الزيارة</button>
            <a href="index.php?page=patient_visits" class="btn">إلغاء</a>
        </div>
    </form>
    
    <script>
    const doctors = <?= json_encode($doctors) ?>;
    
    function loadDoctors(clinicId) {
        const select = document.getElementById('doctor_select');
        select.innerHTML = '<option value="">-- اختر الطبيب --</option>';
        
        if (clinicId) {
            const clinicDoctors = doctors.filter(d => d.clinic_id == clinicId);
            clinicDoctors.forEach(doctor => {
                const option = document.createElement('option');
                option.value = doctor.id;
                option.textContent = doctor.full_name;
                select.appendChild(option);
            });
        }
    }
    </script>
    <?php
}
