<?php

use App\Core\Tenant;

$q = trim($_GET['q'] ?? '');
$patients = [];
$orders = [];
$doctors = [];
$tenantId = Tenant::id();

$directOrder = null;
if (strlen($q) >= 2) {
    $orderTenantAnd = '';
    $orderTenantParams = [];
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $orderTenantAnd = ' AND o.tenant_id = ?'; $orderTenantParams[] = $tenantId; } catch (Throwable $e) {}
    if (preg_match('/^O\d+$/i', $q) || (ctype_digit($q) && strlen($q) >= 8)) {
        try {
            $orderNum = preg_match('/^O/i', $q) ? $q : 'O' . $q;
            $stmt = $db->prepare('SELECT o.id FROM lab_orders o WHERE o.order_number = ?' . $orderTenantAnd . ' LIMIT 1');
            $stmt->execute(array_merge([$orderNum], $orderTenantParams));
            $directOrder = $stmt->fetch();
            if (!$directOrder) {
                $stmt = $db->prepare('SELECT o.id FROM lab_orders o WHERE o.order_number LIKE ?' . $orderTenantAnd . ' LIMIT 1');
                $stmt->execute(array_merge(['%' . $q . '%'], $orderTenantParams));
                $directOrder = $stmt->fetch();
            }
        } catch (Throwable $e) {}
    }
    if (!$directOrder) {
        try {
            $db->query('SELECT id FROM samples LIMIT 1');
            $stmt = $db->prepare('SELECT s.order_id FROM samples s JOIN lab_orders o ON o.id = s.order_id WHERE (s.sample_code = ? OR s.barcode = ?) AND o.tenant_id = ? LIMIT 1');
            $stmt->execute([$q, $q, $tenantId]);
            $row = $stmt->fetch();
            if ($row) $directOrder = ['id' => $row['order_id']];
        } catch (Throwable $e) {
            try {
            $stmt = $db->prepare('SELECT order_id FROM samples WHERE sample_code = ? OR barcode = ? LIMIT 1');
            $stmt->execute([$q, $q]);
                $row = $stmt->fetch();
                if ($row) $directOrder = ['id' => $row['order_id']];
            } catch (Throwable $e2) {}
        }
    }
    try {
        $stmt = $db->prepare('SELECT id, patient_code, full_name, phone FROM patients WHERE (full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ?) AND tenant_id = ? ORDER BY id DESC LIMIT 15');
        $like = '%' . $q . '%';
        $stmt->execute([$like, $like, $like, $tenantId]);
        $patients = $stmt->fetchAll();
    } catch (Throwable $e) {
        try {
            $stmt = $db->prepare('SELECT id, patient_code, full_name, phone FROM patients WHERE full_name LIKE ? OR patient_code LIKE ? OR phone LIKE ? ORDER BY id DESC LIMIT 15');
            $like = '%' . $q . '%';
            $stmt->execute([$like, $like, $like]);
            $patients = $stmt->fetchAll();
        } catch (Throwable $e2) {}
    }
    try {
        $tenantOrd = '';
        try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantOrd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
        $stmt = $db->prepare(
            'SELECT o.id, o.order_number, o.order_date, p.full_name AS patient_name
             FROM lab_orders o JOIN patients p ON p.id = o.patient_id
             WHERE (o.order_number LIKE ? OR p.full_name LIKE ?)' . $tenantOrd . '
             ORDER BY o.id DESC LIMIT 15'
        );
        $stmt->execute([$like, $like]);
        $orders = $stmt->fetchAll();
    } catch (Throwable $e) {
        try {
            $stmt = $db->prepare('SELECT o.id, o.order_number, o.order_date, p.full_name AS patient_name FROM lab_orders o JOIN patients p ON p.id = o.patient_id WHERE o.order_number LIKE ? OR p.full_name LIKE ? ORDER BY o.id DESC LIMIT 15');
            $stmt->execute([$like, $like]);
            $orders = $stmt->fetchAll();
        } catch (Throwable $e2) {}
    }
    try {
        $like = '%' . $q . '%';
        try {
            $db->query('SELECT tenant_id FROM doctors LIMIT 1');
            $stmt = $db->prepare('SELECT id, full_name, clinic_name FROM doctors WHERE (full_name LIKE ? OR clinic_name LIKE ?) AND tenant_id = ? ORDER BY full_name LIMIT 10');
            $stmt->execute([$like, $like, $tenantId]);
        } catch (Throwable $e) {
            $stmt = $db->prepare('SELECT id, full_name, clinic_name FROM doctors WHERE full_name LIKE ? OR clinic_name LIKE ? ORDER BY full_name LIMIT 10');
            $stmt->execute([$like, $like]);
        }
        $doctors = $stmt->fetchAll();
    } catch (Throwable $e) {}
}
?>
<div class="page-header page-header--stack">
    <div class="page-header-top">
        <h1>🔍 بحث</h1>
    </div>
    <p class="page-header-desc">بحث موحّد عن مرضى، طلبات، عينات، وأطباء. يدعم مسح الباركود في الحقل أدناه للانتقال السريع للطلب.</p>
    <nav class="lab-quick-nav" aria-label="اختصارات ذات صلة">
        <?php if (isset($auth) && $auth->can('patients.view')): ?><a href="index.php?page=patients">المرضى</a><?php endif; ?>
        <?php if (isset($auth) && $auth->can('orders.view')): ?><a href="index.php?page=orders">الطلبات</a><?php endif; ?>
        <?php if (isset($auth) && $auth->can('results.view')): ?><a href="index.php?page=results">النتائج</a><?php endif; ?>
    </nav>
</div>
<form method="get" class="form-grid" style="margin-bottom:24px;">
    <input type="hidden" name="page" value="search">
    <div style="display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end;">
        <div style="flex:1;min-width:250px;">
            <label>الكلمة المطلوبة / مسح الباركود</label>
            <input type="search" name="q" id="searchBarcodeInput" value="<?php echo htmlspecialchars($q, ENT_QUOTES, 'UTF-8'); ?>" placeholder="اسم مريض، رقم طلب، باركود عينة، طبيب..." style="width:100%;" autofocus>
        </div>
        <button type="submit">بحث</button>
    </div>
</form>

<?php if ($q !== '' && $directOrder): ?>
<div class="section-card" style="border-right:4px solid var(--accent);margin-bottom:16px;">
    <p><strong>طلب مباشر (من رقم الطلب أو الباركود):</strong> <a href="index.php?page=results&order_id=<?php echo (int)$directOrder['id']; ?>">عرض نتائج الطلب</a> | <a href="index.php?page=print_result&order_id=<?php echo (int)$directOrder['id']; ?>" target="_blank">طباعة</a></p>
</div>
<?php endif; ?>
<script>
document.addEventListener('DOMContentLoaded', function(){
    var inp = document.getElementById('searchBarcodeInput');
    if (inp) inp.focus();
});
</script>
<?php if ($q !== ''): ?>
<div class="section-card">
    <h3>المرضى (<?php echo count($patients); ?>)</h3>
    <div class="table-wrapper">
        <table class="table">
            <thead><tr><th>الكود</th><th>الاسم</th><th>الهاتف</th><th>إجراء</th></tr></thead>
            <tbody>
            <?php foreach ($patients as $p): ?>
                <tr>
                    <td><?php echo htmlspecialchars($p['patient_code'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($p['full_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($p['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><a href="index.php?page=patients&action=view&id=<?php echo (int)$p['id']; ?>">ملف</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<div class="section-card">
    <h3>الطلبات (<?php echo count($orders); ?>)</h3>
    <div class="table-wrapper">
        <table class="table">
            <thead><tr><th>رقم الطلب</th><th>التاريخ</th><th>المريض</th><th>إجراء</th></tr></thead>
            <tbody>
            <?php foreach ($orders as $o): ?>
                <tr>
                    <td><?php echo htmlspecialchars($o['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($o['order_date'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($o['patient_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <a href="index.php?page=results&order_id=<?php echo (int)$o['id']; ?>">نتائج</a>
                        <a href="index.php?page=print_result&order_id=<?php echo (int)$o['id']; ?>" target="_blank">طباعة</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<div class="section-card">
    <h3>الأطباء (<?php echo count($doctors); ?>)</h3>
    <div class="table-wrapper">
        <table class="table">
            <thead><tr><th>الاسم</th><th>العيادة</th><th>إجراء</th></tr></thead>
            <tbody>
            <?php foreach ($doctors as $d): ?>
                <tr>
                    <td><?php echo htmlspecialchars($d['full_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($d['clinic_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><a href="index.php?page=orders&doctor_id=<?php echo (int)$d['id']; ?>">طلباته</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
<?php if (empty($patients) && empty($orders) && empty($doctors) && strlen($q) >= 2): ?>
<p style="color:var(--text-secondary);">لا توجد نتائج.</p>
<?php endif; ?>
<?php endif; ?>
