<?php
/**
 * نظام الحجز والمواعيد
 */

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

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

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

// معالجة الحذف/الإلغاء
if ($action === 'cancel' && isset($_GET['id'])) {
    if (!($auth instanceof Auth) || !$auth->can('appointments.cancel')) {
        http_response_code(403);
        echo 'غير مسموح بإلغاء المواعيد';
        return;
    }
    $apptId = (int)$_GET['id'];
    if ($apptId > 0) {
        try {
            $stmt = $db->prepare('SELECT * FROM appointments WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$apptId, $tenantId]);
            $appointment = $stmt->fetch();
            
            if ($appointment && $appointment['status'] !== 'cancelled') {
                $reason = trim($_POST['cancellation_reason'] ?? 'تم الإلغاء من قبل المستخدم');
                
                $stmt = $db->prepare(
                    'UPDATE appointments SET 
                     status = "cancelled", 
                     cancellation_reason = ?,
                     cancelled_by = ?,
                     cancelled_at = NOW()
                     WHERE id = ? AND tenant_id = ?'
                );
                $stmt->execute([$reason, $_SESSION['user_id'] ?? null, $apptId, $tenantId]);
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'appointment_cancelled',
                        'appointment',
                        $apptId,
                        json_encode(['status' => $appointment['status']], JSON_UNESCAPED_UNICODE),
                        null,
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['appointments_msg'] = 'تم إلغاء الموعد بنجاح';
            }
        } catch (Throwable $e) {
            $_SESSION['appointments_error'] = 'خطأ في إلغاء الموعد: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=appointments');
    exit;
}

// معالجة تحديث الحالة
if ($action === 'update_status' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $apptId = (int)($_POST['id'] ?? 0);
    $newStatus = trim($_POST['status'] ?? '');
    
    if ($apptId > 0 && in_array($newStatus, ['scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show'])) {
        try {
            $stmt = $db->prepare('SELECT * FROM appointments WHERE id = ? AND tenant_id = ?');
            $stmt->execute([$apptId, $tenantId]);
            $appointment = $stmt->fetch();
            
            if ($appointment) {
                $oldStatus = $appointment['status'];
                $stmt = $db->prepare('UPDATE appointments SET status = ? WHERE id = ? AND tenant_id = ?');
                $stmt->execute([$newStatus, $apptId, $tenantId]);
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'appointment_status_updated',
                        'appointment',
                        $apptId,
                        json_encode(['status' => $oldStatus], JSON_UNESCAPED_UNICODE),
                        json_encode(['status' => $newStatus], JSON_UNESCAPED_UNICODE),
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['appointments_msg'] = 'تم تحديث حالة الموعد بنجاح';
            }
        } catch (Throwable $e) {
            $_SESSION['appointments_error'] = 'خطأ في تحديث الحالة: ' . $e->getMessage();
        }
    }
    header('Location: index.php?page=appointments&action=view&id=' . $apptId);
    exit;
}

// معالجة الإضافة
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!($auth instanceof Auth) || !$auth->can('appointments.create')) {
        http_response_code(403);
        echo 'غير مسموح بإضافة المواعيد';
        return;
    }
    
    $clinicId = (int)($_POST['clinic_id'] ?? 0);
    $doctorId = (int)($_POST['doctor_id'] ?? 0);
    $patientId = (int)($_POST['patient_id'] ?? 0);
    $appointmentDate = trim($_POST['appointment_date'] ?? '');
    $appointmentTime = trim($_POST['appointment_time'] ?? '');
    $appointmentType = $_POST['appointment_type'] ?? 'consultation';
    $notes = trim($_POST['notes'] ?? '');
    
    if ($clinicId > 0 && $doctorId > 0 && $patientId > 0 && $appointmentDate && $appointmentTime) {
        // التحقق من عدم وجود موعد متداخل
        try {
            $stmt = $db->prepare(
                'SELECT id FROM appointments 
                 WHERE doctor_id = ? AND appointment_date = ? AND appointment_time = ? 
                 AND status NOT IN ("cancelled", "no_show") AND tenant_id = ?'
            );
            $stmt->execute([$doctorId, $appointmentDate, $appointmentTime, $tenantId]);
            $conflict = $stmt->fetch();
            
            if ($conflict) {
                $_SESSION['appointments_error'] = 'هذا الوقت محجوز بالفعل. يرجى اختيار وقت آخر.';
                header('Location: index.php?page=appointments&action=create');
                exit;
            }
        } catch (Throwable $e) {}
        
        $appointmentNumber = 'APT-' . date('YmdHis') . rand(100, 999);
        
        try {
            $stmt = $db->prepare(
                'INSERT INTO appointments 
                 (appointment_number, clinic_id, doctor_id, patient_id, appointment_date, appointment_time, 
                  appointment_type, status, notes, created_by, tenant_id)
                 VALUES (?, ?, ?, ?, ?, ?, ?, "scheduled", ?, ?, ?)'
            );
            $stmt->execute([
                $appointmentNumber, $clinicId, $doctorId, $patientId, $appointmentDate, $appointmentTime,
                $appointmentType, $notes, $_SESSION['user_id'] ?? 1, $tenantId
            ]);
            
            $newId = (int)$db->lastInsertId();
            
            if (isset($auditLog)) {
                $auditLog->log(
                    'appointment_created',
                    'appointment',
                    $newId,
                    null,
                    json_encode([
                        'appointment_number' => $appointmentNumber,
                        'doctor_id' => $doctorId,
                        'patient_id' => $patientId,
                        'date' => $appointmentDate
                    ], JSON_UNESCAPED_UNICODE),
                    $_SESSION['user_id'] ?? null
                );
            }
            $_SESSION['appointments_msg'] = 'تم حجز الموعد بنجاح';
            header('Location: index.php?page=appointments&action=view&id=' . $newId);
            exit;
        } catch (Throwable $e) {
            $_SESSION['appointments_error'] = 'خطأ في إضافة الموعد: ' . $e->getMessage();
        }
    } else {
        $_SESSION['appointments_error'] = 'يرجى إدخال جميع البيانات المطلوبة';
    }
    header('Location: index.php?page=appointments&action=create');
    exit;
}

// جلب البيانات
$msg = $_SESSION['appointments_msg'] ?? null;
$error = $_SESSION['appointments_error'] ?? null;
unset($_SESSION['appointments_msg'], $_SESSION['appointments_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'] ?? '');
    $statusFilter = $_GET['status'] ?? '';
    $clinicFilter = !empty($_GET['clinic_id']) ? (int)$_GET['clinic_id'] : 0;
    $doctorFilter = !empty($_GET['doctor_id']) ? (int)$_GET['doctor_id'] : 0;
    
    $where = ['a.tenant_id = ?'];
    $params = [$tenantId];
    
    if ($search !== '') {
        $where[] = '(p.full_name LIKE ? OR p.patient_code LIKE ? OR a.appointment_number LIKE ?)';
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }
    
    if ($dateFilter !== '') {
        $where[] = 'a.appointment_date = ?';
        $params[] = $dateFilter;
    } else {
        // افتراضياً عرض مواعيد اليوم والمستقبل
        $where[] = 'a.appointment_date >= CURDATE()';
    }
    
    if ($statusFilter !== '') {
        $where[] = 'a.status = ?';
        $params[] = $statusFilter;
    }
    
    if ($clinicFilter > 0) {
        $where[] = 'a.clinic_id = ?';
        $params[] = $clinicFilter;
    }
    
    if ($doctorFilter > 0) {
        $where[] = 'a.doctor_id = ?';
        $params[] = $doctorFilter;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT a.*, 
             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
             FROM appointments a
             JOIN patients p ON a.patient_id = p.id
             JOIN clinic_doctors d ON a.doctor_id = d.id
             JOIN clinics c ON a.clinic_id = c.id
             WHERE ' . implode(' AND ', $where) . '
             ORDER BY a.appointment_date, a.appointment_time
             LIMIT 200'
        );
        $stmt->execute($params);
        $appointments = $stmt->fetchAll();
    } catch (Throwable $e) {
        $appointments = [];
    }
    
    ?>
    <div class="page-header">
        <h1>المواعيد</h1>
        <?php if ($auth->can('appointments.create')): ?>
            <a href="index.php?page=appointments&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="appointments">
            <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="status" style="padding: 8px;">
                    <option value="">كل الحالات</option>
                    <option value="scheduled" <?= $statusFilter === 'scheduled' ? 'selected' : '' ?>>مجدول</option>
                    <option value="confirmed" <?= $statusFilter === 'confirmed' ? 'selected' : '' ?>>مؤكد</option>
                    <option value="in_progress" <?= $statusFilter === 'in_progress' ? 'selected' : '' ?>>قيد التنفيذ</option>
                    <option value="completed" <?= $statusFilter === 'completed' ? 'selected' : '' ?>>مكتمل</option>
                    <option value="cancelled" <?= $statusFilter === 'cancelled' ? 'selected' : '' ?>>ملغي</option>
                </select>
                <select name="clinic_id" style="padding: 8px;">
                    <option value="">كل العيادات</option>
                    <?php foreach ($clinics as $clinic): ?>
                        <option value="<?= $clinic['id'] ?>" <?= $clinicFilter == $clinic['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($clinic['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="btn">بحث</button>
                <?php if ($search || $dateFilter || $statusFilter || $clinicFilter): ?>
                    <a href="index.php?page=appointments" 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>
                <th>الإجراءات</th>
            </tr>
        </thead>
        <tbody>
            <?php if (empty($appointments)): ?>
                <tr>
                    <td colspan="9" style="text-align: center; padding: 20px;">لا توجد مواعيد</td>
                </tr>
            <?php else: ?>
                <?php foreach ($appointments as $apt): ?>
                    <tr>
                        <td><?= htmlspecialchars($apt['appointment_number']) ?></td>
                        <td><?= date('Y-m-d', strtotime($apt['appointment_date'])) ?></td>
                        <td><?= date('H:i', strtotime($apt['appointment_time'])) ?></td>
                        <td>
                            <a href="index.php?page=patients&action=view&id=<?= $apt['patient_id'] ?>">
                                <?= htmlspecialchars($apt['patient_name']) ?>
                            </a>
                        </td>
                        <td><?= htmlspecialchars($apt['doctor_name']) ?></td>
                        <td><?= htmlspecialchars($apt['clinic_name']) ?></td>
                        <td>
                            <?php
                            $types = [
                                'consultation' => 'استشارة',
                                'follow_up' => 'متابعة',
                                'emergency' => 'طوارئ',
                                'online' => 'أونلاين'
                            ];
                            echo $types[$apt['appointment_type']] ?? $apt['appointment_type'];
                            ?>
                        </td>
                        <td>
                            <?php
                            $statusColors = [
                                'scheduled' => 'warning',
                                'confirmed' => 'info',
                                'in_progress' => 'primary',
                                'completed' => 'success',
                                'cancelled' => 'danger',
                                'no_show' => 'secondary'
                            ];
                            $statusTexts = [
                                'scheduled' => 'مجدول',
                                'confirmed' => 'مؤكد',
                                'in_progress' => 'قيد التنفيذ',
                                'completed' => 'مكتمل',
                                'cancelled' => 'ملغي',
                                'no_show' => 'لم يحضر'
                            ];
                            $color = $statusColors[$apt['status']] ?? 'secondary';
                            $text = $statusTexts[$apt['status']] ?? $apt['status'];
                            ?>
                            <span class="badge badge-<?= $color ?>"><?= $text ?></span>
                        </td>
                        <td>
                            <a href="index.php?page=appointments&action=view&id=<?= $apt['id'] ?>" class="btn btn-sm">عرض</a>
                            <?php if ($auth->can('appointments.update') && $apt['status'] !== 'completed' && $apt['status'] !== 'cancelled'): ?>
                                <a href="index.php?page=appointments&action=edit&id=<?= $apt['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=appointments');
        exit;
    }
    
    try {
        $stmt = $db->prepare(
            'SELECT a.*, 
             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
             FROM appointments a
             JOIN patients p ON a.patient_id = p.id
             JOIN clinic_doctors d ON a.doctor_id = d.id
             JOIN clinics c ON a.clinic_id = c.id
             WHERE a.id = ? AND a.tenant_id = ?'
        );
        $stmt->execute([$id, $tenantId]);
        $appointment = $stmt->fetch();
    } catch (Throwable $e) {
        $appointment = false;
    }
    
    if (!$appointment) {
        echo '<div class="alert alert-danger">الموعد غير موجود</div>';
        echo '<a href="index.php?page=appointments" class="btn">العودة</a>';
        return;
    }
    
    if ($action === 'edit') {
        // معالجة التعديل
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $appointmentDate = trim($_POST['appointment_date'] ?? '');
            $appointmentTime = trim($_POST['appointment_time'] ?? '');
            $appointmentType = $_POST['appointment_type'] ?? 'consultation';
            $status = $_POST['status'] ?? 'scheduled';
            $notes = trim($_POST['notes'] ?? '');
            
            try {
                $stmt = $db->prepare(
                    'UPDATE appointments SET 
                     appointment_date = ?, appointment_time = ?, appointment_type = ?, 
                     status = ?, notes = ?
                     WHERE id = ? AND tenant_id = ?'
                );
                $stmt->execute([$appointmentDate, $appointmentTime, $appointmentType, $status, $notes, $id, $tenantId]);
                
                if (isset($auditLog)) {
                    $auditLog->log(
                        'appointment_updated',
                        'appointment',
                        $id,
                        json_encode(['appointment_number' => $appointment['appointment_number']], JSON_UNESCAPED_UNICODE),
                        null,
                        $_SESSION['user_id'] ?? null
                    );
                }
                $_SESSION['appointments_msg'] = 'تم تحديث الموعد بنجاح';
                header('Location: index.php?page=appointments&action=view&id=' . $id);
                exit;
            } catch (Throwable $e) {
                $_SESSION['appointments_error'] = 'خطأ في تحديث الموعد: ' . $e->getMessage();
            }
        }
        
        ?>
        <div class="page-header">
            <h1>تعديل الموعد</h1>
            <a href="index.php?page=appointments&action=view&id=<?= $id ?>" class="btn">عودة</a>
        </div>
        
        <form method="post" action="index.php?page=appointments&action=edit&id=<?= $id ?>" class="form-card">
            <h3>معلومات الموعد</h3>
            <div class="form-row">
                <div class="form-group">
                    <label>التاريخ *</label>
                    <input type="date" name="appointment_date" value="<?= $appointment['appointment_date'] ?>" required>
                </div>
                <div class="form-group">
                    <label>الوقت *</label>
                    <input type="time" name="appointment_time" value="<?= date('H:i', strtotime($appointment['appointment_time'])) ?>" required>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label>النوع</label>
                    <select name="appointment_type">
                        <option value="consultation" <?= $appointment['appointment_type'] === 'consultation' ? 'selected' : '' ?>>استشارة</option>
                        <option value="follow_up" <?= $appointment['appointment_type'] === 'follow_up' ? 'selected' : '' ?>>متابعة</option>
                        <option value="emergency" <?= $appointment['appointment_type'] === 'emergency' ? 'selected' : '' ?>>طوارئ</option>
                        <option value="online" <?= $appointment['appointment_type'] === 'online' ? 'selected' : '' ?>>أونلاين</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>الحالة</label>
                    <select name="status">
                        <option value="scheduled" <?= $appointment['status'] === 'scheduled' ? 'selected' : '' ?>>مجدول</option>
                        <option value="confirmed" <?= $appointment['status'] === 'confirmed' ? 'selected' : '' ?>>مؤكد</option>
                        <option value="in_progress" <?= $appointment['status'] === 'in_progress' ? 'selected' : '' ?>>قيد التنفيذ</option>
                        <option value="completed" <?= $appointment['status'] === 'completed' ? 'selected' : '' ?>>مكتمل</option>
                        <option value="cancelled" <?= $appointment['status'] === 'cancelled' ? 'selected' : '' ?>>ملغي</option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label>ملاحظات</label>
                <textarea name="notes" rows="3"><?= htmlspecialchars($appointment['notes'] ?? '') ?></textarea>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">حفظ التغييرات</button>
                <a href="index.php?page=appointments&action=view&id=<?= $id ?>" class="btn">إلغاء</a>
            </div>
        </form>
        <?php
    } else {
        ?>
        <div class="page-header">
            <h1>تفاصيل الموعد</h1>
            <div>
                <?php if ($auth->can('appointments.update') && $appointment['status'] !== 'completed' && $appointment['status'] !== 'cancelled'): ?>
                    <a href="index.php?page=appointments&action=edit&id=<?= $id ?>" class="btn">تعديل</a>
                <?php endif; ?>
                <?php if ($auth->can('appointments.cancel') && $appointment['status'] !== 'cancelled'): ?>
                    <form method="post" action="index.php?page=appointments&action=cancel&id=<?= $id ?>" style="display: inline;" onsubmit="return confirm('هل أنت متأكد من إلغاء هذا الموعد؟');">
                        <button type="submit" class="btn btn-danger">إلغاء الموعد</button>
                    </form>
                <?php endif; ?>
                <a href="index.php?page=appointments" class="btn">العودة</a>
            </div>
        </div>
        
        <div class="info-card">
            <h3>معلومات الموعد</h3>
            <table class="info-table">
                <tr><th>رقم الموعد:</th><td><?= htmlspecialchars($appointment['appointment_number']) ?></td></tr>
                <tr><th>التاريخ:</th><td><?= date('Y-m-d', strtotime($appointment['appointment_date'])) ?></td></tr>
                <tr><th>الوقت:</th><td><?= date('H:i', strtotime($appointment['appointment_time'])) ?></td></tr>
                <tr><th>النوع:</th>
                    <td>
                        <?php
                        $types = ['consultation' => 'استشارة', 'follow_up' => 'متابعة', 'emergency' => 'طوارئ', 'online' => 'أونلاين'];
                        echo $types[$appointment['appointment_type']] ?? $appointment['appointment_type'];
                        ?>
                    </td>
                </tr>
                <tr><th>الحالة:</th>
                    <td>
                        <?php
                        $statusColors = ['scheduled' => 'warning', 'confirmed' => 'info', 'in_progress' => 'primary', 'completed' => 'success', 'cancelled' => 'danger', 'no_show' => 'secondary'];
                        $statusTexts = ['scheduled' => 'مجدول', 'confirmed' => 'مؤكد', 'in_progress' => 'قيد التنفيذ', 'completed' => 'مكتمل', 'cancelled' => 'ملغي', 'no_show' => 'لم يحضر'];
                        $color = $statusColors[$appointment['status']] ?? 'secondary';
                        $text = $statusTexts[$appointment['status']] ?? $appointment['status'];
                        ?>
                        <span class="badge badge-<?= $color ?>"><?= $text ?></span>
                    </td>
                </tr>
                <?php if ($appointment['queue_number']): ?>
                    <tr><th>رقم الطابور:</th><td><?= $appointment['queue_number'] ?></td></tr>
                <?php endif; ?>
                <?php if ($appointment['notes']): ?>
                    <tr><th>ملاحظات:</th><td><?= htmlspecialchars($appointment['notes']) ?></td></tr>
                <?php endif; ?>
            </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=<?= $appointment['patient_id'] ?>"><?= htmlspecialchars($appointment['patient_name']) ?></a></td></tr>
                <tr><th>الكود:</th><td><?= htmlspecialchars($appointment['patient_code']) ?></td></tr>
                <tr><th>الهاتف:</th><td><?= htmlspecialchars($appointment['patient_phone'] ?? '-') ?></td></tr>
            </table>
        </div>
        
        <div class="info-card">
            <h3>الطبيب والعيادة</h3>
            <table class="info-table">
                <tr><th>الطبيب:</th><td><?= htmlspecialchars($appointment['doctor_name']) ?></td></tr>
                <tr><th>الاختصاص:</th><td><?= htmlspecialchars($appointment['doctor_specialty'] ?? '-') ?></td></tr>
                <tr><th>العيادة:</th><td><?= htmlspecialchars($appointment['clinic_name']) ?></td></tr>
            </table>
        </div>
        
        <?php if ($appointment['status'] === 'scheduled' || $appointment['status'] === 'confirmed'): ?>
            <div class="info-card">
                <h3>تغيير الحالة</h3>
                <form method="post" action="index.php?page=appointments&action=update_status">
                    <input type="hidden" name="id" value="<?= $id ?>">
                    <div class="form-row">
                        <div class="form-group">
                            <select name="status" class="form-control">
                                <option value="confirmed" <?= $appointment['status'] === 'confirmed' ? 'selected' : '' ?>>مؤكد</option>
                                <option value="in_progress" <?= $appointment['status'] === 'in_progress' ? 'selected' : '' ?>>قيد التنفيذ</option>
                                <option value="completed" <?= $appointment['status'] === 'completed' ? 'selected' : '' ?>>مكتمل</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">تحديث الحالة</button>
                        </div>
                    </div>
                </form>
            </div>
        <?php endif; ?>
        <?php
    }
}

// إضافة موعد جديد
elseif ($action === 'create') {
    ?>
    <div class="page-header">
        <h1>حجز موعد جديد</h1>
        <a href="index.php?page=appointments" class="btn">العودة</a>
    </div>
    
    <form method="post" action="index.php?page=appointments&action=create" class="form-card">
        <h3>معلومات الموعد</h3>
        <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>
            <small style="color: #666;">يمكنك البحث بالاسم أو الكود أو الهاتف</small>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label>التاريخ *</label>
                <input type="date" name="appointment_date" min="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="form-group">
                <label>الوقت *</label>
                <input type="time" name="appointment_time" required>
            </div>
        </div>
        
        <div class="form-group">
            <label>النوع</label>
            <select name="appointment_type">
                <option value="consultation">استشارة</option>
                <option value="follow_up">متابعة</option>
                <option value="emergency">طوارئ</option>
                <option value="online">أونلاين</option>
            </select>
        </div>
        
        <div class="form-group">
            <label>ملاحظات</label>
            <textarea name="notes" rows="3"></textarea>
        </div>
        
        <div class="form-actions">
            <button type="submit" class="btn btn-primary">حجز الموعد</button>
            <a href="index.php?page=appointments" 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);
            });
        }
    }
    
    // بحث المرضى (يمكن تحسينه لاحقاً)
    document.getElementById('patient_search').addEventListener('input', function() {
        // TODO: إضافة AJAX للبحث عن المرضى
    });
    </script>
    <?php
}
