<?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/DoctorNotification.php';
$db = \App\Core\Database::getInstance($config['db'])->connection();

$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;
$doctorPhoneForWa = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $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 {
                $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();
            }

            $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;
            $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 = 'حدث خطأ. حاول لاحقاً أو تواصل معنا.';
        }
    }
}

\App\Core\Session::start();
$msg = $_SESSION['doctor_booking_success'] ?? $msg;
if (isset($_SESSION['doctor_booking_success'])) unset($_SESSION['doctor_booking_success']);
$success = ($msg !== '' && strpos($msg, 'نجاح') !== false) || isset($_GET['success']);

$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; }
    </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" class="doctor-booking-form">
            <?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 if (!empty($doctorPhoneForWa)): ?>
            <?php
            $waMsg = "السلام عليكم دكتور، حجزت موعداً معك.\n\n";
            $waMsg .= "الاسم: " . ($_POST['patient_name'] ?? '') . "\n";
            $waMsg .= "الهاتف: " . ($_POST['phone'] ?? '') . "\n";
            $waMsg .= "التاريخ: " . ($_POST['appointment_date'] ?? '') . "\n";
            $waMsg .= "الوقت: " . ($_POST['appointment_time'] ?? '09:00') . "\n";
            if (!empty($_POST['note'])) $waMsg .= "ملاحظة: " . $_POST['note'] . "\n";
            $waUrl = 'https://wa.me/' . $doctorPhoneForWa . '?text=' . urlencode($waMsg);
            ?>
            <a href="<?php echo htmlspecialchars($waUrl, ENT_QUOTES, 'UTF-8'); ?>" target="_blank" rel="noopener" style="display:inline-block;padding:14px 28px;background:#25D366;color:white;border-radius:12px;text-decoration:none;font-weight:700;font-size:1.05rem;margin-bottom:16px;box-shadow:0 4px 14px rgba(37,211,102,0.4);">
                💬 تواصل مع الطبيب عبر واتساب
            </a>
            <p style="font-size:0.9rem;color:#64748b;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>
