<?php
/**
 * إدارة رابط حجز المواعيد للطبيب
 * يسمح للطبيب بإنشاء رابط حجز خاص به مع QR code
 */

// إنشاء أو تحديث رابط الحجز
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_GET['action'] ?? '') === 'generate') {
    try {
        $db->query('SELECT booking_token FROM doctor_accounts LIMIT 1');
        $token = bin2hex(random_bytes(16));
        $stmt = $db->prepare('UPDATE doctor_accounts SET booking_token = ? WHERE id = ?');
        $stmt->execute([$token, $doctorAuth->accountId()]);
        $_SESSION['doctor_msg'] = 'تم إنشاء رابط الحجز بنجاح.';
        header('Location: doctor.php?page=booking_link');
        exit;
    } catch (Throwable $e) {
        // إذا لم يكن الحقل موجوداً، ننفذ migration
        try {
            $db->exec("ALTER TABLE doctor_accounts ADD COLUMN booking_token VARCHAR(64) NULL UNIQUE AFTER is_active");
            $db->exec("ALTER TABLE doctor_accounts ADD INDEX idx_booking_token (booking_token)");
            $token = bin2hex(random_bytes(16));
            $stmt = $db->prepare('UPDATE doctor_accounts SET booking_token = ? WHERE id = ?');
            $stmt->execute([$token, $doctorAuth->accountId()]);
            $_SESSION['doctor_msg'] = 'تم إنشاء رابط الحجز بنجاح.';
        } catch (Throwable $e2) {
            $_SESSION['doctor_error'] = 'فشل إنشاء الرابط: ' . $e2->getMessage();
        }
        header('Location: doctor.php?page=booking_link');
        exit;
    }
}

// جلب معلومات الطبيب والرابط
$doctorInfo = null;
$bookingToken = null;
$bookingLink = '';
$qrCodeUrl = '';
$whatsappQrUrl = '';

try {
    $db->query('SELECT booking_token FROM doctor_accounts LIMIT 1');
    $stmt = $db->prepare('SELECT da.booking_token, da.phone, d.full_name, d.specialty, d.clinic_name, d.phone AS doc_phone, t.slug AS tenant_slug 
        FROM doctor_accounts da 
        JOIN doctors d ON d.id = da.doctor_id 
        JOIN tenants t ON t.id = da.tenant_id 
        WHERE da.id = ?');
    $stmt->execute([$doctorAuth->accountId()]);
    $doctorInfo = $stmt->fetch();
    $bookingToken = $doctorInfo['booking_token'] ?? null;
    
    if ($bookingToken) {
        $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost');
        $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/index.php'));
        if ($scriptDir === '/' || $scriptDir === '\\') $scriptDir = '';
        
        $bookingLink = rtrim($baseUrl . $scriptDir, '/') . '/index.php?page=doctor_booking&doctor=' . urlencode($bookingToken);
        if (!empty($doctorInfo['tenant_slug']) && $doctorInfo['tenant_slug'] !== 'main') {
            $bookingLink .= '&tenant=' . urlencode($doctorInfo['tenant_slug']);
        }
        
        // إنشاء QR code للحجز
        $qrCodeUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . urlencode($bookingLink);
        
        // QR واتساب - رابط فتح المحادثة (مجاني، يعمل بالخلفية)
        $waPhone = trim((string)($doctorInfo['phone'] ?? $doctorInfo['doc_phone'] ?? ''));
        if ($waPhone !== '') {
            $waPhone = preg_replace('/\D/', '', $waPhone);
            if (strlen($waPhone) === 10 && $waPhone[0] === '0') $waPhone = '964' . substr($waPhone, 1);
            elseif (strlen($waPhone) === 9 && $waPhone[0] === '7') $waPhone = '964' . $waPhone;
            if (strlen($waPhone) >= 9) {
                $waLink = 'https://wa.me/' . $waPhone;
                $whatsappQrUrl = 'https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=' . urlencode($waLink);
            }
        }
    }
} catch (Throwable $e) {
    // إذا لم يكن الحقل موجوداً
    try {
        $db->exec("ALTER TABLE doctor_accounts ADD COLUMN booking_token VARCHAR(64) NULL UNIQUE AFTER is_active");
        $db->exec("ALTER TABLE doctor_accounts ADD INDEX idx_booking_token (booking_token)");
    } catch (Throwable $e2) {}
}

// إحصائيات الحجوزات
$bookingStats = ['total' => 0, 'pending' => 0, 'confirmed' => 0, 'completed' => 0, 'today' => 0];
try {
    $db->query('SELECT id FROM patient_doctor_bookings LIMIT 1');
    $stmt = $db->prepare('SELECT COUNT(*) FROM patient_doctor_bookings WHERE doctor_account_id = ?');
    $stmt->execute([$doctorAuth->accountId()]);
    $bookingStats['total'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM patient_doctor_bookings WHERE doctor_account_id = ? AND status = ?');
    $stmt->execute([$doctorAuth->accountId(), 'pending']);
    $bookingStats['pending'] = (int)$stmt->fetchColumn();
    
    $stmt->execute([$doctorAuth->accountId(), 'confirmed']);
    $bookingStats['confirmed'] = (int)$stmt->fetchColumn();
    
    $stmt->execute([$doctorAuth->accountId(), 'completed']);
    $bookingStats['completed'] = (int)$stmt->fetchColumn();
    
    $stmt = $db->prepare('SELECT COUNT(*) FROM patient_doctor_bookings WHERE doctor_account_id = ? AND appointment_date = CURDATE()');
    $stmt->execute([$doctorAuth->accountId()]);
    $bookingStats['today'] = (int)$stmt->fetchColumn();
} catch (Throwable $e) {}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <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">
    <style>
        .booking-link-card {
            background: white;
            border-radius: 16px;
            padding: 32px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            margin-bottom: 24px;
        }
        .booking-link-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 2px solid #e5e7eb;
        }
        .booking-link-title {
            font-size: 1.5rem;
            font-weight: 700;
            color: #0f172a;
            margin: 0;
        }
        .booking-link-url {
            background: #f3f4f6;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            padding: 12px 16px;
            font-family: monospace;
            font-size: 0.95rem;
            word-break: break-all;
            margin: 16px 0;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .booking-link-url input {
            flex: 1;
            border: none;
            background: transparent;
            font-family: inherit;
            font-size: inherit;
            color: #1f2937;
        }
        .booking-link-url button {
            background: #0d9488;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            white-space: nowrap;
        }
        .booking-link-url button:hover {
            background: #0f766e;
        }
        .qr-code-container {
            text-align: center;
            padding: 24px;
            background: #f9fafb;
            border-radius: 12px;
            margin: 24px 0;
        }
        .qr-code-container img {
            max-width: 300px;
            width: 100%;
            height: auto;
            border: 4px solid white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .booking-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 16px;
            margin-top: 24px;
        }
        .booking-stat-card {
            background: linear-gradient(135deg, #0d9488 0%, #0f766e 100%);
            color: white;
            padding: 20px;
            border-radius: 12px;
            text-align: center;
        }
        .booking-stat-number {
            font-size: 2rem;
            font-weight: 700;
            margin-bottom: 8px;
        }
        .booking-stat-label {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        .no-link-message {
            text-align: center;
            padding: 48px 24px;
            color: #6b7280;
        }
        .no-link-message h3 {
            color: #1f2937;
            margin-bottom: 16px;
        }
    </style>
</head>
<body>
<?php include __DIR__ . '/_layout.php'; ?>
<main class="content">
    <div class="page-header">
        <div>
            <h1>🔗 رابط حجز المواعيد</h1>
            <p class="page-subtitle">أنشئ رابط حجز خاص بك وشاركه مع المرضى</p>
        </div>
        <div>
            <a href="doctor.php?page=appointments" class="btn-secondary">← المواعيد</a>
        </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; ?>
    <?php if (isset($_SESSION['doctor_error'])): ?>
    <div class="alert alert-danger"><?php echo htmlspecialchars($_SESSION['doctor_error'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['doctor_error']); ?></div>
    <?php endif; ?>

    <div class="booking-link-card">
        <div class="booking-link-header">
            <h2 class="booking-link-title">رابط الحجز</h2>
            <?php if (!$bookingToken): ?>
            <form method="post" action="doctor.php?page=booking_link&action=generate" style="display:inline;">
                <button type="submit" class="btn-primary">إنشاء رابط جديد</button>
            </form>
            <?php else: ?>
            <form method="post" action="doctor.php?page=booking_link&action=generate" style="display:inline;">
                <button type="submit" class="btn-secondary">تجديد الرابط</button>
            </form>
            <?php endif; ?>
        </div>

        <?php if ($bookingToken && $bookingLink): ?>
        <div>
            <label style="display:block;margin-bottom:8px;font-weight:600;color:#374151;">الرابط:</label>
            <div class="booking-link-url">
                <input type="text" value="<?php echo htmlspecialchars($bookingLink, ENT_QUOTES, 'UTF-8'); ?>" readonly id="booking-link-input">
                <button type="button" onclick="copyBookingLink()">نسخ الرابط</button>
            </div>
            
            <div class="qr-code-container">
                <h3 style="margin-bottom:16px;color:#374151;">QR Code للحجز</h3>
                <img src="<?php echo htmlspecialchars($qrCodeUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="QR Code">
                <p style="margin-top:16px;color:#6b7280;font-size:0.9rem;">يمكن للمرضى مسح هذا الكود لحجز موعد معك</p>
                <button type="button" onclick="downloadQRCode()" class="btn-secondary" style="margin-top:12px;">تحميل QR Code</button>
            </div>
            <?php if (!empty($whatsappQrUrl)): ?>
            <div class="qr-code-container" style="background:linear-gradient(135deg,#ecfdf5 0%,#d1fae5 50%);border:2px solid #25D366;">
                <h3 style="margin-bottom:16px;color:#0f766e;">💬 QR واتساب للتواصل</h3>
                <img id="wa-qr-img" src="<?php echo htmlspecialchars($whatsappQrUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="QR واتساب">
                <p style="margin-top:16px;color:#065f46;font-size:0.9rem;">مسح الكود يفتح واتساب مباشرة للتواصل معك</p>
                <p style="margin-top:8px;color:#047857;font-size:0.85rem;">✓ التذكيرات ترسل تلقائياً بالخلفية قبل الموعد بساعتين</p>
                <button type="button" onclick="var i=document.getElementById('wa-qr-img');if(i){var a=document.createElement('a');a.href=i.src;a.download='whatsapp-qr.png';a.click();}" class="btn-secondary" style="margin-top:12px;">تحميل QR واتساب</button>
            </div>
            <?php else: ?>
            <p style="margin-top:16px;padding:12px;background:#fef3c7;border-radius:8px;color:#92400e;">أضف رقم هاتفك في <a href="doctor.php?page=profile">الملف الشخصي → إعدادات واتساب</a> لظهور QR واتساب</p>
            <?php endif; ?>

            <div style="background:#fef3c7;border:1px solid #fbbf24;border-radius:8px;padding:16px;margin-top:24px;">
                <h4 style="margin:0 0 8px 0;color:#92400e;">💡 نصائح:</h4>
                <ul style="margin:0;padding-right:20px;color:#78350f;">
                    <li>شارك هذا الرابط مع المرضى عبر WhatsApp أو البريد الإلكتروني</li>
                    <li>اطبع QR Code وضعه في العيادة أو المكتب</li>
                    <li>سيتم إشعارك تلقائياً عند حجز أي مريض موعد</li>
                    <li>التذكيرات ترسل للمريض تلقائياً بالخلفية قبل الموعد بساعتين (بعد تفعيل واتساب)</li>
                </ul>
            </div>
        </div>
        <?php else: ?>
        <div class="no-link-message">
            <h3>لم يتم إنشاء رابط حجز بعد</h3>
            <p>أنشئ رابط حجز خاص بك لتمكين المرضى من حجز مواعيد معك مباشرة</p>
            <form method="post" action="doctor.php?page=booking_link&action=generate" style="margin-top:24px;">
                <button type="submit" class="btn-primary" style="font-size:1.1rem;padding:12px 24px;">إنشاء رابط الحجز</button>
            </form>
        </div>
        <?php endif; ?>
    </div>

    <?php if ($bookingStats['total'] > 0): ?>
    <div class="booking-link-card">
        <h2 class="booking-link-title" style="margin-bottom:16px;">إحصائيات الحجوزات</h2>
        <div class="booking-stats">
            <div class="booking-stat-card">
                <div class="booking-stat-number"><?php echo $bookingStats['total']; ?></div>
                <div class="booking-stat-label">إجمالي الحجوزات</div>
            </div>
            <div class="booking-stat-card" style="background:linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                <div class="booking-stat-number"><?php echo $bookingStats['pending']; ?></div>
                <div class="booking-stat-label">في الانتظار</div>
            </div>
            <div class="booking-stat-card" style="background:linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);">
                <div class="booking-stat-number"><?php echo $bookingStats['confirmed']; ?></div>
                <div class="booking-stat-label">مؤكدة</div>
            </div>
            <div class="booking-stat-card" style="background:linear-gradient(135deg, #10b981 0%, #059669 100%);">
                <div class="booking-stat-number"><?php echo $bookingStats['completed']; ?></div>
                <div class="booking-stat-label">منفذة</div>
            </div>
            <div class="booking-stat-card" style="background:linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%);">
                <div class="booking-stat-number"><?php echo $bookingStats['today']; ?></div>
                <div class="booking-stat-label">حجوزات اليوم</div>
            </div>
        </div>
    </div>
    <?php endif; ?>
</main>

<script>
function copyBookingLink() {
    var input = document.getElementById('booking-link-input');
    if (input) {
        input.select();
        input.setSelectionRange(0, 99999);
        try {
            document.execCommand('copy');
            alert('تم نسخ الرابط بنجاح!');
        } catch (err) {
            if (navigator.clipboard) {
                navigator.clipboard.writeText(input.value).then(function() {
                    alert('تم نسخ الرابط بنجاح!');
                });
            } else {
                alert('فشل نسخ الرابط. يرجى نسخه يدوياً.');
            }
        }
    }
}

function downloadQRCode() {
    var qrImg = document.querySelector('.qr-code-container img');
    if (qrImg) {
        var link = document.createElement('a');
        link.href = qrImg.src;
        link.download = 'doctor-booking-qr.png';
        link.click();
    }
}
function downloadQR(url, filename) {
    if (url) {
        var link = document.createElement('a');
        link.href = url;
        link.download = filename || 'qr.png';
        link.click();
    }
}
</script>
</body>
</html>
