<?php
/**
 * حجوزات ومواعيد المرضى اليومية
 */
$tenantCond = ' AND o.tenant_id = ' . (int)$tenantId;
$doctorCond = ' AND o.doctor_id = ' . (int)$doctorId;

$selectedDate = trim($_GET['date'] ?? date('Y-m-d'));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $selectedDate)) {
    $selectedDate = date('Y-m-d');
}
$filterStatus = trim($_GET['status'] ?? '');
$viewMode = in_array($_GET['view'] ?? 'table', ['table','cards','timeline']) ? $_GET['view'] : 'table';
$searchQuery = trim($_GET['q'] ?? '');

$appointments = [];
try {
    $db->query('SELECT id FROM doctor_appointments LIMIT 1');
    $sql = 'SELECT a.*, p.full_name AS patient_name, p.patient_code, p.phone, p.date_of_birth, p.gender, p.email
            FROM doctor_appointments a
            JOIN patients p ON p.id = a.patient_id
            WHERE a.doctor_account_id = ? AND a.appointment_date = ?';
    $params = [$doctorAuth->accountId(), $selectedDate];
    if ($searchQuery !== '') {
        $like = '%' . $searchQuery . '%';
        $sql .= ' AND (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ? OR a.note LIKE ?)';
        $params = array_merge($params, [$like, $like, $like, $like]);
    }
    $sql .= ' ORDER BY a.appointment_time ASC';
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $appointments = $stmt->fetchAll();
} catch (Throwable $e) {
    // محاولة جلب من patient_doctor_bookings أيضاً
    try {
        $db->query('SELECT id FROM patient_doctor_bookings LIMIT 1');
        $sql = 'SELECT b.id, b.patient_id, b.appointment_date, b.appointment_time, b.duration_minutes, b.note, b.status,
                p.full_name AS patient_name, p.patient_code, p.phone, p.date_of_birth, p.gender, p.email
                FROM patient_doctor_bookings b
                JOIN patients p ON p.id = b.patient_id
                WHERE b.doctor_account_id = ? AND b.appointment_date = ?';
        $params = [$doctorAuth->accountId(), $selectedDate];
        if ($searchQuery !== '') {
            $like = '%' . $searchQuery . '%';
            $sql .= ' AND (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ? OR b.note LIKE ?)';
            $params = array_merge($params, [$like, $like, $like, $like]);
        }
        $sql .= ' ORDER BY b.appointment_time ASC';
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $bookings = $stmt->fetchAll();
        // تحويل bookings إلى appointments format
        foreach ($bookings as $b) {
            $appointments[] = [
                'id' => $b['id'],
                'patient_id' => $b['patient_id'],
                'appointment_date' => $b['appointment_date'],
                'appointment_time' => $b['appointment_time'],
                'duration_minutes' => $b['duration_minutes'] ?? 30,
                'note' => $b['note'],
                'status' => in_array($b['status'] ?? '', ['scheduled','confirmed','completed','cancelled','no_show'], true) ? $b['status'] : 'scheduled',
                'patient_name' => $b['patient_name'],
                'patient_code' => $b['patient_code'],
                'phone' => $b['phone'],
                'date_of_birth' => $b['date_of_birth'],
                'gender' => $b['gender'],
                'email' => $b['email']
            ];
        }
    } catch (Throwable $e2) {}
}

// إذا جدول doctor_appointments موجود لكن لا توجد بيانات لليوم،
// نجلب حجوزات البوابة كـ fallback حتى لا تظهر شاشة فارغة للطبيب.
if (empty($appointments)) {
    try {
        $db->query('SELECT id FROM patient_doctor_bookings LIMIT 1');
        $sql = 'SELECT b.id, b.patient_id, b.appointment_date, b.appointment_time, b.duration_minutes, b.note, b.status,
                p.full_name AS patient_name, p.patient_code, p.phone, p.date_of_birth, p.gender, p.email
                FROM patient_doctor_bookings b
                JOIN patients p ON p.id = b.patient_id
                WHERE b.doctor_account_id = ? AND b.appointment_date = ?';
        $params = [$doctorAuth->accountId(), $selectedDate];
        if ($searchQuery !== '') {
            $like = '%' . $searchQuery . '%';
            $sql .= ' AND (p.full_name LIKE ? OR p.patient_code LIKE ? OR p.phone LIKE ? OR b.note LIKE ?)';
            $params = array_merge($params, [$like, $like, $like, $like]);
        }
        $sql .= ' ORDER BY b.appointment_time ASC';
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $bookings = $stmt->fetchAll();
        foreach ($bookings as $b) {
            $appointments[] = [
                'id' => $b['id'],
                'patient_id' => $b['patient_id'],
                'appointment_date' => $b['appointment_date'],
                'appointment_time' => $b['appointment_time'],
                'duration_minutes' => $b['duration_minutes'] ?? 30,
                'note' => $b['note'],
                'status' => in_array($b['status'] ?? '', ['scheduled','confirmed','completed','cancelled','no_show'], true) ? $b['status'] : 'scheduled',
                'patient_name' => $b['patient_name'],
                'patient_code' => $b['patient_code'],
                'phone' => $b['phone'],
                'date_of_birth' => $b['date_of_birth'],
                'gender' => $b['gender'],
                'email' => $b['email']
            ];
        }
    } catch (Throwable $e) {}
}

$patientsForAppt = [];
try {
    $db->query('SELECT id FROM patients LIMIT 1');
    $tenantPat = '';
    try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $tenantPat = ' AND p.tenant_id = ' . (int)$tenantId; } catch (Throwable $x) {}
    $doctorFilter = '';
    try {
        $db->query('SELECT default_doctor_id FROM patients LIMIT 1');
        $doctorFilter = ' AND (p.default_doctor_id = ' . (int)$doctorId . ' OR EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id' . $tenantCond . $doctorCond . '))';
    } catch (Throwable $e) {
        $doctorFilter = ' AND EXISTS (SELECT 1 FROM lab_orders o WHERE o.patient_id = p.id' . $tenantCond . $doctorCond . ')';
    }
    $sqlPatients = "SELECT p.id, p.full_name, p.patient_code
                    FROM patients p
                    WHERE 1=1 $tenantPat$doctorFilter
                    ORDER BY p.full_name
                    LIMIT 300";
    $stmt = $db->prepare($sqlPatients);
    $stmt->execute();
    $patientsForAppt = $stmt->fetchAll();
} catch (Throwable $e) {}
if (empty($patientsForAppt)) {
    try {
        $db->query('SELECT id FROM patients LIMIT 1');
        $tenantPat = '';
        try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $tenantPat = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $x) {}
        $stmt = $db->prepare("SELECT id, full_name, patient_code FROM patients WHERE 1=1 $tenantPat ORDER BY full_name LIMIT 300");
        $stmt->execute();
        $patientsForAppt = $stmt->fetchAll();
    } catch (Throwable $e2) {}
}

$timeSlots = [];
for ($h = 8; $h <= 17; $h++) {
    $timeSlots[] = ['value' => sprintf('%02d:00', $h), 'label' => ($h <= 12 ? ($h == 12 ? '12' : $h) : $h - 12) . ':00 ' . ($h < 12 ? 'ص' : 'م')];
    if ($h < 17) $timeSlots[] = ['value' => sprintf('%02d:30', $h), 'label' => ($h <= 12 ? ($h == 12 ? '12' : $h) : $h - 12) . ':30 ' . ($h < 12 ? 'ص' : 'م')];
}

function time12($time24) {
    $parts = explode(':', $time24);
    $h = (int)($parts[0] ?? 0);
    $m = $parts[1] ?? '00';
    $ampm = $h < 12 ? 'ص' : 'م';
    $h12 = ($h == 0 || $h == 12) ? 12 : ($h > 12 ? $h - 12 : $h);
    return $h12 . ':' . $m . ' ' . $ampm;
}

$statusLabels = [
    'scheduled' => ['تأكيد', 'مجدول'],
    'confirmed' => ['تم', 'مؤكد'],
    'completed' => ['—', 'منفذ'],
    'cancelled' => ['—', 'ملغي'],
    'no_show' => ['—', 'لم يحضر'],
];

$today = date('Y-m-d');
$nowTime = date('H:i');
$summary = ['total' => 0, 'scheduled' => 0, 'confirmed' => 0, 'completed' => 0, 'cancelled' => 0, 'no_show' => 0, 'upcoming' => 0, 'overdue' => 0];
$allApts = $appointments;
foreach ($allApts as $a) {
    $summary['total']++;
    $summary[$a['status']] = ($summary[$a['status']] ?? 0) + 1;
    if (in_array($a['status'], ['scheduled','confirmed']) && $selectedDate === $today) {
        $t = substr((string)$a['appointment_time'], 0, 5);
        if ($t > $nowTime) $summary['upcoming']++;
        else $summary['overdue']++;
    }
}

$weekStats = ['total' => 0, 'completed' => 0, 'no_show' => 0];
try {
    $weekStart = date('Y-m-d', strtotime($selectedDate . ' monday this week'));
    $weekEnd = date('Y-m-d', strtotime($weekStart . ' +6 days'));
    $stmt = $db->prepare('SELECT status, COUNT(*) as c FROM doctor_appointments WHERE doctor_account_id = ? AND appointment_date BETWEEN ? AND ? GROUP BY status');
    $stmt->execute([$doctorAuth->accountId(), $weekStart, $weekEnd]);
    while ($r = $stmt->fetch()) {
        $weekStats['total'] += $r['c'];
        if ($r['status'] === 'completed') $weekStats['completed'] = $r['c'];
        if ($r['status'] === 'no_show') $weekStats['no_show'] = $r['c'];
    }
} catch (Throwable $e) {}
$weekStats['attendance'] = $weekStats['total'] > 0 ? round(100 * $weekStats['completed'] / max(1, $weekStats['completed'] + $weekStats['no_show'])) : 100;

$overlaps = [];
$activeApts = array_filter($allApts, function($a){ return in_array($a['status'], ['scheduled','confirmed']); });
foreach ($activeApts as $i => $a1) {
    $s1 = strtotime($selectedDate . ' ' . $a1['appointment_time']);
    $e1 = $s1 + (int)$a1['duration_minutes'] * 60;
    foreach ($activeApts as $j => $a2) {
        if ($i >= $j) continue;
        $s2 = strtotime($selectedDate . ' ' . $a2['appointment_time']);
        $e2 = $s2 + (int)$a2['duration_minutes'] * 60;
        if ($s1 < $e2 && $s2 < $e1) $overlaps[] = [$a1['id'], $a2['id']];
    }
}

$patientReminders = [];
try {
    $db->query('SELECT id FROM doctor_follow_up_reminders LIMIT 1');
    $pids = array_unique(array_column($allApts, 'patient_id'));
    if (!empty($pids)) {
        $placeholders = implode(',', array_fill(0, count($pids), '?'));
        $stmt = $db->prepare("SELECT patient_id, COUNT(*) as c FROM doctor_follow_up_reminders WHERE doctor_account_id = ? AND patient_id IN ($placeholders) AND is_done = 0 GROUP BY patient_id");
        $stmt->execute(array_merge([$doctorAuth->accountId()], $pids));
        while ($r = $stmt->fetch()) $patientReminders[$r['patient_id']] = (int)$r['c'];
    }
} catch (Throwable $e) {}

if ($filterStatus !== '' && isset($statusLabels[$filterStatus])) {
    $appointments = array_filter($appointments, function($a) use ($filterStatus){ return $a['status'] === $filterStatus; });
}

$calendarDays = [];
$dowAr = ['Sun'=>'ح','Mon'=>'ن','Tue'=>'ث','Wed'=>'ر','Thu'=>'خ','Fri'=>'ج','Sat'=>'س'];
for ($i = -7; $i <= 7; $i++) {
    $d = date('Y-m-d', strtotime($selectedDate . " $i days"));
    $calendarDays[] = ['date' => $d, 'label' => date('d', strtotime($d)), 'dow' => $dowAr[date('D', strtotime($d))] ?? '', 'is_today' => $d === $today, 'is_selected' => $d === $selectedDate];
}
?>
<!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">
    <link rel="stylesheet" href="doctor.css">
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content doctor-appointments-page">
    <?php
    $doctorPageTitle = '📅 المواعيد اليومية';
    $doctorPageDesc = 'عرض يومي أو أسبوعي، إدارة الحالات، وتتبع التداخلات والحضور.';
    $doctorPageLinks = [
        ['href' => 'doctor.php?page=booking_link', 'label' => '🔗 رابط الحجز'],
        ['href' => 'doctor.php?page=patients', 'label' => '👥 المرضى'],
        ['href' => 'doctor.php?page=reminders', 'label' => '⏰ التذكيرات'],
    ];
    include __DIR__ . '/_page_intro.php';
    ?>
    <div class="doctor-appointments-header doctor-appointments-header--toolbar-only">
        <div class="doctor-appointments-actions">
            <a href="doctor.php?page=patients" class="btn-secondary">← المرضى</a>
        </div>
    </div>

    <div class="doctor-apt-summary-cards">
        <div class="doctor-apt-summary-card"><span class="doctor-apt-summary-num"><?php echo $summary['total']; ?></span><span class="doctor-apt-summary-label">الكل</span></div>
        <div class="doctor-apt-summary-card doctor-apt-summary-scheduled"><span class="doctor-apt-summary-num"><?php echo $summary['scheduled']; ?></span><span class="doctor-apt-summary-label">مجدول</span></div>
        <div class="doctor-apt-summary-card doctor-apt-summary-confirmed"><span class="doctor-apt-summary-num"><?php echo $summary['confirmed']; ?></span><span class="doctor-apt-summary-label">مؤكد</span></div>
        <div class="doctor-apt-summary-card doctor-apt-summary-completed"><span class="doctor-apt-summary-num"><?php echo $summary['completed']; ?></span><span class="doctor-apt-summary-label">منفذ</span></div>
        <div class="doctor-apt-summary-card doctor-apt-summary-upcoming"><span class="doctor-apt-summary-num"><?php echo $summary['upcoming']; ?></span><span class="doctor-apt-summary-label">قادم</span></div>
        <div class="doctor-apt-summary-card doctor-apt-summary-week"><span class="doctor-apt-summary-num"><?php echo $weekStats['attendance']; ?>%</span><span class="doctor-apt-summary-label">حضور الأسبوع</span></div>
    </div>

    <?php if ($summary['upcoming'] > 0 && $selectedDate === $today): ?>
    <div class="doctor-apt-alert doctor-apt-alert-upcoming">
        <span>🔔 لديك <?php echo $summary['upcoming']; ?> موعد قادم اليوم</span>
    </div>
    <?php endif; ?>
    <?php if ($summary['overdue'] > 0 && $selectedDate === $today): ?>
    <div class="doctor-apt-alert doctor-apt-alert-overdue">
        <span>⏰ <?php echo $summary['overdue']; ?> موعد متأخر في الانتظار</span>
    </div>
    <?php endif; ?>
    <?php if (!empty($overlaps)): ?>
    <div class="doctor-apt-alert doctor-apt-alert-overlap">
        <span>⚠️ تحذير: يوجد تداخل بين بعض المواعيد</span>
    </div>
    <?php endif; ?>

    <div class="doctor-appointments-date-nav card">
        <form method="get" action="doctor.php" class="doctor-date-nav-form" id="doctor-date-form">
            <input type="hidden" name="page" value="appointments">
            <input type="hidden" name="status" value="<?php echo htmlspecialchars($filterStatus, ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="view" value="<?php echo htmlspecialchars($viewMode, ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="q" value="<?php echo htmlspecialchars($searchQuery, ENT_QUOTES, 'UTF-8'); ?>">
            <button type="submit" name="date" value="<?php echo date('Y-m-d', strtotime($selectedDate . ' -1 day')); ?>" class="btn-secondary">← أمس</button>
            <input type="date" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>" class="doctor-date-input" onchange="this.form.submit()">
            <button type="submit" name="date" value="<?php echo date('Y-m-d', strtotime($selectedDate . ' +1 day')); ?>" class="btn-secondary">غداً →</button>
            <button type="submit" name="date" value="<?php echo date('Y-m-d'); ?>" class="btn-primary">اليوم</button>
        </form>
        <div class="doctor-mini-calendar">
            <?php foreach (array_slice($calendarDays, 7, 8) as $cd): ?>
            <a href="doctor.php?page=appointments&date=<?php echo urlencode($cd['date']); ?>&status=<?php echo urlencode($filterStatus); ?>&view=<?php echo urlencode($viewMode); ?>&q=<?php echo urlencode($searchQuery); ?>" class="doctor-mini-cal-day <?php echo $cd['is_today'] ? 'is-today' : ''; ?> <?php echo $cd['is_selected'] ? 'is-selected' : ''; ?>">
                <span class="doctor-mini-cal-num"><?php echo $cd['label']; ?></span>
                <span class="doctor-mini-cal-dow"><?php echo $cd['dow']; ?></span>
            </a>
            <?php endforeach; ?>
        </div>
    </div>

    <?php if (!empty($patientsForAppt)): ?>
    <div class="doctor-add-appointment-card card">
        <h3 class="doctor-add-appointment-title">➕ حجز موعد جديد</h3>
        <form method="post" action="doctor.php?page=appointments&action=add" class="doctor-add-appointment-form">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
            <input type="hidden" name="redirect" value="appointments">
            <input type="hidden" name="appointment_date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
            <div class="doctor-add-appointment-grid">
                <div class="doctor-form-group doctor-form-group-patient">
                    <label for="apt-patient-search">المريض</label>
                    <input type="text" id="apt-patient-search" placeholder="🔍 ابحث عن مريض..." class="doctor-patient-search-input" autocomplete="off">
                    <select name="patient_id" id="apt-patient" required>
                        <option value="" data-search="">-- اختر المريض --</option>
                        <?php foreach ($patientsForAppt as $pr): ?>
                        <option value="<?php echo (int)$pr['id']; ?>" data-search="<?php echo htmlspecialchars(mb_strtolower($pr['full_name'] . ' ' . ($pr['patient_code'] ?? '')), ENT_QUOTES, 'UTF-8'); ?>"><?php echo htmlspecialchars($pr['full_name'] . ' (' . $pr['patient_code'] . ')', ENT_QUOTES, 'UTF-8'); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="doctor-form-group doctor-form-group-time">
                    <label for="apt-time-display">🕐 الوقت</label>
                    <input type="text" id="apt-time-display" class="doctor-time-display" readonly placeholder="اختر الوقت" value="8:00 ص">
                    <input type="hidden" name="appointment_time" id="apt-time" value="08:00" required>
                </div>
                <div class="doctor-form-group">
                    <label for="apt-duration">المدة (دقيقة)</label>
                    <select name="duration_minutes" id="apt-duration">
                        <option value="15">15</option>
                        <option value="30" selected>30</option>
                        <option value="45">45</option>
                        <option value="60">60</option>
                    </select>
                </div>
                <div class="doctor-form-group doctor-form-group-note">
                    <label for="apt-note">ملاحظة</label>
                    <input type="text" name="note" id="apt-note" placeholder="مراجعة، فحص...">
                </div>
                <div class="doctor-add-appointment-submit">
                    <button type="submit" class="btn-primary">حجز الموعد</button>
                </div>
            </div>
        </form>
        <p class="doctor-apt-overlap-hint" id="apt-overlap-warn" style="display:none;margin-top:12px;color:#dc2626;font-size:0.9rem;">⚠️ هذا الوقت يتداخل مع موعد آخر</p>
    </div>
    <?php endif; ?>

    <div id="doctor-edit-apt-overlay" class="doctor-time-picker-overlay" style="z-index:10000">
        <div class="doctor-time-picker-modal doctor-time-picker-spinner" style="max-width:400px">
            <div class="doctor-time-picker-header">تعديل الموعد</div>
            <form method="post" action="doctor.php?page=appointments&action=edit" class="doctor-edit-apt-form">
                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                <input type="hidden" name="apt_id" id="edit-apt-id">
                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                <div class="doctor-time-picker-body">
                    <div class="doctor-time-spinner-row">
                        <label>الوقت</label>
                        <input type="time" name="appointment_time" id="edit-apt-time" required style="flex:1;padding:10px">
                    </div>
                    <div class="doctor-time-spinner-row">
                        <label>المدة</label>
                        <select name="duration_minutes" id="edit-apt-duration">
                            <option value="15">15</option><option value="30">30</option><option value="45">45</option><option value="60">60</option>
                        </select>
                    </div>
                    <div class="doctor-time-spinner-row">
                        <label>ملاحظة</label>
                        <input type="text" name="note" id="edit-apt-note" placeholder="ملاحظة">
                    </div>
                </div>
                <div class="doctor-time-picker-footer">
                    <button type="submit" class="doctor-time-btn doctor-time-set">حفظ</button>
                    <button type="button" class="doctor-time-btn doctor-time-cancel" id="edit-apt-close">إلغاء</button>
                </div>
            </form>
        </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="doctor-appointments-list card">
        <div class="doctor-appointments-list-header">
            <h3 class="doctor-appointments-list-title">📅 مواعيد <?php echo date('Y-m-d', strtotime($selectedDate)); ?></h3>
            <div class="doctor-appointments-list-actions">
                <div class="doctor-apt-filter">
                    <a href="doctor.php?page=appointments&date=<?php echo urlencode($selectedDate); ?>&view=<?php echo urlencode($viewMode); ?>&q=<?php echo urlencode($searchQuery); ?>" class="doctor-filter-chip <?php echo $filterStatus === '' ? 'active' : ''; ?>">الكل</a>
                    <?php foreach ($statusLabels as $sk => $sv): ?>
                    <a href="doctor.php?page=appointments&date=<?php echo urlencode($selectedDate); ?>&status=<?php echo urlencode($sk); ?>&view=<?php echo urlencode($viewMode); ?>&q=<?php echo urlencode($searchQuery); ?>" class="doctor-filter-chip <?php echo $filterStatus === $sk ? 'active' : ''; ?>"><?php echo $sv[1]; ?></a>
                    <?php endforeach; ?>
                </div>
                <form method="get" action="doctor.php" class="doctor-apt-search">
                    <input type="hidden" name="page" value="appointments">
                    <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="status" value="<?php echo htmlspecialchars($filterStatus, ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="hidden" name="view" value="<?php echo htmlspecialchars($viewMode, ENT_QUOTES, 'UTF-8'); ?>">
                    <input type="search" name="q" value="<?php echo htmlspecialchars($searchQuery, ENT_QUOTES, 'UTF-8'); ?>" class="doctor-apt-search-input" placeholder="🔍 بحث بالاسم، الكود، الهاتف...">
                </form>
                <div class="doctor-apt-view-toggle">
                    <a href="doctor.php?page=appointments&date=<?php echo urlencode($selectedDate); ?>&status=<?php echo urlencode($filterStatus); ?>&view=table&q=<?php echo urlencode($searchQuery); ?>" class="doctor-view-btn <?php echo $viewMode === 'table' ? 'active' : ''; ?>" title="جدول">⊞</a>
                    <a href="doctor.php?page=appointments&date=<?php echo urlencode($selectedDate); ?>&status=<?php echo urlencode($filterStatus); ?>&view=cards&q=<?php echo urlencode($searchQuery); ?>" class="doctor-view-btn <?php echo $viewMode === 'cards' ? 'active' : ''; ?>" title="بطاقات">▦</a>
                    <a href="doctor.php?page=appointments&date=<?php echo urlencode($selectedDate); ?>&status=<?php echo urlencode($filterStatus); ?>&view=timeline&q=<?php echo urlencode($searchQuery); ?>" class="doctor-view-btn <?php echo $viewMode === 'timeline' ? 'active' : ''; ?>" title="جدول زمني">▤</a>
                </div>
                <button type="button" class="btn-secondary btn-sm doctor-apt-print" onclick="window.print()">🖨 طباعة</button>
            </div>
        </div>
        <?php if (empty($appointments)): ?>
        <div class="doctor-appointments-empty">
            <p>لا توجد مواعيد لهذا اليوم.</p>
            <p class="doctor-smart-hint">أضف موعداً من النموذج أعلاه.</p>
        </div>
        <?php else:
            $overlapIds = [];
            foreach ($overlaps as $ov) { $overlapIds[$ov[0]] = true; $overlapIds[$ov[1]] = true; }
            $baseUrl = 'doctor.php?page=appointments&date=' . urlencode($selectedDate) . '&status=' . urlencode($filterStatus) . '&view=' . urlencode($viewMode) . '&q=' . urlencode($searchQuery);
        ?>
        <?php if ($viewMode === 'table'): ?>
        <div class="doctor-appointments-table-wrapper">
            <table class="table doctor-appointments-table">
                <thead>
                    <tr>
                        <th>الوقت</th>
                        <th>المريض</th>
                        <th>المدة</th>
                        <th>الحالة</th>
                        <th>ملاحظة</th>
                        <th>إجراء</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($appointments as $a):
                    $statusInfo = $statusLabels[$a['status']] ?? ['—', $a['status']];
                    $timeStr = substr((string)$a['appointment_time'], 0, 5);
                    $timeDisplay = time12($timeStr);
                    $hasReminder = isset($patientReminders[$a['patient_id']]) && $patientReminders[$a['patient_id']] > 0;
                    $isOverlap = isset($overlapIds[$a['id']]);
                    $isLateNow = false;
                    if ($selectedDate === $today && in_array($a['status'], ['scheduled', 'confirmed'], true) && $timeStr < $nowTime) {
                        $isLateNow = true;
                    }
                ?>
                <tr class="doctor-appointment-row doctor-appointment-<?php echo htmlspecialchars($a['status'], ENT_QUOTES, 'UTF-8'); ?> <?php echo $isOverlap ? 'doctor-apt-overlap' : ''; ?> <?php echo $isLateNow ? 'doctor-apt-late' : ''; ?>">
                    <td class="doctor-apt-time">🕐 <?php echo $timeDisplay; ?></td>
                    <td>
                        <div style="display:flex;flex-direction:column;gap:4px;">
                            <div>
                                <a href="doctor.php?page=results&patient_id=<?php echo (int)$a['patient_id']; ?>" style="font-weight:600;"><?php echo htmlspecialchars($a['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                                <?php if ($hasReminder): ?><a href="doctor.php?page=reminders" class="doctor-apt-reminder-badge" title="لديه تذكير">📌</a><?php endif; ?>
                            </div>
                            <div style="font-size:0.85rem;color:#64748b;display:flex;gap:12px;flex-wrap:wrap;">
                                <?php if (!empty($a['patient_code'])): ?>
                                <span>الكود: <?php echo htmlspecialchars($a['patient_code'], ENT_QUOTES, 'UTF-8'); ?></span>
                                <?php endif; ?>
                                <?php if (!empty($a['phone'])): 
                                    $aptMsg = "مرحباً " . ($a['patient_name'] ?? '') . "، تذكير بموعدك في {$selectedDate} الساعة " . substr((string)($a['appointment_time'] ?? ''), 0, 5);
                                    $waUrl = function_exists('doctor_wa_link') ? doctor_wa_link($a['phone'], $aptMsg) : '';
                                ?>
                                <a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $a['phone']), ENT_QUOTES, 'UTF-8'); ?>" title="اتصال" style="color:#0d9488;">📞 <?php echo htmlspecialchars($a['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:6px;">💬</a><?php endif; ?>
                                <?php endif; ?>
                                <?php if (!empty($a['date_of_birth'])): 
                                    $age = date_diff(date_create($a['date_of_birth']), date_create('today'))->y;
                                ?>
                                <span>العمر: <?php echo $age; ?> سنة</span>
                                <?php endif; ?>
                                <?php if (!empty($a['gender'])): ?>
                                <span><?php echo $a['gender'] === 'M' ? 'ذكر' : ($a['gender'] === 'F' ? 'أنثى' : ''); ?></span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </td>
                    <td><?php echo (int)$a['duration_minutes']; ?> د</td>
                    <td><span class="doctor-apt-status doctor-apt-<?php echo $a['status']; ?>"><?php echo $statusInfo[1]; ?></span></td>
                    <td><?php echo htmlspecialchars($a['note'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td class="doctor-apt-actions">
                        <div style="display:flex;gap:6px;flex-wrap:wrap;align-items:center;">
                            <?php if (in_array($a['status'], ['scheduled', 'confirmed'])): ?>
                            <button type="button" class="btn-secondary btn-sm doctor-apt-edit-btn" data-id="<?php echo $a['id']; ?>" data-time="<?php echo $timeStr; ?>" data-duration="<?php echo $a['duration_minutes']; ?>" data-note="<?php echo htmlspecialchars($a['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">✏️ تعديل</button>
                            <?php endif; ?>
                            <form method="post" action="doctor.php?page=appointments" 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="copy">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <input type="hidden" name="to_date" value="<?php echo htmlspecialchars(date('Y-m-d', strtotime($selectedDate . ' +1 day')), ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-secondary btn-sm" title="نسخ لغداً">📋 نسخ</button>
                            </form>
                            <?php if ($a['status'] === 'scheduled'): ?>
                            <form method="post" action="doctor.php?page=appointments" 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="confirm">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-secondary btn-sm">✓ تأكيد</button>
                            </form>
                            <?php endif; ?>
                            <?php if (in_array($a['status'], ['scheduled', 'confirmed'])): ?>
                            <form method="post" action="doctor.php?page=appointments" 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="complete">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-primary btn-sm">✅ تم</button>
                            </form>
                            <form method="post" action="doctor.php?page=appointments" 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="no_show">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-secondary btn-sm">❌ لم يحضر</button>
                            </form>
                            <?php endif; ?>
                            <?php if (!in_array($a['status'], ['cancelled'])): ?>
                            <form method="post" action="doctor.php?page=appointments" style="display:inline;" onsubmit="return confirm('⚠️ هل أنت متأكد من إلغاء الموعد؟');">
                                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                                <input type="hidden" name="action" value="cancel">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="doctor-apt-cancel btn-sm">🗑️ إلغاء</button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php elseif ($viewMode === 'cards'): ?>
        <div class="doctor-apt-cards-grid">
            <?php foreach ($appointments as $a):
                $statusInfo = $statusLabels[$a['status']] ?? ['—', $a['status']];
                $timeStr = substr((string)$a['appointment_time'], 0, 5);
                $timeDisplay = time12($timeStr);
                $hasReminder = isset($patientReminders[$a['patient_id']]) && $patientReminders[$a['patient_id']] > 0;
                $isOverlap = isset($overlapIds[$a['id']]);
                $isLateNow = false;
                if ($selectedDate === $today && in_array($a['status'], ['scheduled', 'confirmed'], true) && $timeStr < $nowTime) {
                    $isLateNow = true;
                }
            ?>
            <div class="doctor-apt-card doctor-apt-<?php echo $a['status']; ?> <?php echo $isOverlap ? 'doctor-apt-overlap' : ''; ?> <?php echo $isLateNow ? 'doctor-apt-late' : ''; ?>">
                <div class="doctor-apt-card-header">
                    <span class="doctor-apt-card-time">🕐 <?php echo $timeDisplay; ?></span>
                    <span class="doctor-apt-status doctor-apt-<?php echo $a['status']; ?>"><?php echo $statusInfo[1]; ?></span>
                </div>
                <div class="doctor-apt-card-body">
                    <a href="doctor.php?page=results&patient_id=<?php echo (int)$a['patient_id']; ?>" class="doctor-apt-card-name"><?php echo htmlspecialchars($a['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                    <?php if ($hasReminder): ?><a href="doctor.php?page=reminders" class="doctor-apt-reminder-badge">📌 تذكير</a><?php endif; ?>
                    <p class="doctor-apt-card-meta"><?php echo (int)$a['duration_minutes']; ?> د · <?php echo htmlspecialchars($a['note'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></p>
                    <?php if (!empty($a['phone'])): 
                                        $waUrl = function_exists('doctor_wa_link') ? doctor_wa_link($a['phone'], 'مرحباً، تذكير بموعدك في ' . $selectedDate . ' ' . substr((string)($a['appointment_time'] ?? ''), 0, 5)) : '';
                                        ?><a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $a['phone']), ENT_QUOTES, 'UTF-8'); ?>" class="doctor-apt-card-phone" title="اتصال">📞</a><?php if ($waUrl): ?><a href="<?php echo htmlspecialchars($waUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" title="واتساب مجاني" style="color:#25D366;">💬</a><?php endif; ?><?php endif; ?>
                </div>
                <div class="doctor-apt-card-actions" style="display:flex;gap:6px;flex-wrap:wrap;align-items:center;">
                    <?php if (in_array($a['status'], ['scheduled', 'confirmed'])): ?>
                    <button type="button" class="btn-secondary btn-sm doctor-apt-edit-btn" data-id="<?php echo $a['id']; ?>" data-time="<?php echo $timeStr; ?>" data-duration="<?php echo $a['duration_minutes']; ?>" data-note="<?php echo htmlspecialchars($a['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">✏️ تعديل</button>
                    <?php endif; ?>
                    <form method="post" action="doctor.php?page=appointments" 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="copy">
                        <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                        <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="to_date" value="<?php echo htmlspecialchars(date('Y-m-d', strtotime($selectedDate . ' +1 day')), ENT_QUOTES, 'UTF-8'); ?>">
                        <button type="submit" class="btn-secondary btn-sm">📋 نسخ</button>
                    </form>
                    <?php if ($a['status'] === 'scheduled'): ?>
                    <form method="post" action="doctor.php?page=appointments" 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="confirm">
                        <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                        <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                        <button type="submit" class="btn-secondary btn-sm">✓ تأكيد</button>
                    </form>
                    <?php endif; ?>
                    <?php if (in_array($a['status'], ['scheduled', 'confirmed'])): ?>
                    <form method="post" action="doctor.php?page=appointments" 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="complete">
                        <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                        <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                        <button type="submit" class="btn-primary btn-sm">✅ تم</button>
                    </form>
                    <form method="post" action="doctor.php?page=appointments" 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="no_show">
                        <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                        <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                        <button type="submit" class="btn-secondary btn-sm">❌ لم يحضر</button>
                    </form>
                    <?php endif; ?>
                    <?php if (!in_array($a['status'], ['cancelled'])): ?>
                    <form method="post" action="doctor.php?page=appointments" style="display:inline;" onsubmit="return confirm('⚠️ هل أنت متأكد من إلغاء الموعد؟');">
                        <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="action" value="cancel">
                        <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                        <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                        <button type="submit" class="doctor-apt-cancel btn-sm">🗑️ إلغاء</button>
                    </form>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="doctor-apt-timeline">
            <?php
            $hours = [];
            for ($h = 8; $h <= 17; $h++) $hours[] = sprintf('%02d:00', $h);
            $slots = [];
            foreach ($appointments as $a) {
                $t = substr((string)$a['appointment_time'], 0, 5);
                $dur = (int)$a['duration_minutes'];
                $startMin = (int)substr($t, 0, 2) * 60 + (int)substr($t, 3, 2);
                $endMin = $startMin + $dur;
                $slots[] = ['apt' => $a, 'start' => $startMin, 'end' => $endMin, 'time' => $t, 'duration' => $dur];
            }
            $dayStart = 8 * 60;
            $dayEnd = 18 * 60;
            $dayTotal = $dayEnd - $dayStart;
            ?>
            <div class="doctor-timeline-ruler">
                <?php for ($h = 8; $h <= 17; $h++): ?>
                <div class="doctor-timeline-hour" style="left:<?php echo 100 * ($h * 60 - $dayStart) / $dayTotal; ?>%"><?php echo $h; ?>:00 <?php echo $h < 12 ? 'ص' : 'م'; ?></div>
                <?php endfor; ?>
            </div>
            <div class="doctor-timeline-slots">
                <?php foreach ($slots as $s):
                    $a = $s['apt'];
                    $statusInfo = $statusLabels[$a['status']] ?? ['—', $a['status']];
                    $top = 100 * ($s['start'] - $dayStart) / $dayTotal;
                    $height = 100 * ($s['duration'] / $dayTotal);
                    $hasReminder = isset($patientReminders[$a['patient_id']]) && $patientReminders[$a['patient_id']] > 0;
                    $isOverlap = isset($overlapIds[$a['id']]);
                    $isLateNow = false;
                    if ($selectedDate === $today && in_array($a['status'], ['scheduled', 'confirmed'], true) && $s['time'] < $nowTime) {
                        $isLateNow = true;
                    }
                ?>
                <div class="doctor-timeline-slot doctor-apt-<?php echo $a['status']; ?> <?php echo $isOverlap ? 'doctor-apt-overlap' : ''; ?> <?php echo $isLateNow ? 'doctor-apt-late' : ''; ?>" style="top:<?php echo $top; ?>%;height:<?php echo $height; ?>%">
                    <div class="doctor-timeline-slot-inner">
                        <span class="doctor-timeline-time"><?php echo time12($s['time']); ?></span>
                        <div style="display:flex;flex-direction:column;gap:4px;">
                            <div>
                                <a href="doctor.php?page=results&patient_id=<?php echo (int)$a['patient_id']; ?>" style="font-weight:600;"><?php echo htmlspecialchars($a['patient_name'], ENT_QUOTES, 'UTF-8'); ?></a>
                                <?php if ($hasReminder): ?><span class="doctor-apt-reminder-badge">📌</span><?php endif; ?>
                                <span class="doctor-apt-status doctor-apt-<?php echo $a['status']; ?>"><?php echo $statusInfo[1]; ?></span>
                            </div>
                            <div style="font-size:0.8rem;color:#64748b;">
                                <?php if (!empty($a['patient_code'])): ?>
                                <span>الكود: <?php echo htmlspecialchars($a['patient_code'], ENT_QUOTES, 'UTF-8'); ?></span>
                                <?php endif; ?>
                                <?php if (!empty($a['phone'])): 
                                    $waUrl = function_exists('doctor_wa_link') ? doctor_wa_link($a['phone'], '') : '';
                                    ?>
                                <a href="tel:<?php echo htmlspecialchars(preg_replace('/[^0-9+]/', '', $a['phone']), ENT_QUOTES, 'UTF-8'); ?>" style="color:#0d9488;">📞 <?php echo htmlspecialchars($a['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:6px;">💬</a><?php endif; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                        <div class="doctor-timeline-slot-actions" style="display:flex;gap:6px;flex-wrap:wrap;align-items:center;">
                            <?php if (in_array($a['status'], ['scheduled', 'confirmed'])): ?>
                            <button type="button" class="btn-secondary btn-sm doctor-apt-edit-btn" data-id="<?php echo $a['id']; ?>" data-time="<?php echo $s['time']; ?>" data-duration="<?php echo $a['duration_minutes']; ?>" data-note="<?php echo htmlspecialchars($a['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">✏️</button>
                            <?php endif; ?>
                            <form method="post" action="doctor.php?page=appointments" 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="copy">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <input type="hidden" name="to_date" value="<?php echo htmlspecialchars(date('Y-m-d', strtotime($selectedDate . ' +1 day')), ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-secondary btn-sm" title="نسخ">📋</button>
                            </form>
                            <?php if ($a['status'] === 'scheduled'): ?>
                            <form method="post" action="doctor.php?page=appointments" 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="confirm">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-secondary btn-sm" title="تأكيد">✓</button>
                            </form>
                            <?php endif; ?>
                            <?php if (in_array($a['status'], ['scheduled', 'confirmed'])): ?>
                            <form method="post" action="doctor.php?page=appointments" 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="complete">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-primary btn-sm" title="تم">✅</button>
                            </form>
                            <form method="post" action="doctor.php?page=appointments" 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="no_show">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="btn-secondary btn-sm" title="لم يحضر">❌</button>
                            </form>
                            <?php endif; ?>
                            <?php if (!in_array($a['status'], ['cancelled'])): ?>
                            <form method="post" action="doctor.php?page=appointments" style="display:inline;" onsubmit="return confirm('⚠️ هل أنت متأكد من إلغاء الموعد؟');">
                                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
                                <input type="hidden" name="action" value="cancel">
                                <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                <input type="hidden" name="date" value="<?php echo htmlspecialchars($selectedDate, ENT_QUOTES, 'UTF-8'); ?>">
                                <button type="submit" class="doctor-apt-cancel btn-sm" title="إلغاء">🗑️</button>
                            </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</main>

<div id="doctor-time-picker-overlay" class="doctor-time-picker-overlay">
    <div class="doctor-time-picker-modal doctor-time-picker-spinner">
        <div class="doctor-time-picker-header">
            <span class="doctor-time-digital" id="doctor-time-display">٨:٠٠</span>
        </div>
        <div class="doctor-time-picker-body">
            <div class="doctor-time-spinner-row">
                <label>الساعة</label>
                <div class="doctor-time-spinner">
                    <input type="text" id="doctor-spinner-hour" class="doctor-spinner-input" inputmode="numeric" maxlength="2" placeholder="٨" dir="ltr">
                    <div class="doctor-spinner-updown">
                        <button type="button" class="doctor-spinner-btn" id="doctor-hour-up">▲</button>
                        <button type="button" class="doctor-spinner-btn" id="doctor-hour-down">▼</button>
                    </div>
                </div>
                <div class="doctor-ampm-inline">
                    <button type="button" class="doctor-ampm-btn" data-ampm="ص">ص</button>
                    <button type="button" class="doctor-ampm-btn" data-ampm="م">م</button>
                </div>
            </div>
            <div class="doctor-time-spinner-row">
                <label>الدقائق</label>
                <div class="doctor-time-spinner">
                    <input type="text" id="doctor-spinner-min" class="doctor-spinner-input" inputmode="numeric" maxlength="2" placeholder="٠٠" dir="ltr">
                    <div class="doctor-spinner-updown">
                        <button type="button" class="doctor-spinner-btn" id="doctor-min-up">▲</button>
                        <button type="button" class="doctor-spinner-btn" id="doctor-min-down">▼</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="doctor-time-picker-footer">
            <button type="button" class="doctor-time-btn doctor-time-set" id="doctor-time-set">تعيين</button>
            <button type="button" class="doctor-time-btn doctor-time-cancel" id="doctor-time-cancel">إلغاء</button>
            <button type="button" class="doctor-time-btn doctor-time-clear" id="doctor-time-clear">محو</button>
        </div>
    </div>
</div>

<script>
(function(){
    var search = document.getElementById('apt-patient-search');
    var select = document.getElementById('apt-patient');
    if (search && select) {
        var container = search.parentElement;
        var suggest = document.createElement('div');
        suggest.id = 'apt-patient-suggest';
        suggest.className = 'doctor-patient-suggest';
        container.appendChild(suggest);

        function buildSuggestions(q) {
            var opts = Array.prototype.slice.call(select.querySelectorAll('option'));
            var items = [];
            opts.forEach(function(opt){
                var val = opt.value || '';
                if (!val) return;
                var txt = (opt.getAttribute('data-search') || opt.textContent || '').toLowerCase();
                if (!q || txt.indexOf(q) >= 0) {
                    items.push({
                        id: val,
                        label: opt.textContent || '',
                        search: txt
                    });
                }
            });
            suggest.innerHTML = '';
            if (!q || items.length === 0) {
                suggest.style.display = 'none';
                return;
            }
            items.slice(0, 8).forEach(function(item){
                var el = document.createElement('button');
                el.type = 'button';
                el.className = 'doctor-patient-suggest-item';
                el.textContent = item.label;
                el.addEventListener('click', function(){
                    select.value = item.id;
                    search.value = item.label;
                    suggest.style.display = 'none';
                });
                suggest.appendChild(el);
            });
            suggest.style.display = items.length > 0 ? 'block' : 'none';
        }

        search.addEventListener('input', function(){
            var q = this.value.trim().toLowerCase();
            buildSuggestions(q);
        });
        search.addEventListener('keydown', function(e){
            if (e.key === 'Enter') {
                e.preventDefault();
                var first = suggest.querySelector('.doctor-patient-suggest-item');
                if (first) first.click();
            }
        });
        document.addEventListener('click', function(e){
            if (!suggest.contains(e.target) && e.target !== search) {
                suggest.style.display = 'none';
            }
        });
    }
})();

(function(){
    var overlay = document.getElementById('doctor-time-picker-overlay');
    var displayInput = document.getElementById('apt-time-display');
    var hiddenInput = document.getElementById('apt-time');
    if (!overlay || !displayInput || !hiddenInput) return;

    var arNums = ['٠','١','٢','٣','٤','٥','٦','٧','٨','٩'];
    var arToEn = {'٠':'0','١':'1','٢':'2','٣':'3','٤':'4','٥':'5','٦':'6','٧':'7','٨':'8','٩':'9'};
    function toAr(n){ return String(n).split('').map(function(c){ return arNums[parseInt(c,10)]||c; }).join(''); }
    function arToNum(str){ return (str||'').replace(/[٠-٩]/g,function(c){ return arToEn[c]||c; }); }
    function to24(h12, ampm){ h12 = h12===0 ? 12 : h12; return ampm==='م' ? (h12===12?12:h12+12) : (h12===12?0:h12); }
    function to12(h24){ return h24===0?12:(h24>12?h24-12:h24); }

    var pickerHour = 8, pickerMin = 0, pickerAmPm = 'ص';
    var hourInput = document.getElementById('doctor-spinner-hour');
    var minInput = document.getElementById('doctor-spinner-min');

    function updatePickerDisplay(){
        var hAr = toAr(pickerHour);
        var mAr = (pickerMin<10?'٠':'') + toAr(pickerMin);
        document.getElementById('doctor-time-display').textContent = hAr + ':' + mAr;
        if (hourInput) hourInput.value = hAr;
        if (minInput) minInput.value = mAr;
        document.querySelectorAll('.doctor-ampm-btn').forEach(function(b){ b.classList.toggle('active', b.getAttribute('data-ampm')===pickerAmPm); });
    }

    displayInput.onclick = function(){ overlay.classList.add('show'); };
    overlay.querySelector('.doctor-time-picker-modal').onclick = function(e){ e.stopPropagation(); };
    overlay.onclick = function(){ if(event.target===overlay) overlay.classList.remove('show'); };

    document.getElementById('doctor-hour-up').onclick = function(){
        pickerHour = pickerHour >= 12 ? 1 : pickerHour + 1;
        updatePickerDisplay();
    };
    document.getElementById('doctor-hour-down').onclick = function(){
        pickerHour = pickerHour <= 1 ? 12 : pickerHour - 1;
        updatePickerDisplay();
    };
    document.getElementById('doctor-min-up').onclick = function(){
        pickerMin = pickerMin >= 55 ? 0 : pickerMin + 5;
        updatePickerDisplay();
    };
    document.getElementById('doctor-min-down').onclick = function(){
        pickerMin = pickerMin <= 0 ? 55 : pickerMin - 5;
        updatePickerDisplay();
    };
    document.querySelectorAll('.doctor-ampm-btn').forEach(function(el){
        el.onclick = function(){ pickerAmPm = this.getAttribute('data-ampm'); updatePickerDisplay(); };
    });

    function applyHourInput(){
        var v = arToNum(hourInput.value.trim());
        var n = parseInt(v, 10);
        if (!isNaN(n) && n >= 1 && n <= 12) { pickerHour = n; updatePickerDisplay(); }
        else { hourInput.value = toAr(pickerHour); }
    }
    function applyMinInput(){
        var v = arToNum(minInput.value.trim());
        var n = parseInt(v, 10);
        if (!isNaN(n) && n >= 0 && n <= 59) { pickerMin = n; updatePickerDisplay(); }
        else { minInput.value = (pickerMin<10?'٠':'') + toAr(pickerMin); }
    }
    if (hourInput) {
        hourInput.addEventListener('blur', applyHourInput);
        hourInput.addEventListener('keydown', function(e){ if (e.key==='Enter'){ e.preventDefault(); applyHourInput(); if (minInput) minInput.focus(); } });
    }
    if (minInput) {
        minInput.addEventListener('blur', applyMinInput);
        minInput.addEventListener('keydown', function(e){ if (e.key==='Enter'){ e.preventDefault(); applyMinInput(); } });
    }

    document.getElementById('doctor-time-set').onclick = function(){
        var h24 = to24(pickerHour, pickerAmPm);
        var val = String(h24).padStart(2,'0') + ':' + String(pickerMin).padStart(2,'0');
        hiddenInput.value = val;
        displayInput.value = pickerHour + ':' + (pickerMin<10?'0':'') + pickerMin + ' ' + pickerAmPm;
        overlay.classList.remove('show');
        hiddenInput.dispatchEvent(new Event('change'));
    };
    document.getElementById('doctor-time-cancel').onclick = function(){ overlay.classList.remove('show'); };
    document.getElementById('doctor-time-clear').onclick = function(){
        pickerHour = 8; pickerMin = 0; pickerAmPm = 'ص';
        updatePickerDisplay();
    };

    var cur = hiddenInput.value || '08:00';
    var p = cur.split(':');
    var h = parseInt(p[0],10);
    pickerHour = to12(h);
    pickerMin = parseInt(p[1],10) || 0;
    pickerAmPm = h >= 12 ? 'م' : 'ص';
    updatePickerDisplay();
})();

(function(){
    var editOverlay = document.getElementById('doctor-edit-apt-overlay');
    var editClose = document.getElementById('edit-apt-close');
    if (editOverlay && editClose) {
        editClose.onclick = function(){ editOverlay.classList.remove('show'); };
        editOverlay.onclick = function(e){ if (e.target === editOverlay) editOverlay.classList.remove('show'); };
        editOverlay.querySelector('.doctor-time-picker-modal').onclick = function(e){ e.stopPropagation(); };
    }
    document.querySelectorAll('.doctor-apt-edit-btn').forEach(function(btn){
        btn.onclick = function(){
            var id = this.getAttribute('data-id');
            var time = this.getAttribute('data-time');
            var duration = this.getAttribute('data-duration');
            var note = this.getAttribute('data-note') || '';
            document.getElementById('edit-apt-id').value = id;
            document.getElementById('edit-apt-time').value = time.length === 5 ? time : time.substring(0,5);
            document.getElementById('edit-apt-duration').value = duration;
            document.getElementById('edit-apt-note').value = note;
            editOverlay.classList.add('show');
        };
    });
})();

(function(){
    var aptTime = document.getElementById('apt-time');
    var aptDuration = document.getElementById('apt-duration');
    var warn = document.getElementById('apt-overlap-warn');
    var apts = <?php
    $aptsJs = [];
    foreach ($activeApts as $a) {
        $t = substr((string)$a['appointment_time'], 0, 5);
        $d = (int)$a['duration_minutes'];
        $sh = (int)substr($t, 0, 2);
        $sm = (int)substr($t, 3, 2);
        $em = $sm + $d;
        $eh = $sh + (int)floor($em / 60);
        $em = $em % 60;
        $aptsJs[] = ['start' => $t, 'end' => sprintf('%02d:%02d', $eh, $em), 'dur' => $d];
    }
    echo json_encode($aptsJs);
    ?>;
    function checkOverlap(){
        if (!warn || !aptTime) return;
        var t = aptTime.value;
        var d = parseInt(aptDuration.value,10) || 30;
        var sh = parseInt(t.substring(0,2),10); var sm = parseInt(t.substring(3,5),10);
        var em = sm + d; var eh = sh + Math.floor(em/60); em = em % 60;
        var end = (eh < 10 ? '0' : '') + eh + ':' + (em < 10 ? '0' : '') + em;
        var conflict = false;
        apts.forEach(function(a){
            if (t < a.end && end > a.start) conflict = true;
        });
        warn.style.display = conflict ? 'block' : 'none';
    }
    if (aptTime && aptDuration && warn) {
        aptTime.addEventListener('change', checkOverlap);
        aptDuration.addEventListener('change', checkOverlap);
        checkOverlap();
    }
})();
</script>
</body>
</html>
