<?php
/**
 * قائمة عمل الفني - عرض يومي للمريض والفحوصات المطلوبة
 */
use App\Core\Auth;
use App\Core\Tenant;

$tenantId = Tenant::id();
$userBranchId = ($auth instanceof Auth) ? $auth->branchId() : null;

if (!($auth instanceof Auth) || !$auth->can('worklist.view')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول إلى قائمة العمل';
    return;
}

$workDate = $_GET['date'] ?? date('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $workDate)) {
    $workDate = date('Y-m-d');
}
$showAllPending = isset($_GET['all']) && $_GET['all'] === '1';
$branchFilter = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : 0;
if ($userBranchId !== null && $branchFilter === 0) {
    $branchFilter = $userBranchId;
}

$orderTenantAnd = '';
try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $orderTenantAnd = ' AND o.tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}

$branchCond = $branchFilter > 0 ? ' AND o.branch_id = ' . (int)$branchFilter : '';

$worklist = [];
try {
    $dateCond = $showAllPending ? " AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) " : " AND DATE(o.order_date) = :work_date ";
    $params = $showAllPending ? [] : ['work_date' => $workDate];
    $testTenantAnd = '';
    try { $db->query('SELECT tenant_id FROM tests LIMIT 1'); $testTenantAnd = ' AND t.tenant_id = :ttid'; $params['ttid'] = $tenantId; } catch (Throwable $e) {}
    $hasPriority = false;
    try { $db->query('SELECT priority FROM lab_orders LIMIT 1'); $hasPriority = true; } catch (Throwable $e) {}
    $hasDoctorCol = false;
    try { $db->query('SELECT doctor_id FROM lab_orders LIMIT 1'); $hasDoctorCol = true; } catch (Throwable $e) {}
    $hasDoctorsTbl = false;
    try { $db->query('SELECT 1 FROM doctors LIMIT 1'); $hasDoctorsTbl = true; } catch (Throwable $e) {}
    $doctorSel = ($hasDoctorsTbl && $hasDoctorCol)
        ? ', o.doctor_id, (SELECT d.full_name FROM doctors d WHERE d.id = o.doctor_id LIMIT 1) AS doctor_name'
        : ($hasDoctorCol ? ', o.doctor_id, NULL AS doctor_name' : '');
    if ($hasDoctorCol) {
        $orderBy = $hasPriority ? "ORDER BY FIELD(COALESCE(o.priority,'normal'), 'urgent', 'high', 'normal'), (CASE WHEN COALESCE(o.doctor_id,0) > 0 THEN 0 ELSE 1 END), o.order_date DESC, o.id, oi.id" : "ORDER BY (CASE WHEN COALESCE(o.doctor_id,0) > 0 THEN 0 ELSE 1 END), o.order_date DESC, o.id, oi.id";
    } else {
        $orderBy = $hasPriority ? "ORDER BY FIELD(COALESCE(o.priority,'normal'), 'urgent', 'high', 'normal'), o.order_date DESC, o.id, oi.id" : "ORDER BY o.order_date DESC, o.id, oi.id";
    }
    $priorityCol = $hasPriority ? ', o.priority' : '';
    $sql = "SELECT o.id AS order_id, o.order_number, o.order_date $priorityCol $doctorSel, p.id AS patient_id, p.full_name AS patient_name, p.phone,
         oi.id AS item_id, oi.status AS item_status, t.name AS test_name, t.test_code,
         (SELECT COUNT(*) FROM order_items oi2 WHERE oi2.order_id = o.id AND oi2.status IN ('pending','in_progress')) AS pending_count
         FROM order_items oi
         JOIN lab_orders o ON o.id = oi.order_id
         JOIN patients p ON p.id = o.patient_id
         JOIN tests t ON t.id = oi.test_id
         WHERE 1=1 $dateCond
         AND oi.status IN ('pending','in_progress')
         AND o.status != 'cancelled'
         $orderTenantAnd $branchCond $testTenantAnd
         $orderBy
         LIMIT 200";
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $worklist = $stmt->fetchAll();
} catch (Throwable $e) {}

$branchesForFilter = [];
try {
    try {
        $db->query('SELECT tenant_id FROM branches LIMIT 1');
        $stmt = $db->prepare('SELECT id, name FROM branches WHERE is_active = 1 AND tenant_id = ? ORDER BY name');
        $stmt->execute([$tenantId]);
    } catch (Throwable $e) {
        $stmt = $db->query('SELECT id, name FROM branches WHERE is_active = 1 ORDER BY name');
    }
    $branchesForFilter = $stmt->fetchAll();
} catch (Throwable $e) {}

$statusLabels = ['pending' => 'معلق', 'in_progress' => 'قيد التنفيذ', 'validated' => 'معتمد'];
?>
<div class="page-header page-header--stack">
    <div class="page-header-top">
        <h1>📋 قائمة العمل</h1>
        <form method="get" action="index.php" class="worklist-filters" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
            <input type="hidden" name="page" value="worklist">
            <label>التاريخ:</label>
            <input type="date" name="date" value="<?php echo htmlspecialchars($workDate, ENT_QUOTES, 'UTF-8'); ?>" onchange="this.form.submit()" <?php echo $showAllPending ? '' : ''; ?>>
            <label class="settings-checkbox" style="margin:0;display:inline-flex;">
                <input type="checkbox" name="all" value="1" onchange="this.form.submit()" <?php echo $showAllPending ? 'checked' : ''; ?>>
                <span>عرض كل المعلقة (30 يوم)</span>
            </label>
            <?php if (count($branchesForFilter) > 1): ?>
            <label>الفرع:</label>
            <select name="branch_id" onchange="this.form.submit()">
                <option value="0" <?php echo $branchFilter === 0 ? 'selected' : ''; ?>>كل الفروع</option>
                <?php foreach ($branchesForFilter as $br): ?>
                <option value="<?php echo (int)$br['id']; ?>" <?php echo $branchFilter === (int)$br['id'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($br['name'], ENT_QUOTES, 'UTF-8'); ?></option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
        </form>
    </div>
    <p class="page-header-desc">عرض يومي للفحوصات المعلقة مجمّعاً حسب الطلب، مع الأولوية ومصدر الطلب (طبيب أو مختبر). انتقل لإدخال النتائج من عمود الإجراء.</p>
    <nav class="lab-quick-nav" aria-label="اختصارات ذات صلة">
        <?php if ($auth->can('results.view')): ?><a href="index.php?page=results">نتائج الفحوصات</a><?php endif; ?>
        <?php if ($auth->can('orders.view')): ?><a href="index.php?page=orders">طلبات الفحوصات</a><?php endif; ?>
        <?php if ($auth->can('results.view')): ?><a href="index.php?page=samples">العينات</a><?php endif; ?>
    </nav>
</div>

<div class="section-card">
    <?php if (empty($worklist)): ?>
    <p class="patients-empty"><?php echo $showAllPending ? 'لا توجد فحوصات معلقة خلال آخر 30 يوم.' : 'لا توجد فحوصات معلقة لهذا اليوم.'; ?></p>
    <?php else: ?>
    <?php
    $grouped = [];
    foreach ($worklist as $row) {
        $key = $row['order_id'];
        if (!isset($grouped[$key])) {
            $grouped[$key] = [
                'order_id' => $row['order_id'],
                'order_number' => $row['order_number'],
                'order_date' => $row['order_date'] ?? '',
                'priority' => $row['priority'] ?? 'normal',
                'doctor_id' => (int)($row['doctor_id'] ?? 0),
                'doctor_name' => (string)($row['doctor_name'] ?? ''),
                'patient_id' => $row['patient_id'],
                'patient_name' => $row['patient_name'],
                'phone' => $row['phone'],
                'pending_count' => $row['pending_count'],
                'items' => []
            ];
        }
        $grouped[$key]['items'][] = [
            'item_id' => $row['item_id'],
            'test_name' => $row['test_name'],
            'test_code' => $row['test_code'],
            'item_status' => $row['item_status']
        ];
    }
    ?>
    <div class="table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>رقم الطلب</th>
                    <?php if ($hasPriority): ?><th>الأولوية</th><?php endif; ?>
                    <?php if ($showAllPending): ?><th>التاريخ</th><?php endif; ?>
                    <th>المصدر</th>
                    <th>المريض</th>
                    <th>الهاتف</th>
                    <th>الفحوصات المطلوبة</th>
                    <th>إجراء</th>
                </tr>
            </thead>
            <tbody>
            <?php $n = 1; foreach ($grouped as $g): ?>
                <tr>
                    <td><?php echo $n++; ?></td>
                    <td><?php echo htmlspecialchars($g['order_number'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <?php if ($hasPriority): ?><td><span style="padding:2px 6px;border-radius:4px;font-size:0.85em;background:<?php echo ($g['priority'] ?? '') === 'urgent' ? '#dc2626' : (($g['priority'] ?? '') === 'high' ? '#f59e0b' : '#6b7280'); ?>;color:white;"><?php echo ($g['priority'] ?? '') === 'urgent' ? 'عاجل' : (($g['priority'] ?? '') === 'high' ? 'عالي' : 'عادي'); ?></span></td><?php endif; ?>
                    <?php if ($showAllPending): ?><td><?php echo htmlspecialchars($g['order_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td><?php endif; ?>
                    <td><?php
                        if (($g['doctor_id'] ?? 0) > 0) {
                            $dn = trim((string)($g['doctor_name'] ?? ''));
                            echo '<span style="color:#0d9488;font-weight:600;">طبيب</span>';
                            if ($dn !== '') {
                                echo ' <small>' . htmlspecialchars($dn, ENT_QUOTES, 'UTF-8') . '</small>';
                            }
                        } else {
                            echo '<span style="color:var(--text-muted);">مختبر</span>';
                        }
                    ?></td>
                    <td><?php echo htmlspecialchars($g['patient_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php echo htmlspecialchars($g['phone'] ?? '', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td>
                        <ul style="margin:0;padding-right:16px;list-style:disc;">
                        <?php foreach ($g['items'] as $it): ?>
                            <li><span class="badge badge-<?php echo $it['item_status']; ?>"><?php echo htmlspecialchars($it['test_name'], ENT_QUOTES, 'UTF-8'); ?></span></li>
                        <?php endforeach; ?>
                        </ul>
                    </td>
                    <td>
                        <a href="index.php?page=results&order_id=<?php echo (int)$g['order_id']; ?>" class="btn-primary">إدخال النتائج</a>
                        <a href="index.php?page=patients&action=view&id=<?php echo (int)$g['patient_id']; ?>" class="btn-secondary">ملف المريض</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>
