<?php
/**
 * طلب زيارة منزلية - من بوابة المريض أو للجميع
 */
$config = require __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Core/Tenant.php';
$db = \App\Core\Database::getInstance($config['db'])->connection();

if (session_status() === PHP_SESSION_NONE) session_start();
$tenantSlug = trim($_GET['tenant'] ?? $_POST['tenant'] ?? '');
$tenantId = 1;
if ($tenantSlug !== '') {
    try {
        $stmt = $db->prepare('SELECT id FROM tenants WHERE slug = ? AND status IN (?, ?) LIMIT 1');
        $stmt->execute([$tenantSlug, 'active', 'trial']);
        if ($row = $stmt->fetch()) {
            \App\Core\Tenant::setId((int)$row['id']);
            $tenantId = (int)$row['id'];
        }
    } catch (Throwable $e) {}
}

$patientId = isset($_SESSION['portal_patient_id']) ? (int)$_SESSION['portal_patient_id'] : 0;
$patientName = '';
$patientPhone = '';
if ($patientId > 0) {
    try {
        $stmt = $db->prepare('SELECT full_name, phone FROM patients WHERE id = ?');
        $stmt->execute([$patientId]);
        if ($r = $stmt->fetch()) {
            $patientName = $r['full_name'] ?? '';
            $patientPhone = $r['phone'] ?? '';
        }
    } catch (Throwable $e) {}
}

$msg = '';
$success = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['patient_name'] ?? '') ?: $patientName;
    $phone = trim($_POST['patient_phone'] ?? '') ?: $patientPhone;
    $address = trim($_POST['address'] ?? '');
    $visitDate = trim($_POST['visit_date'] ?? '');
    $timeStart = trim($_POST['visit_time_start'] ?? '');
    $timeEnd = trim($_POST['visit_time_end'] ?? '');
    $notes = trim($_POST['notes'] ?? '');

    if (strlen($name) < 2) $msg = 'أدخل الاسم.';
    elseif (strlen($phone) < 8) $msg = 'أدخل رقم هاتف صحيح.';
    elseif (strlen($address) < 5) $msg = 'أدخل العنوان.';
    elseif (empty($visitDate)) $msg = 'اختر تاريخ الزيارة.';
    else {
        try {
            $db->query('SELECT id FROM home_visit_requests LIMIT 1');
            $stmt = $db->prepare('INSERT INTO home_visit_requests (patient_id, patient_name, patient_phone, address, visit_date, visit_time_start, visit_time_end, status, tenant_id, notes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
            $stmt->execute([
                $patientId ?: null,
                $name,
                $phone,
                $address,
                $visitDate,
                $timeStart ?: null,
                $timeEnd ?: null,
                'pending',
                $tenantId,
                $notes ?: null
            ]);
            $success = true;
            $msg = 'تم استلام طلبك. سنتواصل معك لتأكيد الموعد.';
        } catch (Throwable $e) {
            $msg = 'حدث خطأ. حاول لاحقاً.';
        }
    }
}

$labName = 'مختبر تحاليل';
try {
    $stmt = $db->prepare("SELECT setting_value FROM settings WHERE setting_key = 'lab_name' LIMIT 1");
    $stmt->execute();
    if (($r = $stmt->fetch()) && !empty(trim($r['setting_value'] ?? ''))) {
        $labName = trim($r['setting_value']);
    }
} 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">
    <title>طلب زيارة منزلية - <?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="portal.css">
</head>
<body class="portal-page">
    <div class="portal-wrap">
        <div class="portal-container home-visit-form">
            <div class="portal-brand">
                <div class="portal-brand-icon">🏠</div>
                <h1 class="portal-title">طلب زيارة منزلية</h1>
                <p class="portal-subtitle"><?php echo htmlspecialchars($labName, ENT_QUOTES, 'UTF-8'); ?></p>
            </div>
            <?php if ($success): ?>
            <div class="portal-alert portal-alert--success"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div>
            <a href="index.php?page=patient_portal<?php echo $tenantSlug ? '&tenant=' . urlencode($tenantSlug) : ''; ?>" class="portal-btn">العودة للبوابة</a>
            <?php else: ?>
            <?php if ($msg): ?><div class="portal-alert portal-alert--danger"><?php echo htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            <form method="post" class="portal-form home-visit-form-inner">
                <?php if ($tenantSlug): ?><input type="hidden" name="tenant" value="<?php echo htmlspecialchars($tenantSlug, ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
                <div class="portal-form-group">
                    <label>الاسم</label>
                    <input type="text" name="patient_name" required value="<?php echo htmlspecialchars($_POST['patient_name'] ?? $patientName, ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="portal-form-group">
                    <label>الهاتف</label>
                    <input type="tel" name="patient_phone" required value="<?php echo htmlspecialchars($_POST['patient_phone'] ?? $patientPhone, ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="portal-form-group home-visit-address">
                    <label>العنوان الكامل</label>
                    <textarea name="address" rows="3" required placeholder="الحي، الشارع، رقم المنزل"><?php echo htmlspecialchars($_POST['address'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                </div>
                <div class="portal-form-group">
                    <label>تاريخ الزيارة المفضل</label>
                    <input type="date" name="visit_date" required min="<?php echo date('Y-m-d'); ?>" value="<?php echo htmlspecialchars($_POST['visit_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="portal-form-group home-visit-time-range">
                    <label>الفترة المفضلة</label>
                    <div class="home-visit-time-inputs">
                        <span class="home-visit-time-from">
                            <label class="home-visit-time-label">من</label>
                            <input type="time" name="visit_time_start" value="<?php echo htmlspecialchars($_POST['visit_time_start'] ?? '08:00', ENT_QUOTES, 'UTF-8'); ?>">
                        </span>
                        <span class="home-visit-time-sep">—</span>
                        <span class="home-visit-time-to">
                            <label class="home-visit-time-label">إلى</label>
                            <input type="time" name="visit_time_end" value="<?php echo htmlspecialchars($_POST['visit_time_end'] ?? '12:00', ENT_QUOTES, 'UTF-8'); ?>">
                        </span>
                    </div>
                </div>
                <div class="portal-form-group home-visit-notes">
                    <label>ملاحظات <span class="portal-optional">(اختياري)</span></label>
                    <textarea name="notes" rows="2" placeholder="مثلاً: الصيام، نوع العينة"><?php echo htmlspecialchars($_POST['notes'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                </div>
                <button type="submit" class="portal-btn">إرسال الطلب</button>
                <div class="home-visit-footer">
                    <a href="index.php?page=patient_portal<?php echo $tenantSlug ? '&tenant=' . urlencode($tenantSlug) : ''; ?>" class="portal-footer-link">← العودة للبوابة</a>
                </div>
            </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
