<?php
/**
 * بوابة المريض - الدخول برقم الهاتف ورمز البوابة
 * index.php?page=patient_portal أو index.php?page=patient_portal&tenant=slug
 */
$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();

// دعم ?tenant=slug لتحديد المختبر عند استخدام نفس النطاق
$tenantSlug = trim($_GET['tenant'] ?? $_POST['tenant'] ?? '');
if ($tenantSlug !== '') {
    try {
        $stmt = $db->prepare('SELECT id FROM tenants WHERE slug = ? AND status IN (?, ?) LIMIT 1');
        $stmt->execute([$tenantSlug, 'active', 'trial']);
        $row = $stmt->fetch();
        if ($row) {
            \App\Core\Tenant::setId((int)$row['id']);
        }
    } catch (Throwable $e) {}
}
$tenantId = (int)(\App\Core\Tenant::id());
$labName = 'مختبر تحاليل';
$labPhone = '';
try {
    $stmt = $db->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('lab_name','lab_phone') AND tenant_id = ?");
    $stmt->execute([$tenantId]);
    foreach ($stmt->fetchAll() as $r) {
        if ($r['setting_key'] === 'lab_name') $labName = $r['setting_value'] ?: $labName;
        if ($r['setting_key'] === 'lab_phone') $labPhone = $r['setting_value'] ?? '';
    }
} catch (Throwable $e) {
    try {
        $stmt = $db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('lab_name','lab_phone')");
        foreach ($stmt->fetchAll() as $r) {
            if ($r['setting_key'] === 'lab_name') $labName = $r['setting_value'] ?: $labName;
            if ($r['setting_key'] === 'lab_phone') $labPhone = $r['setting_value'] ?? '';
        }
    } catch (Throwable $e2) {}
}

$patient = null;
$orders = [];
$error = '';
$step = 'login';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'rate' && isset($_SESSION['portal_patient_id'])) {
    $orderId = (int)($_POST['order_id'] ?? 0);
    $rating = (int)($_POST['rating'] ?? 0);
    $comment = trim($_POST['comment'] ?? '');
    if ($orderId > 0 && $rating >= 1 && $rating <= 5) {
        try {
            $db->query('SELECT id FROM service_ratings LIMIT 1');
            $stmt = $db->prepare('INSERT INTO service_ratings (tenant_id, order_id, patient_id, rating, comment) VALUES (?, ?, ?, ?, ?)');
            $stmt->execute([$tenantId, $orderId, (int)$_SESSION['portal_patient_id'], $rating, $comment ?: null]);
            $_SESSION['portal_rated_' . $orderId] = true;
        } catch (Throwable $e) {}
    }
    header('Location: index.php?page=patient_portal' . ($tenantSlug ? '&tenant=' . urlencode($tenantSlug) : ''));
    exit;
}
$orderFilter = trim($_GET['order_q'] ?? '');
if (session_status() === PHP_SESSION_NONE) session_start();

// الدخول بكود QR: ?qr=PATIENT:كود_المريض أو ?qr=PATIENT:كود_المريض:رمز_البوابة
$qrLogin = trim($_GET['qr'] ?? '');
if ($qrLogin !== '' && preg_match('/PATIENT:([^:\s]+)(?::([^\s]+))?/i', $qrLogin, $m)) {
    $pc = trim($m[1]);
    $portalCodeFromQr = isset($m[2]) ? trim($m[2]) : '';
    try {
        $sql = 'SELECT id, full_name, patient_code FROM patients WHERE patient_code = ?';
        $params = [$pc];
        try { $db->query('SELECT tenant_id FROM patients LIMIT 1'); $sql .= ' AND tenant_id = ?'; $params[] = $tenantId; } catch (Throwable $e) {}
        try { $db->query('SELECT portal_code FROM patients LIMIT 1'); $sql = str_replace('patient_code FROM', 'patient_code, portal_code FROM', $sql); } catch (Throwable $e) {}
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        $p = $stmt->fetch();
        if (!$p) {
            $stmt = $db->prepare('SELECT id, full_name, patient_code, portal_code FROM patients WHERE patient_code = ? LIMIT 1');
            $stmt->execute([$pc]);
            $p = $stmt->fetch();
        }
        if ($p) {
            $pPortalCode = trim($p['portal_code'] ?? '');
            $codeMatch = $pPortalCode === '' || $pPortalCode === $portalCodeFromQr;
            if ($codeMatch) {
                $_SESSION['portal_patient_id'] = (int)$p['id'];
                $redirect = 'index.php?page=patient_portal';
                if ($tenantSlug !== '') $redirect .= '&tenant=' . urlencode($tenantSlug);
                header('Location: ' . $redirect);
                exit;
            }
        }
    } catch (Throwable $e) {}
}
if (isset($_GET['logout'])) {
    unset($_SESSION['portal_patient_id']);
    $logoutUrl = 'index.php?page=patient_portal';
    if ($tenantSlug !== '') $logoutUrl .= '&tenant=' . urlencode($tenantSlug);
    header('Location: ' . $logoutUrl);
    exit;
}
if (isset($_SESSION['portal_patient_id']) && (int)$_SESSION['portal_patient_id'] > 0) {
    try {
        $stmt = $db->prepare('SELECT id, full_name, patient_code FROM patients WHERE id = ?');
        $stmt->execute([(int)$_SESSION['portal_patient_id']]);
        $patient = $stmt->fetch();
        try { $db->query('SELECT portal_code FROM patients LIMIT 1'); $stmt2 = $db->prepare('SELECT id, full_name, patient_code, portal_code FROM patients WHERE id = ?'); $stmt2->execute([(int)$_SESSION['portal_patient_id']]); $patient = $stmt2->fetch(); } catch (Throwable $e) {}
    } catch (Throwable $e) {}
    if ($patient) $step = 'results';
}
$orderTenantAnd = '';
try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $orderTenantAnd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
if ($patient && $step === 'results') {
    $stmt = $db->prepare(
        'SELECT o.id, o.order_number, o.order_date, o.status,
                (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) AS tests_count,
                (SELECT COUNT(*) FROM order_items WHERE order_id = o.id AND status = "validated") AS completed_count
         FROM lab_orders o WHERE o.patient_id = ?' . $orderTenantAnd . '
         ORDER BY o.order_date DESC LIMIT 50'
    );
    $stmt->execute([$patient['id']]);
    $orders = $stmt->fetchAll();
    if ($orderFilter !== '') {
        $orders = array_filter($orders, function ($o) use ($orderFilter) {
            return stripos($o['order_number'] ?? '', $orderFilter) !== false || stripos($o['order_date'] ?? '', $orderFilter) !== false;
        });
        $orders = array_values($orders);
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = preg_replace('/\D/', '', trim($_POST['phone'] ?? ''));
    $code = trim($_POST['portal_code'] ?? '');
    $qrPaste = trim($_POST['qr_paste'] ?? '');

    // استخراج كود QR من الرابط إن كان المستخدم قد الصق رابطاً كاملاً
    if ($qrPaste !== '' && (strpos($qrPaste, 'http') === 0 || strpos($qrPaste, 'qr=') !== false)) {
        $query = parse_url($qrPaste, PHP_URL_QUERY);
        if ($query === null && strpos($qrPaste, '?') !== false) {
            $query = substr($qrPaste, strpos($qrPaste, '?') + 1);
        }
        if ($query) {
            parse_str($query, $urlParams);
            if (!empty($urlParams['qr'])) {
                $qrPaste = trim($urlParams['qr']);
            }
        }
    }

    // استخراج كود المريض أولاً: PATIENT:xxx أو PATIENT:xxx:yyy أو كود المريض مباشرة (مثل P1771140581)
    // لا نعتبره رقم هاتف إذا كان يبدو كود مريض (P + أرقام أو حرف + أرقام)
    $looksLikePatientCode = preg_match('/^[A-Za-z]\d+/', $qrPaste) || preg_match('/^[A-Za-z]?\d{6,}$/', $qrPaste) || preg_match('/^PATIENT:/i', $qrPaste);

    // إذا أُدخل رقم هاتف فقط (بدون حرف) في حقل QR، نستخدمه كرقم هاتف
    if ($qrPaste !== '' && !$looksLikePatientCode && strlen($phone) < 8 && preg_match('/^\d{8,}$/', preg_replace('/\D/', '', $qrPaste))) {
        $phone = preg_replace('/\D/', '', $qrPaste);
        $qrPaste = '';
    }

    // استخراج كود المريض: PATIENT:xxx أو PATIENT:xxx:yyy أو كود المريض مباشرة (مثل P1771140581)
    $pc = null;
    $portalCodeFromQr = '';
    if ($qrPaste !== '') {
        if (preg_match('/PATIENT:([^:\s]+)(?::([^\s]+))?/i', $qrPaste, $m)) {
            $pc = trim($m[1]);
            $portalCodeFromQr = isset($m[2]) ? trim($m[2]) : '';
        } elseif (preg_match('/^[A-Za-z]?\d{6,}$/', $qrPaste) || preg_match('/^[A-Za-z]\d+/', $qrPaste)) {
            $pc = trim($qrPaste);
        }
    }

    // الدخول بكود المريض أو QR
    if ($pc !== null) {
        try {
            $sql = 'SELECT id, full_name, patient_code FROM patients WHERE patient_code = ?';
            $params = [$pc];
            try {
                $db->query('SELECT tenant_id FROM patients LIMIT 1');
                $sql .= ' AND tenant_id = ?';
                $params[] = $tenantId;
            } catch (Throwable $e) {}
            try { $db->query('SELECT portal_code FROM patients LIMIT 1'); $sql = str_replace('patient_code FROM', 'patient_code, portal_code FROM', $sql); } catch (Throwable $e) {}
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            $p = $stmt->fetch();
            if (!$p) {
                $stmt = $db->prepare('SELECT id, full_name, patient_code, portal_code FROM patients WHERE patient_code = ? LIMIT 1');
                $stmt->execute([$pc]);
                $p = $stmt->fetch();
            }
            if ($p) {
                $pPortalCode = trim($p['portal_code'] ?? '');
                $codeOk = $pPortalCode === '' || $pPortalCode === $portalCodeFromQr || $pPortalCode === $code;
                if ($codeOk) {
                    $_SESSION['portal_patient_id'] = (int)$p['id'];
                    $patient = $p;
                    $step = 'results';
                    $stmt = $db->prepare(
                        'SELECT o.id, o.order_number, o.order_date, o.status,
                                (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) AS tests_count,
                                (SELECT COUNT(*) FROM order_items WHERE order_id = o.id AND status = "validated") AS completed_count
                         FROM lab_orders o WHERE o.patient_id = ?' . $orderTenantAnd . '
                         ORDER BY o.order_date DESC LIMIT 50'
                    );
                    $stmt->execute([$patient['id']]);
                    $orders = $stmt->fetchAll();
                } else {
                    $error = 'رمز البوابة مطلوب لهذا المريض. أدخل رمز البوابة في الحقل أدناه.';
                }
            } else {
                $error = 'لم يُعثر على مريض بهذا الكود. جرّب رقم الهاتف.';
            }
        } catch (Throwable $e) { $error = 'حدث خطأ في التحقق.'; }
    } elseif ($qrPaste !== '' && !$patient) {
        $error = 'لم يتعرّف النظام على المدخل. أدخل كود المريض (مثل P1771140581) أو رقم الهاتف.';
    } elseif (strlen($phone) < 8) {
        $error = 'أدخل رقم هاتف صحيح أو الصق كود QR.';
    } else {
        try {
            $sql = 'SELECT id, full_name, patient_code FROM patients WHERE phone LIKE ?';
            $params = ['%' . $phone . '%'];
            try {
                $db->query('SELECT tenant_id FROM patients LIMIT 1');
                $sql .= ' AND tenant_id = ?';
                $params[] = $tenantId;
            } catch (Throwable $e2) {}
            try { $db->query('SELECT portal_code FROM patients LIMIT 1'); $sql = str_replace('patient_code FROM', 'patient_code, portal_code FROM', $sql); } catch (Throwable $e2) {}
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            $candidates = $stmt->fetchAll();
            foreach ($candidates as $p) {
                $pCode = trim($p['portal_code'] ?? '');
                if ($code === '' || $pCode === $code) {
                    $patient = $p;
                    break;
                }
            }
            if (!$patient && count($candidates) === 1 && trim($candidates[0]['portal_code'] ?? '') === '') {
                $patient = $candidates[0];
            }
        } catch (Throwable $e) {
            $error = 'حدث خطأ في البحث.';
        }
    }

    if ($patient) {
        $_SESSION['portal_patient_id'] = (int)$patient['id'];
        $step = 'results';
        $stmt = $db->prepare(
            'SELECT o.id, o.order_number, o.order_date, o.status,
                    (SELECT COUNT(*) FROM order_items WHERE order_id = o.id) AS tests_count,
                    (SELECT COUNT(*) FROM order_items WHERE order_id = o.id AND status = "validated") AS completed_count
             FROM lab_orders o WHERE o.patient_id = ?' . $orderTenantAnd . '
             ORDER BY o.order_date DESC LIMIT 50'
        );
        $stmt->execute([$patient['id']]);
        $orders = $stmt->fetchAll();
    } elseif ($error === '') {
        $error = 'لم يتم العثور على مريض بهذا الهاتف والرمز. تواصل مع المختبر للحصول على رمز البوابة.';
    }
}

?>
<!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="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%230f766e'/%3E%3Ctext x='50%25' y='50%25' font-family='Arial' font-size='28' font-weight='bold' fill='white' text-anchor='middle' dominant-baseline='central'%3ESL%3C/text%3E%3C/svg%3E">
    <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">
            <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'); ?><?php echo $labPhone ? ' — ' . htmlspecialchars($labPhone, ENT_QUOTES, 'UTF-8') : ''; ?></p>
                <div class="portal-brand-actions" style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px;justify-content:center;">
                    <a href="index.php?page=booking<?php echo $tenantSlug !== '' ? '&tenant=' . urlencode($tenantSlug) : ''; ?>" class="portal-btn" style="text-align:center;display:inline-block;text-decoration:none;flex:1;min-width:140px;">📅 حجز موعد جديد</a>
                    <a href="index.php?page=home_visit_request<?php echo $tenantSlug !== '' ? '&tenant=' . urlencode($tenantSlug) : ''; ?>" class="portal-btn" style="text-align:center;display:inline-block;text-decoration:none;background:linear-gradient(135deg,#64748b,#475569);flex:1;min-width:140px;">🏠 طلب زيارة منزلية</a>
                </div>
            </div>

            <?php if ($step === 'login'): ?>
            <?php if ($error): ?><div class="portal-alert portal-alert--danger"><?php echo htmlspecialchars($error, ENT_QUOTES, 'UTF-8'); ?></div><?php endif; ?>
            <form method="post" class="portal-form">
                <?php if ($tenantSlug !== ''): ?><input type="hidden" name="tenant" value="<?php echo htmlspecialchars($tenantSlug, ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
                <div class="portal-form-group portal-qr-section">
                    <label>الدخول بكود المريض أو QR</label>
                    <input type="text" name="qr_paste" placeholder="كود المريض (P123...) أو الصق محتوى QR" dir="ltr" style="text-align:left;" value="<?php echo htmlspecialchars($_POST['qr_paste'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <p class="portal-divider">— أو —</p>
                <div class="portal-form-group">
                    <label>رقم الهاتف</label>
                    <input type="tel" name="phone" placeholder="05xxxxxxxx" value="<?php echo htmlspecialchars($_POST['phone'] ?? ($phone ?: ''), ENT_QUOTES, 'UTF-8'); ?>">
                </div>
                <div class="portal-form-group">
                    <label>رمز البوابة <span class="portal-optional">(اختياري)</span></label>
                    <input type="text" name="portal_code" placeholder="اتركه فارغاً إن لم يُعطَك رمزاً">
                </div>
                <button type="submit" class="portal-btn">عرض النتائج</button>
            </form>

            <?php else: ?>
            <div class="portal-welcome">
                <p class="portal-welcome-text">أهلاً، <strong><?php echo htmlspecialchars($patient['full_name'], ENT_QUOTES, 'UTF-8'); ?></strong></p>
                <p class="portal-welcome-code">كود المريض: <code><?php echo htmlspecialchars($patient['patient_code'], ENT_QUOTES, 'UTF-8'); ?></code></p>
            </div>

            <div class="portal-section">
                <div class="portal-section-header">
                    <h2>طلباتك ونتائجك</h2>
                    <?php if (count($orders) > 0): ?>
                    <form method="get" class="portal-search-form">
                        <input type="hidden" name="page" value="patient_portal">
                        <?php if ($tenantSlug !== ''): ?><input type="hidden" name="tenant" value="<?php echo htmlspecialchars($tenantSlug, ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
                        <input type="search" name="order_q" placeholder="بحث برقم طلب أو تاريخ..." value="<?php echo htmlspecialchars($orderFilter ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                        <button type="submit">بحث</button>
                    </form>
                    <?php endif; ?>
                </div>

                <?php if (empty($orders)): ?>
                <div class="portal-empty">
                    <span class="portal-empty-icon">📋</span>
                    <p>لا توجد طلبات مسجلة.</p>
                </div>
                <?php else:
                    $orderStatusLabels = ['new' => 'جديد', 'in_progress' => 'قيد التنفيذ', 'completed' => 'مكتمل', 'cancelled' => 'ملغى']; ?>
                <div class="portal-orders">
                    <?php foreach ($orders as $o): 
                        $testsCnt = (int)($o['tests_count'] ?? 0);
                        $doneCnt = (int)($o['completed_count'] ?? 0);
                        $testsLabel = $testsCnt > 0 ? $doneCnt . '/' . $testsCnt : '—';
                        $pt = md5($o['id'] . ($patient['id'] ?? 0) . ($config['security']['portal_token_secret'] ?? 'lab_portal'));
                        $statusAr = $orderStatusLabels[$o['status'] ?? ''] ?? ($o['status'] ?? '—');
                    ?>
                    <div class="portal-order-card">
                        <div class="portal-order-main">
                            <span class="portal-order-num"><?php echo htmlspecialchars($o['order_number'], ENT_QUOTES, 'UTF-8'); ?></span>
                            <span class="portal-order-date"><?php echo htmlspecialchars($o['order_date'], ENT_QUOTES, 'UTF-8'); ?></span>
                            <span class="portal-order-tests"><?php echo $testsLabel; ?> فحص</span>
                            <span class="badge badge-<?php echo htmlspecialchars($o['status'], ENT_QUOTES, 'UTF-8'); ?>"><?php echo $statusAr; ?></span>
                        </div>
                        <a href="index.php?page=print_result&order_id=<?php echo (int)$o['id']; ?>&from_portal=1&token=<?php echo $pt; ?><?php if ($tenantSlug !== ''): ?>&tenant=<?php echo urlencode($tenantSlug); ?><?php endif; ?>" target="_blank" class="portal-order-action">عرض PDF / تحميل</a>
                        <?php if (($o['status'] ?? '') === 'completed' && empty($_SESSION['portal_rated_' . $o['id']])): ?>
                        <form method="post" class="portal-rate-form" style="margin-top:8px;display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                            <input type="hidden" name="action" value="rate">
                            <input type="hidden" name="order_id" value="<?php echo (int)$o['id']; ?>">
                            <?php if ($tenantSlug !== ''): ?><input type="hidden" name="tenant" value="<?php echo htmlspecialchars($tenantSlug, ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
                            <span style="font-size:0.9rem;">قيّم الخدمة:</span>
                            <select name="rating" style="padding:4px 8px;">
                                <option value="5">⭐⭐⭐⭐⭐</option>
                                <option value="4">⭐⭐⭐⭐</option>
                                <option value="3">⭐⭐⭐</option>
                                <option value="2">⭐⭐</option>
                                <option value="1">⭐</option>
                            </select>
                            <input type="text" name="comment" placeholder="تعليق (اختياري)" style="flex:1;min-width:120px;">
                            <button type="submit" class="portal-btn" style="padding:4px 12px;">إرسال</button>
                        </form>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>

            <div class="portal-footer-actions">
                <a href="index.php?page=patient_portal&logout=1<?php if ($tenantSlug !== ''): ?>&tenant=<?php echo urlencode($tenantSlug); ?><?php endif; ?>" class="portal-footer-link">تسجيل خروج</a>
                <button type="button" id="copyPortalBtn" class="portal-footer-btn">نسخ رابط البوابة</button>
            </div>
            <script>
            document.getElementById('copyPortalBtn').onclick=function(){
                var u=location.origin+location.pathname+'?page=patient_portal'<?php if ($tenantSlug !== ''): ?>+'&tenant=<?php echo htmlspecialchars(addslashes($tenantSlug), ENT_QUOTES, 'UTF-8'); ?>'<?php endif; ?>;
                if(navigator.clipboard){navigator.clipboard.writeText(u).then(function(){alert('تم نسخ رابط البوابة بنجاح');}).catch(function(){prompt('انسخ الرابط:',u);});}
                else{prompt('انسخ الرابط:',u);}
            };
            </script>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
