<?php
/**
 * بوابة حجز موعد مع طبيب — مستقلة تماماً عن بوابة المريض
 * index.php?page=doctor_booking
 * لا تتطلب كود مريض أو رمز بوابة
 */
$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Core/Tenant.php';
require_once __DIR__ . '/../src/Core/TenantPolicy.php';
require_once __DIR__ . '/../src/Core/Session.php';
require_once __DIR__ . '/../src/Core/Csrf.php';
require_once __DIR__ . '/../src/Core/DoctorNotification.php';
$db = \App\Core\Database::getInstance($config['db'])->connection();
\App\Core\Session::start();

/** رقم واتساب بصيغة wa.me (مثل doctor.php) */
function doctor_booking_wa_digits(string $phone): string {
    $p = preg_replace('/\D/', '', trim($phone));
    if (strlen($p) < 8) {
        return '';
    }
    if (strlen($p) === 10 && $p[0] === '0') {
        $p = '964' . substr($p, 1);
    } elseif (strlen($p) === 9 && $p[0] === '7') {
        $p = '964' . $p;
    }
    return $p;
}

$tenantSlug = trim($_GET['tenant'] ?? $_POST['tenant'] ?? '');
$tenant = null;
if ($tenantSlug !== '') {
    try {
        $stmt = $db->prepare('SELECT id, name FROM tenants WHERE slug = ? AND status IN (?, ?)');
        $stmt->execute([$tenantSlug, 'active', 'trial']);
        $tenant = $stmt->fetch();
        if ($tenant) {
            \App\Core\Tenant::setId((int)$tenant['id']);
        }
    } catch (Throwable $e) {}
}
if (!$tenant) {
    try {
        $stmt = $db->query('SELECT id, name FROM tenants WHERE status IN ("active","trial") ORDER BY id ASC LIMIT 1');
        $tenant = $stmt->fetch();
        if ($tenant) \App\Core\Tenant::setId((int)$tenant['id']);
    } catch (Throwable $e) {}
}
$tenantId = (int)(\App\Core\Tenant::id());
$tenantName = ($tenant['name'] ?? null) ?: 'المختبر';

// التحقق من وجود token طبيب في الرابط
$doctorToken = trim($_GET['doctor'] ?? '');
$selectedDoctor = null;
$doctors = [];

if ($doctorToken !== '') {
    // البحث عن الطبيب باستخدام token
    try {
        $db->query('SELECT booking_token FROM doctor_accounts LIMIT 1');
        $stmt = $db->prepare('SELECT da.id, da.doctor_id, da.tenant_id, d.full_name, d.specialty, d.clinic_name
            FROM doctor_accounts da
            JOIN doctors d ON d.id = da.doctor_id AND d.tenant_id = da.tenant_id
            WHERE da.booking_token = ? AND da.is_active = 1');
        $stmt->execute([$doctorToken]);
        $selectedDoctor = $stmt->fetch();
        if ($selectedDoctor) {
            // التأكد من أن tenant_id متطابق
            if ((int)$selectedDoctor['tenant_id'] === $tenantId) {
                $doctors = [$selectedDoctor];
            }
        }
    } catch (Throwable $e) {
        // إذا لم يكن الحقل موجوداً بعد
    }
}

// إذا لم يكن هناك token أو لم يتم العثور على الطبيب، عرض قائمة الأطباء
if (empty($doctors)) {
    try {
        $stmt = $db->prepare('SELECT da.id, da.doctor_id, d.full_name, d.specialty, d.clinic_name
            FROM doctor_accounts da
            JOIN doctors d ON d.id = da.doctor_id AND d.tenant_id = da.tenant_id
            WHERE da.tenant_id = ? AND da.is_active = 1
            ORDER BY d.full_name');
        $stmt->execute([$tenantId]);
        $doctors = $stmt->fetchAll();
    } catch (Throwable $e) {}
}

$msg = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $redirectBack = 'index.php?page=doctor_booking';
    if ($tenantSlug !== '') {
        $redirectBack .= '&tenant=' . urlencode($tenantSlug);
    }
    if ($doctorToken !== '') {
        $redirectBack .= '&doctor=' . urlencode($doctorToken);
    }
    \App\Core\Csrf::enforce($_POST['_csrf'] ?? null, $redirectBack);

    $patientName = trim($_POST['patient_name'] ?? '');
    $phone = preg_replace('/\D/', '', trim($_POST['phone'] ?? ''));
    $doctorAccountId = (int)($_POST['doctor_account_id'] ?? 0);
    $aptDate = trim($_POST['appointment_date'] ?? '');
    $aptTime = trim($_POST['appointment_time'] ?? '09:00');
    $note = trim($_POST['note'] ?? '');
    $postDoctorToken = trim($_POST['doctor'] ?? '');

    // إذا كان هناك token في POST، التحقق منه
    if ($postDoctorToken !== '' && $postDoctorToken === $doctorToken && $selectedDoctor) {
        $doctorAccountId = (int)$selectedDoctor['id'];
    }

    if (strlen($patientName) < 2) {
        $msg = 'أدخل الاسم الكامل.';
    } elseif (strlen($phone) < 8) {
        $msg = 'أدخل رقم هاتف صحيح.';
    } elseif ($doctorAccountId <= 0) {
        $msg = 'اختر الطبيب.';
    } elseif ($selectedDoctor && (int)$doctorAccountId !== (int)$selectedDoctor['id']) {
        $msg = 'الطبيب المحدد غير صحيح.';
    } elseif (!$selectedDoctor && !in_array($doctorAccountId, array_column($doctors, 'id'))) {
        $msg = 'اختر الطبيب.';
    } elseif (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $aptDate) || strtotime($aptDate) < strtotime('today')) {
        $msg = 'اختر تاريخاً صالحاً.';
    } else {
        try {
            $db->query('SELECT id FROM patient_doctor_bookings LIMIT 1');
            $db->query('SELECT id FROM patients LIMIT 1');

            $patientId = null;
            $stmt = $db->prepare('SELECT id FROM patients WHERE (phone = ? OR REPLACE(REPLACE(phone," ",""),"-","") = ?) AND tenant_id = ? LIMIT 1');
            $phoneNorm = preg_replace('/\s|-/', '', $phone);
            $stmt->execute([$phone, $phoneNorm, $tenantId]);
            $p = $stmt->fetch();
            if ($p) {
                $patientId = (int)$p['id'];
                $db->prepare('UPDATE patients SET full_name = ? WHERE id = ?')->execute([$patientName, $patientId]);
            } else {
                [$quotaOk, $quotaErr] = \App\Core\TenantPolicy::monthlyNewPatientQuotaOk($db, $tenantId);
                if (!$quotaOk) {
                    $msg = $quotaErr;
                } else {
                $patientCode = 'P' . date('Ymd') . substr(uniqid(), -4);
                $stmt = $db->prepare('INSERT INTO patients (patient_code, full_name, phone, tenant_id) VALUES (?, ?, ?, ?)');
                $stmt->execute([$patientCode, $patientName, $phone, $tenantId]);
                $patientId = (int)$db->lastInsertId();
                }
            }

            if ($patientId === null) {
                if ($msg === '') {
                    $msg = 'تعذر تسجيل المريض.';
                }
            } else {

            $timeVal = preg_match('/^\d{1,2}:\d{2}(:\d{2})?$/', $aptTime) ? $aptTime : ($aptTime . ':00');
            if (substr_count($timeVal, ':') === 1) $timeVal .= ':00';

            $source = 'patient_portal';
            try {
                $db->query("SHOW COLUMNS FROM patient_doctor_bookings LIKE 'source'");
                $stmt = $db->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='patient_doctor_bookings' AND COLUMN_NAME='source'");
                if ($stmt && strpos($stmt->fetchColumn() ?? '', 'doctor_booking') !== false) {
                    $source = 'doctor_booking';
                }
            } catch (Throwable $e) {}

            $stmt = $db->prepare('INSERT INTO patient_doctor_bookings (patient_id, doctor_account_id, tenant_id, appointment_date, appointment_time, duration_minutes, note, status, source) VALUES (?, ?, ?, ?, ?, 30, ?, ?, ?)');
            $stmt->execute([$patientId, $doctorAccountId, $tenantId, $aptDate, $timeVal, $note ?: null, 'pending', $source]);
            $bookingId = (int)$db->lastInsertId();

            // إرسال إشعار واتساب للطبيب
            try {
                $doctorNotif = new \App\Core\DoctorNotification($db, $config);
                $doctorNotif->notifyAppointmentBooking($doctorAccountId, $patientName, $phone, $aptDate, $timeVal, $note ?: null, $patientId);
            } catch (Throwable $e) {
                error_log('Booking WhatsApp notification: ' . $e->getMessage());
            }

            // إضافة الموعد مباشرة لجدول المواعيد اليومية حتى يظهر للطبيب فوراً
            $doctorAppointmentId = 0;
            try {
                $db->query('SELECT id FROM doctor_appointments LIMIT 1');
                $stmt = $db->prepare('INSERT INTO doctor_appointments (doctor_account_id, patient_id, appointment_date, appointment_time, duration_minutes, note, status) VALUES (?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([$doctorAccountId, $patientId, $aptDate, $timeVal, 30, $note ?: null, 'scheduled']);
                $doctorAppointmentId = (int)$db->lastInsertId();
            } catch (Throwable $e) {}

            // إرسال إشعار للطبيب
            try {
                // إنشاء جدول doctor_alerts إذا لم يكن موجوداً
                try {
                    $db->exec("CREATE TABLE IF NOT EXISTS doctor_alerts (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        doctor_account_id INT NOT NULL,
                        alert_type VARCHAR(50) NOT NULL,
                        title VARCHAR(255) NOT NULL,
                        message TEXT,
                        patient_id INT NULL,
                        order_id INT NULL,
                        priority ENUM('low','normal','high','urgent') DEFAULT 'normal',
                        is_read TINYINT(1) DEFAULT 0,
                        entity_type VARCHAR(50) NULL,
                        entity_id INT NULL,
                        action_url VARCHAR(500) NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        INDEX idx_doctor_account (doctor_account_id),
                        INDEX idx_is_read (is_read),
                        INDEX idx_created_at (created_at),
                        FOREIGN KEY (doctor_account_id) REFERENCES doctor_accounts(id) ON DELETE CASCADE
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
                } catch (Throwable $e) {}
                
                // إنشاء تنبيه في doctor_alerts
                try {
                    $db->query('SELECT id FROM doctor_alerts LIMIT 1');
                    $actionUrl = 'doctor.php?page=appointments&date=' . urlencode($aptDate);
                    $stmt = $db->prepare('INSERT INTO doctor_alerts (doctor_account_id, alert_type, title, message, patient_id, priority, is_read, entity_type, entity_id, action_url, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?, NOW())');
                    $stmt->execute([
                        $doctorAccountId,
                        'appointment',
                        'حجز موعد جديد',
                        'تم حجز موعد جديد من ' . $patientName . ' في ' . $aptDate . ' الساعة ' . substr($timeVal, 0, 5) . ($note ? ' - ' . $note : ''),
                        $patientId,
                        'high',
                        'appointment',
                        $doctorAppointmentId > 0 ? $doctorAppointmentId : null,
                        $actionUrl
                    ]);
                } catch (Throwable $e) {
                    error_log('Error creating booking alert: ' . $e->getMessage());
                }
            } catch (Throwable $e) {
                error_log('Error in booking notification: ' . $e->getMessage());
            }

            $success = true;
            $msg = 'تم إرسال طلب الموعد بنجاح. سنتواصل معك قريباً للتأكيد.';
            $_SESSION['doctor_booking_success'] = $msg;

            // مشاركة واتساب مع الطبيب: جلب رقم الطبيب من قاعدة البيانات + حفظ نص الرسالة في الجلسة (بعد إعادة التوجيه لا يوجد $_POST)
            $waDigits = '';
            $doctorDisplayName = '';
            try {
                $db->query('SELECT phone FROM doctor_accounts LIMIT 1');
                $docStmt = $db->prepare('SELECT da.phone, d.full_name FROM doctor_accounts da INNER JOIN doctors d ON d.id = da.doctor_id AND d.tenant_id = da.tenant_id WHERE da.id = ? AND da.tenant_id = ? LIMIT 1');
                $docStmt->execute([$doctorAccountId, $tenantId]);
                $docRow = $docStmt->fetch();
                if ($docRow) {
                    $doctorDisplayName = trim((string)($docRow['full_name'] ?? ''));
                    $waDigits = doctor_booking_wa_digits((string)($docRow['phone'] ?? ''));
                }
            } catch (Throwable $e) {
            }
            $_SESSION['doctor_booking_share'] = [
                'doctor_account_id' => (int)$doctorAccountId,
                'wa_phone' => $waDigits,
                'doctor_name' => $doctorDisplayName,
                'patient_name' => $patientName,
                'patient_phone' => $phone,
                'apt_date' => $aptDate,
                'apt_time' => substr($timeVal, 0, 5),
                'note' => $note,
                'tenant_name' => $tenantName,
            ];

            $redirect = 'index.php?page=doctor_booking&success=1';
            if ($tenantSlug !== '') $redirect .= '&tenant=' . urlencode($tenantSlug);
            if ($doctorToken !== '') $redirect .= '&doctor=' . urlencode($doctorToken);
            header('Location: ' . $redirect);
            exit;
            }
        } catch (Throwable $e) {
            $msg = 'حدث خطأ. حاول لاحقاً أو تواصل معنا.';
        }
    }
}

$msg = $_SESSION['doctor_booking_success'] ?? $msg;
if (isset($_SESSION['doctor_booking_success'])) {
    unset($_SESSION['doctor_booking_success']);
}
$csrfFlash = \App\Core\Csrf::pullError();
if ($csrfFlash !== null && $csrfFlash !== '') {
    $msg = $csrfFlash;
}
$bookingShare = $_SESSION['doctor_booking_share'] ?? null;
$success = ($msg !== '' && strpos($msg, 'نجاح') !== false) || isset($_GET['success']);
if ($csrfFlash !== null && $csrfFlash !== '') {
    $success = false;
}

$formAction = 'index.php?page=doctor_booking';
if ($tenantSlug !== '') {
    $formAction .= '&tenant=' . urlencode($tenantSlug);
}
if ($doctorToken !== '') {
    $formAction .= '&doctor=' . urlencode($doctorToken);
}

$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/'), '/\\');
if ($baseUrl === '' || $baseUrl === '.') $baseUrl = '';
$baseUrl = $baseUrl ? rtrim($baseUrl, '/') . '/' : './';
?>
<!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="<?php echo htmlspecialchars($baseUrl, ENT_QUOTES); ?>favicon.svg">
    <title>حجز موعد مع طبيب</title>
    <link rel="stylesheet" href="<?php echo htmlspecialchars($baseUrl, ENT_QUOTES); ?>styles.css">
    <link rel="stylesheet" href="<?php echo htmlspecialchars($baseUrl, ENT_QUOTES); ?>portal.css">
    <style>
        .doctor-booking-page { min-height:100vh; display:flex; align-items:center; justify-content:center; background: linear-gradient(145deg, #0f172a 0%, #164e63 50%, #0d9488 100%); padding:24px; }
        .doctor-booking-card { max-width:480px; width:100%; background:rgba(255,255,255,0.98); border-radius:20px; box-shadow:0 25px 50px -12px rgba(0,0,0,0.35); padding:32px; }
        .doctor-booking-title { text-align:center; margin:0 0 8px; font-size:1.75rem; font-weight:800; color:#0f172a; }
        .doctor-booking-subtitle { text-align:center; margin:0 0 24px; color:#64748b; font-size:0.95rem; }
        .doctor-booking-form .portal-form-group { margin-bottom:20px; }
        .doctor-booking-form label { display:block; margin-bottom:8px; font-weight:600; color:#334155; }
        .doctor-booking-form input, .doctor-booking-form select, .doctor-booking-form textarea { width:100%; padding:12px 14px; border:2px solid #e2e8f0; border-radius:10px; font-size:1rem; }
        .doctor-booking-form input:focus, .doctor-booking-form select:focus { border-color:#0d9488; outline:none; }
        .doctor-booking-btn { width:100%; padding:14px; background:linear-gradient(135deg,#0d9488,#0f766e); color:white; border:none; border-radius:10px; font-size:1.1rem; font-weight:700; cursor:pointer; margin-top:8px; }
        .doctor-booking-btn:hover { opacity:0.95; }
        .doctor-booking-back { display:block; text-align:center; margin-top:20px; color:#0d9488; text-decoration:none; font-weight:600; }
        .doctor-booking-back:hover { text-decoration:underline; }
        .doctor-booking-wa-btn { display:inline-flex; align-items:center; justify-content:center; gap:12px; padding:16px 24px; background:#25D366; color:#fff !important; border-radius:14px; text-decoration:none; font-weight:700; font-size:1.05rem; margin-bottom:12px; box-shadow:0 4px 16px rgba(37,211,102,0.45); transition:transform 0.15s, box-shadow 0.15s; border:none; cursor:pointer; }
        .doctor-booking-wa-btn:hover { transform:translateY(-1px); box-shadow:0 6px 20px rgba(37,211,102,0.55); color:#fff; }
        .doctor-booking-wa-btn svg { flex-shrink:0; width:28px; height:28px; fill:currentColor; }
    </style>
</head>
<body class="doctor-booking-page">
    <div class="doctor-booking-card">
        <div style="text-align:center; font-size:2.5rem; margin-bottom:12px;">🩺</div>
        <h1 class="doctor-booking-title">حجز موعد مع طبيب</h1>
        <?php if ($selectedDoctor): ?>
        <p class="doctor-booking-subtitle" style="font-size:1.1rem;font-weight:600;color:#0d9488;">
            د. <?php echo htmlspecialchars($selectedDoctor['full_name'], ENT_QUOTES, 'UTF-8'); ?>
            <?php if (!empty($selectedDoctor['specialty'])): ?>
            <br><span style="font-size:0.9rem;font-weight:400;color:#64748b;"><?php echo htmlspecialchars($selectedDoctor['specialty'], ENT_QUOTES, 'UTF-8'); ?></span>
            <?php endif; ?>
        </p>
        <?php else: ?>
        <p class="doctor-booking-subtitle"><?php echo htmlspecialchars($tenantName, ENT_QUOTES, 'UTF-8'); ?></p>
        <?php endif; ?>

        <?php if ($msg): ?>
        <div class="portal-alert <?php echo $success ? 'portal-alert--success' : 'portal-alert--danger'; ?>" style="margin-bottom:20px;">
            <?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?>
        </div>
        <?php endif; ?>

        <?php if (empty($doctors)): ?>
        <p style="color:#64748b; text-align:center;">لا يوجد أطباء متاحين للحجز حالياً.</p>
        <?php else: ?>
        <?php if (!$success): ?>
        <form method="post" action="<?php echo htmlspecialchars($formAction, ENT_QUOTES, 'UTF-8'); ?>" class="doctor-booking-form">
            <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8'); ?>">
            <?php if ($tenantSlug): ?><input type="hidden" name="tenant" value="<?php echo htmlspecialchars($tenantSlug, ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
            <?php if ($doctorToken): ?><input type="hidden" name="doctor" value="<?php echo htmlspecialchars($doctorToken, ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
            <div class="portal-form-group">
                <label>الاسم الكامل</label>
                <input type="text" name="patient_name" required placeholder="أدخل اسمك الكامل" value="<?php echo htmlspecialchars($_POST['patient_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="portal-form-group">
                <label>رقم الهاتف</label>
                <input type="tel" name="phone" required placeholder="05xxxxxxxx" value="<?php echo htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <?php if ($selectedDoctor): ?>
            <input type="hidden" name="doctor_account_id" value="<?php echo (int)$selectedDoctor['id']; ?>">
            <?php else: ?>
            <div class="portal-form-group">
                <label>الطبيب</label>
                <select name="doctor_account_id" required>
                    <option value="">— اختر الطبيب —</option>
                    <?php foreach ($doctors as $d): ?>
                    <option value="<?php echo (int)$d['id']; ?>" <?php echo (int)($_POST['doctor_account_id'] ?? 0) === (int)$d['id'] ? 'selected' : ''; ?>>
                        د. <?php echo htmlspecialchars($d['full_name'], ENT_QUOTES, 'UTF-8'); ?>
                        <?php if (!empty($d['specialty'])): ?> — <?php echo htmlspecialchars($d['specialty'], ENT_QUOTES, 'UTF-8'); ?><?php endif; ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            <div class="portal-form-group">
                <label>التاريخ</label>
                <input type="date" name="appointment_date" required min="<?php echo date('Y-m-d'); ?>" value="<?php echo htmlspecialchars($_POST['appointment_date'] ?? date('Y-m-d'), ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="portal-form-group">
                <label>الوقت</label>
                <input type="time" name="appointment_time" value="<?php echo htmlspecialchars($_POST['appointment_time'] ?? '09:00', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="portal-form-group">
                <label>ملاحظة (اختياري)</label>
                <input type="text" name="note" placeholder="سبب الزيارة..." value="<?php echo htmlspecialchars($_POST['note'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <button type="submit" class="doctor-booking-btn">إرسال طلب الموعد</button>
        </form>
        <?php else: ?>
        <div style="text-align:center; margin:24px 0;">
            <?php
            $bs = is_array($bookingShare ?? null) ? $bookingShare : null;
            $waUrl = '';
            if ($bs && !empty($bs['wa_phone'])) {
                $waMsg = '';
                $tplBody = '';
                try {
                    $accForTpl = (int)($bs['doctor_account_id'] ?? 0);
                    if ($accForTpl > 0) {
                        $db->query('SELECT id FROM doctor_message_templates LIMIT 1');
                        $tSt = $db->prepare('SELECT body FROM doctor_message_templates WHERE doctor_account_id = ? AND template_key = ? LIMIT 1');
                        $tSt->execute([$accForTpl, 'booking_whatsapp']);
                        $tplBody = trim((string)$tSt->fetchColumn());
                    }
                } catch (Throwable $e) {
                }
                if ($tplBody !== '') {
                    $waMsg = str_replace(
                        ['{doctor_name}', '{patient_name}', '{patient_phone}', '{apt_date}', '{apt_time}', '{note}', '{tenant_name}'],
                        [
                            (string)($bs['doctor_name'] ?? ''),
                            (string)($bs['patient_name'] ?? ''),
                            (string)($bs['patient_phone'] ?? ''),
                            (string)($bs['apt_date'] ?? ''),
                            (string)($bs['apt_time'] ?? ''),
                            (string)($bs['note'] ?? ''),
                            (string)($bs['tenant_name'] ?? ''),
                        ],
                        $tplBody
                    );
                } else {
                    $waMsg = "السلام عليكم";
                    if (!empty($bs['doctor_name'])) {
                        $waMsg .= " د. " . $bs['doctor_name'];
                    }
                    $waMsg .= "\n\nأرسلت طلب حجز موعد :\n\n";
                    $waMsg .= "👤 الاسم: " . ($bs['patient_name'] ?? '') . "\n";
                    $waMsg .= "📱 الهاتف: " . ($bs['patient_phone'] ?? '') . "\n";
                    $waMsg .= "📅 التاريخ: " . ($bs['apt_date'] ?? '') . "\n";
                    $waMsg .= "🕐 الوقت: " . ($bs['apt_time'] ?? '') . "\n";
                    if (!empty(trim((string)($bs['note'] ?? '')))) {
                        $waMsg .= "📝 ملاحظة: " . $bs['note'] . "\n";
                    }
                    $waMsg .= "\nأرجو تأكيد الموعد. شكراً.";
                }
                $waUrl = 'https://wa.me/' . preg_replace('/\D/', '', (string)$bs['wa_phone']) . '?text=' . rawurlencode($waMsg);
            }
            ?>
            <?php if ($waUrl !== ''): ?>
            <p style="font-size:0.95rem;color:#334155;margin:0 0 12px;font-weight:600;">شارك تفاصيل الحجز مع الطبيب على واتساب</p>
            <a href="<?php echo htmlspecialchars($waUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener noreferrer" class="doctor-booking-wa-btn" title="فتح واتساب برسالة جاهزة">
                <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.435 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                إرسال نسخة الحجز للطبيب (واتساب)
            </a>
            <p style="font-size:0.9rem;color:#64748b;margin:0 0 16px;max-width:340px;margin-left:auto;margin-right:auto;line-height:1.5;">يفتح واتساب على رقم الطبيب مع نسخة من بيانات الحجز؛ يمكنك تعديل الرسالة قبل الإرسال.</p>
            <?php elseif ($success): ?>
            <p style="font-size:0.95rem;color:#92400e;background:#fffbeb;border:1px solid #fde68a;border-radius:10px;padding:12px;margin:0 0 16px;">لم يُضبط رقم واتساب للطبيب في الملف — يمكنك التواصل مع المختبر لتأكيد الموعد.</p>
            <?php endif; ?>
            <a href="index.php?page=doctor_booking<?php echo $doctorToken ? '&doctor='.urlencode($doctorToken) : ''; ?><?php echo $tenantSlug ? '&tenant='.urlencode($tenantSlug) : ''; ?>" class="doctor-booking-back">حجز موعد آخر</a>
        </div>
        <?php endif; ?>
        <?php endif; ?>

        <a href="index.php?page=login<?php echo $tenantSlug ? '&tenant='.urlencode($tenantSlug) : ''; ?>" class="doctor-booking-back">← العودة لصفحة الدخول</a>
    </div>
</body>
</html>
