<?php
/**
 * إدارة العينات - باركود، موقع، تتبع، تسجيل التخلص
 */
use App\Core\Auth;
use App\Core\Tenant;

$tenantId = Tenant::id();
$action = $_GET['action'] ?? 'index';

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

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

if ($action === 'print_barcode') {
    $sid = (int)($_GET['id'] ?? 0);
    if ($sid > 0) {
        $stmt = $db->prepare("SELECT s.sample_code, s.barcode, o.order_number, p.full_name FROM samples s JOIN lab_orders o ON o.id = s.order_id JOIN patients p ON p.id = o.patient_id WHERE s.id = ?" . $orderTenantAnd);
        $stmt->execute([$sid]);
        $sample = $stmt->fetch();
        if ($sample) {
            $barcodeVal = !empty($sample['barcode']) ? $sample['barcode'] : $sample['sample_code'];
            $barcodeHeight = 60;
            $barcodeCode = 'Code128';
            try {
                $hasTenant = false;
                try { $db->query('SELECT tenant_id FROM settings LIMIT 1'); $hasTenant = true; } catch (Throwable $e) {}
                $st = $hasTenant ? $db->prepare('SELECT setting_key, setting_value FROM settings WHERE tenant_id = ? AND setting_key IN ("print_barcode_height","print_barcode_code")') : $db->query('SELECT setting_key, setting_value FROM settings WHERE setting_key IN ("print_barcode_height","print_barcode_code")');
                if ($hasTenant) $st->execute([$tenantId]);
                if ($st) foreach ($st->fetchAll() as $r) {
                    if ($r['setting_key'] === 'print_barcode_height') $barcodeHeight = min(120, max(30, (int)$r['setting_value']));
                    if ($r['setting_key'] === 'print_barcode_code') $barcodeCode = in_array($r['setting_value'], ['Code128','Code39','EAN-13']) ? $r['setting_value'] : 'Code128';
                }
            } catch (Throwable $e) {}
            header('Content-Type: text/html; charset=utf-8');
            echo '<!DOCTYPE html><html dir="rtl" lang="ar"><head><meta charset="UTF-8"><title>باركود عينة</title></head><body style="font-family:Arial;padding:20px;text-align:center;">';
            echo '<div style="border:1px solid #ccc;padding:16px;display:inline-block;">';
            echo '<div style="font-size:12px;margin-bottom:8px;">' . htmlspecialchars($sample['order_number'] . ' - ' . ($sample['full_name'] ?? ''), ENT_QUOTES, 'UTF-8') . '</div>';
            $showBarcodeText = true;
            try {
                $hasTenant = false;
                try { $db->query('SELECT tenant_id FROM settings LIMIT 1'); $hasTenant = true; } catch (Throwable $e) {}
                $st = $hasTenant ? $db->prepare('SELECT setting_value FROM settings WHERE tenant_id = ? AND setting_key = "print_barcode_show_text"') : $db->query('SELECT setting_value FROM settings WHERE setting_key = "print_barcode_show_text"');
                if ($hasTenant) $st->execute([$tenantId]);
                if ($st && ($r = $st->fetch())) $showBarcodeText = ($r['setting_value'] ?? '1') === '1';
            } catch (Throwable $e) {}
            echo '<img src="https://barcode.tec-it.com/barcode.ashx?data=' . urlencode($barcodeVal) . '&code=' . urlencode($barcodeCode) . '&dpi=96" alt="' . htmlspecialchars($barcodeVal, ENT_QUOTES, 'UTF-8') . '" style="height:' . (int)$barcodeHeight . 'px;">';
            if ($showBarcodeText) echo '<div style="font-size:11px;margin-top:4px;">' . htmlspecialchars($barcodeVal, ENT_QUOTES, 'UTF-8') . '</div>';
            echo '</div><script>window.print();</script></body></html>';
            exit;
        }
    }
}

if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST' && ($auth->can('results.edit') || $auth->can('results.validate'))) {
    $id = (int)($_POST['sample_id'] ?? 0);
    $location = trim($_POST['location'] ?? '');
    $disposalDate = trim($_POST['disposal_date'] ?? '') ?: null;
    $disposalMethod = trim($_POST['disposal_method'] ?? '') ?: null;
    $newStatus = trim($_POST['status'] ?? '') ?: null;

    if ($id > 0) {
        try {
            $updCols = ['s.location = ?', 's.disposal_date = ?'];
            $updVals = [$location ?: null, $disposalDate];
            try {
                $db->query('SELECT disposal_method FROM samples LIMIT 1');
                $updCols[] = 's.disposal_method = ?';
                $updVals[] = $disposalMethod;
            } catch (Throwable $e) {}
            $validStatuses = ['pending','collected','received','in_progress','used','disposed','rejected'];
            if ($newStatus && in_array($newStatus, $validStatuses, true)) {
                try {
                    $db->query('SELECT status FROM samples LIMIT 1');
                    $updCols[] = 's.status = ?';
                    $updVals[] = $newStatus;
                } catch (Throwable $e) {}
            }
            $updVals[] = $id;
            $updVals[] = $tenantId;
            $db->prepare("UPDATE samples s JOIN lab_orders o ON o.id = s.order_id SET " . implode(', ', $updCols) . " WHERE s.id = ? AND o.tenant_id = ?")->execute($updVals);
            $_SESSION['samples_msg'] = 'تم تحديث العينة.';
        } catch (Throwable $e) {}
    }
    $qs = array_filter(['q' => $_POST['_ret_q'] ?? null, 'location' => $_POST['_ret_location'] ?? null, 'disposed' => $_POST['_ret_disposed'] ?? null, 'status_filter' => $_POST['_ret_status'] ?? null, 'p' => $_POST['_ret_p'] ?? null]);
    header('Location: index.php?page=samples' . (empty($qs) ? '' : '&' . http_build_query($qs)));
    exit;
}

$samples = [];
$hasDisposalMethod = false;
try {
    $db->query('SELECT disposal_method FROM samples LIMIT 1');
    $hasDisposalMethod = true;
} catch (Throwable $e) {}
$selCols = "s.id, s.sample_code, s.barcode, s.sample_type, s.collection_datetime, s.received_datetime, s.status, s.location, s.disposal_date" . ($hasDisposalMethod ? ", s.disposal_method" : "") . ", o.id AS order_id, o.order_number, o.order_date, p.full_name AS patient_name";

$searchQ = trim($_GET['q'] ?? '');
$filterLocation = trim($_GET['location'] ?? '');
$filterDisposed = trim($_GET['disposed'] ?? ''); // all, yes, no
$filterStatus = trim($_GET['status_filter'] ?? '');
$hasStatusCol = false;
try { $db->query('SELECT status FROM samples LIMIT 1'); $hasStatusCol = true; } catch (Throwable $e) {}
$pageNum = max(1, (int)($_GET['p'] ?? 1));
$perPage = 25;
$offset = ($pageNum - 1) * $perPage;

$whereClause = ' o.tenant_id = ' . (int)$tenantId;
$params = [];
if ($searchQ !== '') {
    $whereClause .= ' AND (s.sample_code LIKE ? OR s.barcode LIKE ? OR o.order_number LIKE ? OR p.full_name LIKE ?)';
    $like = '%' . $searchQ . '%';
    $params = array_merge($params, [$like, $like, $like, $like]);
}
if ($filterLocation !== '') {
    if ($filterLocation === '_none') {
        $whereClause .= ' AND (s.location IS NULL OR s.location = \'\')';
    } else {
        $whereClause .= ' AND s.location = ?';
        $params[] = $filterLocation;
    }
}
if ($filterDisposed === 'yes') {
    $whereClause .= ' AND s.disposal_date IS NOT NULL AND s.disposal_date != \'\'';
} elseif ($filterDisposed === 'no') {
    $whereClause .= ' AND (s.disposal_date IS NULL OR s.disposal_date = \'\')';
}

try {
    $countSql = "SELECT COUNT(*) FROM samples s JOIN lab_orders o ON o.id = s.order_id JOIN patients p ON p.id = o.patient_id WHERE $whereClause";
    $countStmt = count($params) > 0 ? $db->prepare($countSql) : $db->query($countSql);
    if (count($params) > 0) $countStmt->execute($params);
    $totalSamples = (int)$countStmt->fetchColumn();
} catch (Throwable $e) { $totalSamples = 0; }

$totalPages = $totalSamples > 0 ? (int)ceil($totalSamples / $perPage) : 1;
$pageNum = min($pageNum, max(1, $totalPages));
$offset = ($pageNum - 1) * $perPage;

try {
    $sql = "SELECT $selCols FROM samples s JOIN lab_orders o ON o.id = s.order_id JOIN patients p ON p.id = o.patient_id WHERE $whereClause ORDER BY s.id DESC LIMIT " . (int)$perPage . " OFFSET " . (int)$offset;
    if (count($params) > 0) {
        $stmt = $db->prepare("SELECT $selCols FROM samples s JOIN lab_orders o ON o.id = s.order_id JOIN patients p ON p.id = o.patient_id WHERE $whereClause ORDER BY s.id DESC LIMIT " . (int)$perPage . " OFFSET " . (int)$offset);
        $stmt->execute($params);
        $samples = $stmt->fetchAll();
    } else {
        $samples = $db->query($sql)->fetchAll();
    }
} catch (Throwable $e) {
    try {
        $stmt = $db->prepare("SELECT $selCols FROM samples s JOIN lab_orders o ON o.id = s.order_id JOIN patients p ON p.id = o.patient_id WHERE o.tenant_id = ? ORDER BY s.id DESC LIMIT " . (int)$perPage . " OFFSET " . (int)$offset);
        $stmt->execute([$tenantId]);
        $samples = $stmt->fetchAll();
    } catch (Throwable $e2) {}
}

$locations = ['ثلاجة 1', 'ثلاجة 2', 'غرفة التحاليل', 'ملقم', 'مخزن', 'مختبر مركزي'];
$baseUrl = 'index.php?page=samples' . ($searchQ ? '&q=' . urlencode($searchQ) : '') . ($filterLocation ? '&location=' . urlencode($filterLocation) : '') . ($filterDisposed ? '&disposed=' . urlencode($filterDisposed) : '') . ($filterStatus ? '&status_filter=' . urlencode($filterStatus) : '');
?>
<div class="page-header">
    <h1>إدارة العينات</h1>
</div>

<?php if (!empty($_SESSION['samples_msg'])): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['samples_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['samples_msg']); ?></div>
<?php endif; ?>

<div class="stats-cards" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:12px;margin-bottom:16px;">
    <div class="stat-card" style="background:var(--bg-card);border:1px solid var(--border);border-radius:8px;padding:12px;">
        <div style="color:var(--text-muted);font-size:0.85em;">إجمالي العينات</div>
        <div style="font-size:1.4em;font-weight:600;"><?php echo number_format($totalSamples); ?></div>
    </div>
</div>

<div class="samples-filters-card">
    <form method="get" class="samples-filters-form">
        <input type="hidden" name="page" value="samples">
        <div class="samples-filters-row">
            <div class="samples-filter-search">
                <input type="search" name="q" placeholder="كود العينة، رقم الطلب، اسم المريض..." value="<?php echo htmlspecialchars($searchQ, ENT_QUOTES, 'UTF-8'); ?>">
            </div>
            <div class="samples-filter-group">
                <select name="location" onchange="this.form.submit()">
                    <option value="">كل المواقع</option>
                    <option value="_none" <?php echo $filterLocation === '_none' ? 'selected' : ''; ?>>بدون موقع</option>
                    <?php foreach ($locations as $loc): ?>
                    <option value="<?php echo htmlspecialchars($loc, ENT_QUOTES, 'UTF-8'); ?>" <?php echo $filterLocation === $loc ? 'selected' : ''; ?>><?php echo htmlspecialchars($loc, ENT_QUOTES, 'UTF-8'); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="samples-filter-group">
                <select name="disposed" onchange="this.form.submit()">
                    <option value="">كل الحالات</option>
                    <option value="no" <?php echo $filterDisposed === 'no' ? 'selected' : ''; ?>>لم يتخلص</option>
                    <option value="yes" <?php echo $filterDisposed === 'yes' ? 'selected' : ''; ?>>تم التخلص</option>
                </select>
            </div>
            <?php if ($hasStatusCol): ?>
            <div class="samples-filter-group">
                <select name="status_filter" onchange="this.form.submit()">
                    <option value="">كل الحالات</option>
                    <option value="pending" <?php echo $filterStatus === 'pending' ? 'selected' : ''; ?>>معلق</option>
                    <option value="collected" <?php echo $filterStatus === 'collected' ? 'selected' : ''; ?>>تم الجمع</option>
                    <option value="received" <?php echo $filterStatus === 'received' ? 'selected' : ''; ?>>مستلم</option>
                    <option value="in_progress" <?php echo $filterStatus === 'in_progress' ? 'selected' : ''; ?>>قيد التحليل</option>
                    <option value="used" <?php echo $filterStatus === 'used' ? 'selected' : ''; ?>>مستخدم</option>
                    <option value="disposed" <?php echo $filterStatus === 'disposed' ? 'selected' : ''; ?>>تم التخلص</option>
                    <option value="rejected" <?php echo $filterStatus === 'rejected' ? 'selected' : ''; ?>>مرفوض</option>
                </select>
            </div>
            <?php endif; ?>
            <div class="samples-filter-actions">
                <button type="submit" class="btn-primary btn-sm">بحث</button>
                <?php if ($searchQ !== '' || $filterLocation !== '' || $filterDisposed !== '' || $filterStatus !== ''): ?><a href="index.php?page=samples" class="btn-secondary btn-sm">إزالة الفلتر</a><?php endif; ?>
            </div>
        </div>
    </form>
</div>

<div class="section-card samples-page">
    <div class="table-wrapper samples-table-wrapper">
        <table class="table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>كود العينة</th>
                    <th>الطلب</th>
                    <th>المريض</th>
                    <th>التاريخ</th>
                    <?php if ($hasStatusCol): ?><th>الحالة</th><?php endif; ?>
                    <th>الموقع</th>
                    <th>التخلص</th>
                    <th>إجراء</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($samples as $s): ?>
                <tr>
                    <td><?php echo (int)$s['id']; ?></td>
                    <td><code><?php echo htmlspecialchars($s['sample_code'] ?? $s['barcode'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></code></td>
                    <td><a href="index.php?page=results&order_id=<?php echo (int)$s['order_id']; ?>"><?php echo htmlspecialchars($s['order_number'], ENT_QUOTES, 'UTF-8'); ?></a></td>
                    <td><?php echo htmlspecialchars($s['patient_name'], ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php
                    $dt = $s['received_datetime'] ?? $s['collection_datetime'] ?? null;
                    echo $dt ? htmlspecialchars(date('d/m/Y H:i', strtotime($dt)), ENT_QUOTES, 'UTF-8') : '—';
                ?></td>
                    <?php if ($hasStatusCol): ?>
                    <td><?php
                    $statusLabels = ['pending'=>'معلق','collected'=>'تم الجمع','received'=>'مستلم','in_progress'=>'قيد التحليل','used'=>'مستخدم','disposed'=>'تم التخلص','rejected'=>'مرفوض'];
                    echo htmlspecialchars($statusLabels[$s['status'] ?? ''] ?? $s['status'] ?? '—', ENT_QUOTES, 'UTF-8');
                    ?></td>
                    <?php endif; ?>
                    <td><?php echo htmlspecialchars($s['location'] ?? '—', ENT_QUOTES, 'UTF-8'); ?></td>
                    <td><?php
                    if (!empty($s['disposal_date'])) {
                        $disp = date('d/m/Y', strtotime($s['disposal_date']));
                        if (!empty($s['disposal_method'])) $disp .= ' (' . htmlspecialchars($s['disposal_method'], ENT_QUOTES, 'UTF-8') . ')';
                        echo $disp;
                    } else echo '—';
                ?></td>
                    <td>
                        <?php if ($auth->can('results.edit') || $auth->can('results.validate')): ?>
                        <button type="button" class="btn-secondary btn-sm" onclick="document.getElementById('editSample<?php echo (int)$s['id']; ?>').style.display='block'">تحديث</button>
                        <?php endif; ?>
                        <a href="index.php?page=samples&action=print_barcode&id=<?php echo (int)$s['id']; ?>" target="_blank" class="btn-secondary btn-sm">طباعة باركود</a>
                    </td>
                </tr>
                <?php if ($auth->can('results.edit') || $auth->can('results.validate')): ?>
                <tr id="editSample<?php echo (int)$s['id']; ?>" style="display:none;">
                    <td colspan="<?php echo 8 + ($hasStatusCol ? 1 : 0); ?>" style="background:#f8fafc;padding:16px;">
                        <form method="post" action="index.php?page=samples&action=update" class="samples-update-form">
                            <input type="hidden" name="sample_id" value="<?php echo (int)$s['id']; ?>">
                            <input type="hidden" name="_ret_q" value="<?php echo htmlspecialchars($searchQ ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="_ret_location" value="<?php echo htmlspecialchars($filterLocation ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="_ret_disposed" value="<?php echo htmlspecialchars($filterDisposed ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            <input type="hidden" name="_ret_p" value="<?php echo (int)$pageNum; ?>">
                            <label>الموقع:</label>
                            <select name="location" style="min-width:140px;">
                                <option value="">—</option>
                                <?php foreach ($locations as $loc): ?>
                                <option value="<?php echo htmlspecialchars($loc, ENT_QUOTES, 'UTF-8'); ?>" <?php echo ($s['location'] ?? '') === $loc ? 'selected' : ''; ?>><?php echo htmlspecialchars($loc, ENT_QUOTES, 'UTF-8'); ?></option>
                                <?php endforeach; ?>
                                <option value="_other">أخرى...</option>
                            </select>
                            <label>تاريخ التخلص:</label>
                            <input type="datetime-local" name="disposal_date" value="<?php echo htmlspecialchars($s['disposal_date'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                            <?php if ($hasDisposalMethod): ?><label>طريقة التخلص:</label>
                            <input type="text" name="disposal_method" placeholder="حرق، تعقيم، إلخ" value="<?php echo htmlspecialchars($s['disposal_method'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"><?php endif; ?>
                            <button type="submit" class="btn-primary btn-sm">حفظ</button>
                            <button type="button" class="btn-secondary btn-sm" onclick="document.getElementById('editSample<?php echo (int)$s['id']; ?>').style.display='none'">إلغاء</button>
                        </form>
                    </td>
                </tr>
                <?php endif; ?>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php if (empty($samples)): ?>
    <p class="patients-empty">لا توجد عينات مطابقة للبحث. <a href="index.php?page=samples">عرض الكل</a></p>
    <?php elseif ($totalPages > 1): ?>
    <div class="pagination-bar" style="display:flex;align-items:center;gap:8px;margin-top:16px;flex-wrap:wrap;">
        <span style="color:var(--text-muted);">صفحة <?php echo $pageNum; ?> من <?php echo $totalPages; ?> (<?php echo number_format($totalSamples); ?> عينة)</span>
        <?php if ($pageNum > 1): ?><a href="<?php echo $baseUrl . '&p=' . ($pageNum - 1); ?>" class="btn-secondary btn-sm">← السابق</a><?php endif; ?>
        <?php if ($pageNum < $totalPages): ?><a href="<?php echo $baseUrl . '&p=' . ($pageNum + 1); ?>" class="btn-secondary btn-sm">التالي →</a><?php endif; ?>
    </div>
    <?php endif; ?>
</div>

<style>
/* بطاقة فلترة العينات */
.samples-filters-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 16px 20px;
    margin-bottom: 20px;
}
.samples-filters-form .samples-filters-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 12px;
}
.samples-filter-search {
    flex: 1;
    min-width: 180px;
}
.samples-filter-search input {
    width: 100%;
    padding: 10px 14px;
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    font-size: 0.95rem;
    background: var(--bg-input);
}
.samples-filter-search input:focus {
    outline: none;
    border-color: var(--primary);
}
.samples-filter-group select {
    min-width: 140px;
    padding: 10px 14px;
    border: 1px solid var(--border);
    border-radius: var(--radius-sm);
    font-size: 0.95rem;
    background: var(--bg-input);
}
.samples-filter-group select:focus {
    outline: none;
    border-color: var(--primary);
}
.samples-filter-actions {
    display: flex;
    gap: 8px;
    align-items: center;
}
@media (max-width: 600px) {
    .samples-filters-row { flex-direction: column; align-items: stretch; }
    .samples-filter-search { min-width: 100%; }
    .samples-filter-group select { min-width: 100%; }
    .samples-filter-actions { justify-content: flex-end; }
}
.samples-table-wrapper { max-height: 420px; overflow-y: auto; overflow-x: auto; }
.samples-page .table thead th { position: sticky; top: 0; background: var(--bg-input); z-index: 1; box-shadow: 0 1px 0 var(--border); }
.samples-page .samples-update-form { display: grid; grid-template-columns: auto 1fr auto 1fr auto auto; gap: 10px; align-items: center; flex-wrap: wrap; }
.samples-page .samples-update-form label { margin: 0; white-space: nowrap; }
@media (max-width: 768px) { .samples-page .samples-update-form { grid-template-columns: 1fr 1fr; } }
</style>
