<?php
/**
 * Online Booking - حجز موعد واختيار فحص (عام - بدون تسجيل دخول)
 * index.php?page=booking&tenant=slug
 */
$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';
$db = \App\Core\Database::getInstance($config['db'])->connection();

$tenantSlug = trim($_GET['tenant'] ?? 'main');
$tenant = null;
$tests = [];
$msg = '';
$booked = false;

try {
    $stmt = $db->prepare('SELECT id, name, primary_color, logo_url FROM tenants WHERE slug = ? AND status IN (?, ?)');
    $stmt->execute([$tenantSlug, 'active', 'trial']);
    $tenant = $stmt->fetch();
    if (!$tenant) {
        $stmt = $db->query('SELECT id, name, primary_color, logo_url FROM tenants WHERE status IN ("active","trial") ORDER BY id ASC LIMIT 1');
        $tenant = $stmt->fetch();
    }
} catch (Throwable $e) {
}

$tid = $tenant ? (int)$tenant['id'] : 1;
try {
    $stmt = $db->prepare('SELECT id, name, test_code, default_price FROM tests WHERE tenant_id = ? ORDER BY name LIMIT 100');
    $stmt->execute([$tid]);
    $tests = $stmt->fetchAll();
} catch (Throwable $e) {
    $stmt = $db->query('SELECT id, name, test_code, default_price FROM tests ORDER BY name LIMIT 100');
    $tests = $stmt->fetchAll();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $tenant) {
    $patientName = trim($_POST['patient_name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $date = trim($_POST['booking_date'] ?? '');
    $testIds = array_map('intval', (array)($_POST['test_ids'] ?? []));
    $testIds = array_filter($testIds);

    if (strlen($patientName) < 2 || strlen($phone) < 8) {
        $msg = 'أدخل الاسم والهاتف.';
    } elseif (empty($date)) {
        $msg = 'اختر التاريخ.';
    } elseif (empty($testIds)) {
        $msg = 'اختر فحصاً على الأقل.';
    } else {
        try {
            $db->beginTransaction();
            $patientCode = 'B' . date('Ymd') . rand(100, 999);
            try {
                $stmt = $db->prepare('INSERT INTO patients (patient_code, full_name, phone, tenant_id) VALUES (?, ?, ?, ?)');
                $stmt->execute([$patientCode, $patientName, $phone, $tid]);
            } catch (Throwable $e2) {
                $stmt = $db->prepare('INSERT INTO patients (patient_code, full_name, phone) VALUES (?, ?, ?)');
                $stmt->execute([$patientCode, $patientName, $phone]);
                $tid = 1;
            }
            $patientId = (int)$db->lastInsertId();

            $stmt = $db->prepare('SELECT id FROM branches WHERE tenant_id = ? ORDER BY tenant_id DESC LIMIT 1');
            $stmt->execute([$tid]);
            $b = $stmt->fetch();
            $branchId = $b ? (int)$b['id'] : 1;
            $stmt = $db->prepare('SELECT id FROM users WHERE (tenant_id = ?) AND is_active = 1 LIMIT 1');
            $stmt->execute([$tid]);
            $u = $stmt->fetch();
            $createdBy = $u ? (int)$u['id'] : 1;

            $orderNum = 'ORD' . date('YmdHis') . $tid;
            $total = 0;
            $stmt = $db->prepare('SELECT id, default_price FROM tests WHERE id = ?');
            foreach ($testIds as $tId) {
                $stmt->execute([$tId]);
                $t = $stmt->fetch();
                if ($t) $total += (float)$t['default_price'];
            }
            try {
                $stmt = $db->prepare('INSERT INTO lab_orders (order_number, patient_id, order_date, status, total_amount, net_amount, branch_id, created_by, tenant_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([$orderNum, $patientId, $date . ' 08:00:00', 'new', $total, $total, $branchId, $createdBy, $tid]);
            } catch (Throwable $e2) {
                $stmt = $db->prepare('INSERT INTO lab_orders (order_number, patient_id, order_date, status, total_amount, net_amount, branch_id, created_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
                $stmt->execute([$orderNum, $patientId, $date . ' 08:00:00', 'new', $total, $total, $branchId, $createdBy]);
            }
            $orderId = (int)$db->lastInsertId();
            if ($orderId <= 0) {
                $db->rollBack();
                $msg = 'فشل إنشاء الطلب.';
            }

            $stmt = $db->prepare('INSERT INTO order_items (order_id, test_id, price, status) VALUES (?, ?, ?, ?)');
            $stmtPrice = $db->prepare('SELECT default_price FROM tests WHERE id = ?');
            foreach ($testIds as $tId) {
                $price = 0;
                $stmtPrice->execute([$tId]);
                $pr = $stmtPrice->fetch();
                if ($pr) $price = (float)$pr['default_price'];
                $stmt->execute([$orderId, $tId, $price, 'pending']);
            }
            $db->commit();
            $booked = true;
        } catch (Throwable $e) {
            if ($db->inTransaction()) $db->rollBack();
            $msg = 'حدث خطأ. تأكد من وجود tenant_id في الجداول.';
        }
    }
}

$labName = $tenant['name'] ?? 'المختبر';
$primaryColor = $tenant['primary_color'] ?? '#0d9488';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>حجز موعد - <?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="stylesheet" href="styles.css">
    <style>:root { --primary: <?php echo htmlspecialchars($primaryColor, ENT_QUOTES, 'UTF-8'); ?>; }</style>
</head>
<body class="login-page">
    <div class="login-container" style="max-width:500px;">
        <?php if ($tenant && !empty($tenant['logo_url'])): 
            $logoUrl = trim($tenant['logo_url'], '/');
            // حساب المسار الأساسي للتطبيق
            $scriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? ''));
            if ($scriptDir === '/') $scriptDir = '';
            $basePath = $scriptDir;
            if (strpos($logoUrl, 'http') !== 0 && strpos($logoUrl, '//') !== 0) {
                $logoUrl = ($basePath ? $basePath . '/' : '/') . $logoUrl;
            }
        ?>
        <img src="<?php echo htmlspecialchars($logoUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="Logo" style="max-height:60px;margin-bottom:16px;">
        <?php endif; ?>
        <h1>حجز موعد - <?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></h1>

        <?php if ($booked): ?>
            <div class="alert alert-success">تم الحجز. سنتواصل معك قريباً.</div>
        <?php elseif ($tenant): ?>
            <?php if ($msg): ?><div class="alert alert-danger"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            <form method="post">
                <div class="form-group">
                    <label>اسم المريض</label>
                    <input type="text" name="patient_name" required value="<?php echo htmlspecialchars($_POST['patient_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>الهاتف</label>
                    <input type="tel" name="phone" required value="<?php echo htmlspecialchars($_POST['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>البريد (اختياري)</label>
                    <input type="email" name="email" value="<?php echo htmlspecialchars($_POST['email'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>موعد مطلوب</label>
                    <input type="date" name="booking_date" required min="<?php echo date('Y-m-d'); ?>" value="<?php echo htmlspecialchars($_POST['booking_date'] ?? date('Y-m-d', strtotime('+1 day')), ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="form-group">
                    <label>الفحوصات المطلوبة</label>
                    <input type="search" id="bookingTestsSearch" placeholder="ابحث بالاسم... (مثل: ALT، سكر، هيموغلوبين)" style="margin-bottom:8px;width:100%;padding:10px 14px;border:1px solid var(--border);border-radius:8px;font-size:1rem;">
                    <div id="bookingTestsList" style="max-height:200px;overflow-y:auto;border:1px solid var(--border);padding:12px;border-radius:8px;">
                    <?php foreach ($tests as $t): ?>
                        <label class="booking-test-item" style="display:block;margin:6px 0;"><input type="checkbox" name="test_ids[]" value="<?php echo (int)$t['id']; ?>"> <?php echo htmlspecialchars($t['name'], ENT_QUOTES, 'UTF-8'); ?> (<?php echo $t['default_price']; ?>)</label>
                    <?php endforeach; ?>
                    </div>
                </div>
                <button type="submit">حجز</button>
            </form>
            <script>
            (function(){
                var searchInput = document.getElementById('bookingTestsSearch');
                var list = document.getElementById('bookingTestsList');
                if (searchInput && list) {
                    searchInput.addEventListener('input', function(){
                        var q = (this.value || '').trim().toLowerCase();
                        list.querySelectorAll('.booking-test-item').forEach(function(label){
                            var text = (label.textContent || '').toLowerCase();
                            label.style.display = q === '' || text.indexOf(q) >= 0 ? '' : 'none';
                        });
                    });
                }
            })();
            </script>
        <?php else: ?>
            <p>المختبر غير متوفر.</p>
            <p style="font-size:0.9rem;color:var(--text-muted);">يرجى التواصل مع مسؤولي المختبر لتفعيل الحجز الإلكتروني.</p>
        <?php endif; ?>
        <p style="margin-top:20px;"><a href="index.php?page=login">دخول الموظفين</a></p>
    </div>
</body>
</html>
