<?php
/**
 * Counter - Count Items (Data Entry & Submission)
 *
 * Primary data entry point for the counter to input physical
 * stock counts and submit counted data for verification.
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
require_once __DIR__ . '/../middleware/workflow_middleware.php';
counter_only();

$pageTitle = 'Count Items';
$db = Database::getInstance();
$userId = SessionManager::getUserId();

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Csrf::check();
    $action = $_POST['action'] ?? '';

    if ($action === 'start_count') {
        $assignmentId = (int)($_POST['assignment_id'] ?? 0);

        if (!validate_assignment_ownership($assignmentId, $userId)) {
            set_error('Assignment not found or access denied.');
            redirect(APP_URL . '/counter/count_items.php');
        }

        if (!validate_assignment_status($assignmentId, ['pending', 'recount'])) {
            set_error('This assignment cannot be started in its current status.');
            redirect(APP_URL . '/counter/count_items.php');
        }

        $db->update('assignments', [
            'status' => ASSIGN_IN_PROGRESS,
            'updated_at' => date('Y-m-d H:i:s'),
        ], 'id = ? AND counter_id = ?', [$assignmentId, $userId]);

        log_action($userId, 'start_count', 'assignment', $assignmentId);
        set_success('Count started. Enter your physical count below.');

        redirect(APP_URL . '/counter/count_items.php?assignment_id=' . $assignmentId);
    }

    if ($action === 'submit_count') {
        $assignmentId = (int)($_POST['assignment_id'] ?? 0);
        $countedQuantity = (float)($_POST['counted_quantity'] ?? 0);
        $countMethod = $_POST['count_method'] ?? 'manual';
        $notes = trim($_POST['notes'] ?? '');

        if (!validate_assignment_ownership($assignmentId, $userId)) {
            set_error('Assignment not found or access denied.');
            redirect(APP_URL . '/counter/count_items.php');
        }

        if (!validate_assignment_status($assignmentId, [ASSIGN_IN_PROGRESS])) {
            set_error('This assignment is not in progress. Please start counting first.');
            redirect(APP_URL . '/counter/count_items.php?assignment_id=' . $assignmentId);
        }

        if ($countedQuantity < 0) {
            set_error('Counted quantity cannot be negative.');
            redirect(APP_URL . '/counter/count_items.php?assignment_id=' . $assignmentId);
        }

        $db->beginTransaction();
        try {
            // Check if entry already exists
            $existing = $db->fetch(
                "SELECT id FROM count_entries WHERE assignment_id = ? AND counter_id = ?",
                [$assignmentId, $userId]
            );

            if ($existing) {
                $db->update('count_entries', [
                    'counted_quantity' => $countedQuantity,
                    'count_method' => $countMethod,
                    'notes' => $notes ?: null,
                    'counted_at' => date('Y-m-d H:i:s'),
                ], 'id = ?', [$existing['id']]);
            } else {
                $db->insert('count_entries', [
                    'assignment_id' => $assignmentId,
                    'counter_id' => $userId,
                    'counted_quantity' => $countedQuantity,
                    'count_method' => $countMethod,
                    'notes' => $notes ?: null,
                ]);
            }

            // Update assignment status to counted
            $db->update('assignments', [
                'status' => ASSIGN_COUNTED,
                'completed_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ], 'id = ?', [$assignmentId]);

            $db->commit();
            log_action($userId, 'submit_count', 'assignment', $assignmentId, [
                'counted_quantity' => $countedQuantity,
                'count_method' => $countMethod,
            ]);

            set_success('Count submitted successfully for verification.');
            redirect(APP_URL . '/counter/count_items.php');
        } catch (Exception $e) {
            $db->rollBack();
            set_error('Failed to submit count: ' . $e->getMessage());
            redirect(APP_URL . '/counter/count_items.php?assignment_id=' . $assignmentId);
        }
    }

    if ($action === 'bulk_submit_counts') {
        $bulkCounts = $_POST['bulk_counts'] ?? [];
        $individualQuantities = $_POST['individual_quantity'] ?? [];
        $countMethod = $_POST['count_method'] ?? 'manual';
        $notes = trim($_POST['notes'] ?? '');

        // DEBUG: Log incoming data
        error_log("BULK SUBMIT DEBUG - user: $userId, bulkCounts: " . count($bulkCounts) . ", quantities: " . count($individualQuantities));

        if (empty($bulkCounts)) {
            set_error('No assignments selected.');
            error_log("BULK SUBMIT DEBUG - Empty bulkCounts, redirecting");
            redirect(APP_URL . '/counter/count_items.php');
        }

        // Fetch assignments for validation
        $assignmentIds = array_keys($bulkCounts);
        error_log("BULK SUBMIT DEBUG - assignmentIds: " . implode(',', $assignmentIds));
        
        $userAssignments = $db->fetchAll(
            "SELECT id, status FROM assignments WHERE id IN (" . implode(',', array_fill(0, count($assignmentIds), '?')) . ") AND counter_id = ?",
            array_merge($assignmentIds, [$userId])
        );
        error_log("BULK SUBMIT DEBUG - fetched assignments: " . count($userAssignments) . ", details: " . json_encode($userAssignments));

        $validAssignments = [];
        foreach ($userAssignments as $a) {
            if (in_array($a['status'], ['pending', 'in_progress', 'recount'])) {
                $validAssignments[] = $a['id'];
            }
        }
        error_log("BULK SUBMIT DEBUG - validAssignments: " . json_encode($validAssignments));

        if (empty($validAssignments)) {
            set_error('No valid assignments available for counting.');
            error_log("BULK SUBMIT DEBUG - No valid assignments, redirecting");
            redirect(APP_URL . '/counter/count_items.php');
        }

        $db->beginTransaction();
        try {
            $successCount = 0;
            foreach ($validAssignments as $assignmentId) {
                try {
                    $countedQuantity = isset($individualQuantities[$assignmentId]) ? (float)$individualQuantities[$assignmentId] : 0;
                    error_log("BULK SUBMIT DEBUG - assignment $assignmentId qty: $countedQuantity");
                    
                    if ($countedQuantity < 0) {
                        error_log("BULK SUBMIT DEBUG - skipping invalid qty for $assignmentId");
                        continue;
                    }

                    // Upsert count entry
                    $existing = $db->fetch(
                        "SELECT id FROM count_entries WHERE assignment_id = ? AND counter_id = ?",
                        [$assignmentId, $userId]
                    );

                    if ($existing) {
                        $db->update('count_entries', [
                            'counted_quantity' => $countedQuantity,
                            'count_method' => $countMethod,
                            'notes' => $notes ?: null,
                            'counted_at' => date('Y-m-d H:i:s'),
                        ], 'id = ?', [$existing['id']]);
                    } else {
                        $db->insert('count_entries', [
                            'assignment_id' => $assignmentId,
                            'counter_id' => $userId,
                            'counted_quantity' => $countedQuantity,
                            'count_method' => $countMethod,
                            'notes' => $notes ?: null,
                        ]);
                    }

                    // Update assignment
                    $db->update('assignments', [
                        'status' => ASSIGN_COUNTED,
                        'completed_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s'),
                    ], 'id = ?', [$assignmentId]);

                    $successCount++;
                    error_log("BULK SUBMIT DEBUG - success for $assignmentId");
                } catch (Exception $e) {
                    error_log("BULK SUBMIT DEBUG - failed for $assignmentId: " . $e->getMessage());
                    // Continue with others
                }
            }
            error_log("BULK SUBMIT DEBUG - total success: $successCount");

            $db->commit();
            log_action($userId, 'bulk_submit_counts', 'assignments', 0, [
                'count' => $successCount,
                'method' => $countMethod,
            ]);

            set_success("$successCount assignments counted and submitted successfully.");
            redirect(APP_URL . '/counter/count_items.php');
        } catch (Exception $e) {
            $db->rollBack();
            set_error('Bulk submit failed: ' . $e->getMessage());
            redirect(APP_URL . '/counter/count_items.php');
        }
    }
}

// Filters
$sessionFilter = $_GET['session_id'] ?? '';
$assignmentId = (int)($_GET['assignment_id'] ?? 0);

// If specific assignment requested, show count form
$activeAssignment = null;
if ($assignmentId) {
$activeAssignment = $db->fetch("
        SELECT a.*, s.name as session_name, i.Item_Code as item_code, i.Item_Description as item_name,
               i.Item_Description as item_description, i.System_Qty as system_quantity, i.Stores, i.Rack, i.Level, i.Bin, a.zone,
               i.Uom as unit_of_measure, i.Item_Group as category,
               ce.counted_quantity as existing_count, ce.count_method as existing_method,
               ce.notes as existing_notes
        FROM assignments a
        JOIN sessions s ON a.session_id = s.id
        JOIN items i ON a.item_id = i.id
        LEFT JOIN count_entries ce ON ce.assignment_id = a.id AND ce.counter_id = a.counter_id
        WHERE a.id = ? AND a.counter_id = ?
    ", [$assignmentId, $userId]);

    if (!$activeAssignment) {
        set_error('Assignment not found.');
        redirect(APP_URL . '/counter/count_items.php');
    }
}

// Build assignment list for the table
$where = "a.counter_id = ? AND a.status IN ('pending', 'in_progress', 'counted', 'recount')";
$params = [$userId];
if ($sessionFilter) {
    $where .= " AND a.session_id = ?";
    $params[] = $sessionFilter;
}

// Location filters
$storeFilter = $_GET['store_filter'] ?? '';
if ($storeFilter) {
    $where .= " AND i.Stores = ?";
    $params[] = $storeFilter;
}

$rackFilter = $_GET['rack_filter'] ?? '';
if ($rackFilter) {
    $where .= " AND i.Rack = ?";
    $params[] = $rackFilter;
}

$levelFilter = $_GET['level_filter'] ?? '';
if ($levelFilter) {
    $where .= " AND i.Level = ?";
    $params[] = $levelFilter;
}

$binFilter = $_GET['bin_filter'] ?? '';
if ($binFilter) {
    $where .= " AND i.Bin = ?";
    $params[] = $binFilter;
}

$itemGroupFilter = $_GET['item_group'] ?? '';
if ($itemGroupFilter) {
    $where .= " AND i.Item_Group = ?";
    $params[] = $itemGroupFilter;
}

    $assignments = $db->fetchAll("
    SELECT a.id, a.*, s.name as session_name, i.Item_Code as item_code, i.Item_Description as item_name,
           i.System_Qty as system_quantity, i.Stores, i.Rack, i.Level, i.Bin, i.Uom as unit_of_measure, a.zone,
           ce.counted_quantity, ce.counted_at
    FROM assignments a
    JOIN sessions s ON a.session_id = s.id
    JOIN items i ON a.item_id = i.id
    LEFT JOIN count_entries ce ON ce.assignment_id = a.id AND ce.counter_id = a.counter_id
    WHERE $where
    ORDER BY
        FIELD(a.status, 'recount', 'in_progress', 'pending', 'counted'),
        a.priority DESC, a.created_at ASC
", $params);

$sessions = $db->fetchAll("
    SELECT DISTINCT s.id, s.name
    FROM sessions s
    JOIN assignments a ON a.session_id = s.id
    WHERE a.counter_id = ? AND s.status IN ('open', 'in_progress')
    ORDER BY s.name
", [$userId]);

include APP_ROOT . '/templates/header.php';
?>

    <style>
        .count-items-filter-row {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            align-items: flex-end;
            padding-bottom: 10px;
        }
        .count-items-filter-row input.form-control,
        .count-items-filter-row select.form-control,
        .count-items-filter-row button {
            width: auto;
            min-width: 0;
            flex: 1 1 auto;
        }
        .count-items-filter-row input.form-control {
            min-width: 180px;
        }
        .count-items-filter-row select.form-control,
        .count-items-filter-row button {
            min-width: 120px;
        }
        @media (max-width: 768px) {
            .count-items-filter-row {
                flex-direction: column;
                align-items: stretch;
            }
            .count-items-filter-row input.form-control,
            .count-items-filter-row select.form-control,
            .count-items-filter-row button {
                width: 100%;
                min-width: 100%;
                flex: none;
            }
        }
        @media (max-width: 480px) {
            .count-items-filter-row {
                padding-bottom: 8px;
                gap: 8px;
            }
            .table-container {
                border: 1px solid var(--border-light);
                border-radius: var(--radius);
                margin: 0 -12px;
                width: calc(100% + 24px);
            }
        }
    </style>

<script>
/* ── PWA Offline Queue: form interception ───────────────────────────
   Each count-form submission is intercepted:
     navigator.onLine === true  → let PHP handle normally
     navigator.onLine === false → enqueueCount / enqueueBulkCounts
                                   then redirect back with a status alert
   Queue draining is handled by offline-queue.js (window.online + SW sync). */
function _enqueueAndRedirect(countRecords) {
    if (!window.offlineQueue || !countRecords.length) return;
    window.offlineQueue.enqueueBulkCounts(countRecords).then(function () {
        try { window.offlineQueue.registerSyncTag('drain-counts'); } catch (_) {}
        var el = document.createElement('div');
        el.className = 'alert alert-warning';
        el.style.cssText = 'position:fixed;bottom:60px;left:50%;transform:translateX(-50%);z-index:9999;min-width:300px;max-width:500px;text-align:center';
        var n = countRecords.length;
        el.innerHTML = '<strong>Offline Mode</strong><br>' + n + ' count(s) saved locally and will sync automatically when back online.';
        document.body.appendChild(el);
        setTimeout(function () { el.style.opacity = '0'; setTimeout(function () { el.remove(); }, 300); }, 4500);
        setTimeout(function () { window.location.href = '<?= APP_URL ?>/counter/count_items.php'; }, 800);
    });
}

document.addEventListener('DOMContentLoaded', function () {
    /* ── Submit-count form (single assignment) ──────────────────── */
    var submitForm = Array.from(document.querySelectorAll('form[method="POST"]')).find(function (f) {
        return f.querySelector('input[name="action"][value="submit_count"]');
    });
    if (submitForm) {
        submitForm.addEventListener('submit', function (e) {
            if (navigator.onLine) return;   // PHP handles online requests
            e.preventDefault();
            var rec = {
                assignment_id:    submitForm.querySelector('[name="assignment_id"]')?.value   || '',
                counted_quantity: submitForm.querySelector('[name="counted_quantity"]')?.value || '',
                count_method:     submitForm.querySelector('[name="count_method"]')?.value    || 'manual',
                notes:            submitForm.querySelector('[name="notes"]')?.value           || '',
            };
            if (!rec.assignment_id) return;
            _enqueueAndRedirect([rec]);
        });
    }

    /* ── Bulk-submit form ───────────────────────────────────────── */
    var bulkForm = document.getElementById('bulkForm');
    if (bulkForm) {
        bulkForm.addEventListener('submit', function (e) {
            if (navigator.onLine) return;
            e.preventDefault();
            var records = [];
            document.querySelectorAll('.bulk-checkbox:checked').forEach(function (cb) {
                var aid  = cb.value;
                var qty  = document.querySelector('input[name="individual_quantity[' + aid + ']"]');
                records.push({
                    assignment_id:    aid,
                    counted_quantity: qty ? qty.value : '0',
                    count_method:     bulkForm.querySelector('[name="count_method"]')?.value || 'manual',
                    notes:            bulkForm.querySelector('[name="notes"]')?.value      || '',
                });
            });
            if (records.length === 0) return;
            _enqueueAndRedirect(records);
        });
    }
});

function filterAssignmentRows() {
    const searchInput = document.getElementById('itemSearch');
    const groupSelect = document.getElementById('itemGroupFilter');
    const query = searchInput ? searchInput.value.trim().toLowerCase() : '';
    const group = groupSelect ? groupSelect.value.trim().toLowerCase() : '';
    const rows = document.querySelectorAll('.table-container tbody tr.assignment-row');
    let visibleCount = 0;

    rows.forEach(row => {
        const rowText = row.textContent.toLowerCase();
        const rowGroup = row.dataset.itemGroup ? row.dataset.itemGroup.toLowerCase() : '';
        const matchesQuery = !query || rowText.includes(query);
        const matchesGroup = !group || rowGroup === group;
        const matches = matchesQuery && matchesGroup;
        row.style.display = matches ? '' : 'none';
        if (matches) {
            visibleCount++;
        }
    });

    const countText = document.getElementById('visibleAssignmentsCount');
    if (countText) {
        countText.textContent = visibleCount;
    }

    const noResultsRow = document.getElementById('searchNoResultsRow');
    if (noResultsRow) {
        noResultsRow.style.display = visibleCount === 0 ? '' : 'none';
    }
}

function preventEnterSubmit(event) {
    if (event.key === 'Enter') {
        event.preventDefault();
    }
}

// Bulk selection JS
function toggleAll(source) {
    document.querySelectorAll('.bulk-checkbox').forEach(cb => {
        cb.checked = source.checked;
    });
    updateBulkUI();
}

function toggleCheckbox(cb) {
    updateBulkUI();
}

function updateBulkUI() {
    const checkedBoxes = document.querySelectorAll('.bulk-checkbox:checked');
    const count = checkedBoxes.length;
    const btn = document.getElementById('bulkSubmitBtn');
    const countSpan = document.getElementById('bulkCount');
    
    if (countSpan) countSpan.textContent = count;
    if (btn) btn.disabled = count === 0;
    
    // Update select all indeterminate
    const selectAll = document.getElementById('selectAll');
    if (selectAll) {
        const allCheckboxes = document.querySelectorAll('.bulk-checkbox');
        selectAll.indeterminate = count > 0 && count < allCheckboxes.length;
    }
}

function validateBulkSubmit() {
    let valid = true;
    const form = document.getElementById('bulkForm');

    // Remove previously injected hidden inputs
    form.querySelectorAll('input.dynamic-bulk-input').forEach(el => el.remove());

    const checkedBoxes = document.querySelectorAll('.bulk-checkbox:checked');
    if (checkedBoxes.length === 0) return false;

    checkedBoxes.forEach(cb => {
        const row = cb.closest('tr');
        const assignmentId = cb.value;
        const qtyInput = row.querySelector('input[name^=individual_quantity]');

        if (qtyInput && (!qtyInput.value || parseFloat(qtyInput.value) < 0)) {
            qtyInput.classList.add('is-invalid');
            valid = false;
            return;
        }

        // Add hidden input for bulk_counts[assignmentId]
        const hiddenCheckbox = document.createElement('input');
        hiddenCheckbox.type = 'hidden';
        hiddenCheckbox.name = 'bulk_counts[' + assignmentId + ']';
        hiddenCheckbox.value = assignmentId;
        hiddenCheckbox.className = 'dynamic-bulk-input';
        form.appendChild(hiddenCheckbox);

        // Add hidden input for individual_quantity[assignmentId]
        const hiddenQty = document.createElement('input');
        hiddenQty.type = 'hidden';
        hiddenQty.name = 'individual_quantity[' + assignmentId + ']';
        hiddenQty.value = qtyInput ? qtyInput.value : '0';
        hiddenQty.className = 'dynamic-bulk-input';
        form.appendChild(hiddenQty);
    });

    return valid;
}

document.addEventListener('DOMContentLoaded', function() {
    updateBulkUI();
    filterAssignmentRows();

    const itemSearch = document.getElementById('itemSearch');
    if (itemSearch) {
        itemSearch.addEventListener('input', filterAssignmentRows);
    }

    const itemGroupFilter = document.getElementById('itemGroupFilter');
    if (itemGroupFilter) {
        itemGroupFilter.addEventListener('change', filterAssignmentRows);
    }

    // Clear validation errors when user types in quantity fields
    document.querySelectorAll('input[name^="individual_quantity"]').forEach(input => {
        input.addEventListener('input', function() {
            this.classList.remove('is-invalid');
        });
    });
});
</script>

<?php if ($activeAssignment): ?>
<!-- COUNT FORM - Active Assignment -->

<?php if ($activeAssignment['status'] === 'recount'): ?>
<div class="alert alert-warning" style="margin-bottom:20px">
    <strong>Recount Required</strong> &mdash; This item was rejected and needs to be recounted. Please verify the quantity carefully.
</div>
<?php endif; ?>

<?php if (in_array($activeAssignment['status'], ['pending', 'recount'])): ?>
<!-- Start Count Form -->
<div class="card">
    <div class="card-body" style="text-align:center;padding:40px">
        <div style="font-size:48px;margin-bottom:16px">&#128203;</div>
    <h3><?= e($activeAssignment['item_code']) ?> &mdash; <?= e($activeAssignment['item_name'] ?? 'N/A') ?></h3>
        <p class="text-muted" style="margin:12px 0 24px">
            Location: <strong><?= format_location($activeAssignment['Stores'], $activeAssignment['Rack'], $activeAssignment['Level'], $activeAssignment['Bin'], $activeAssignment['zone']) ?></strong> |
            System Qty: <strong><?= format_number($activeAssignment['system_quantity'], 0) ?> <?= e($activeAssignment['unit_of_measure']) ?></strong>
        </p>
        <form method="POST">
            <?= Csrf::field() ?>
            <input type="hidden" name="action" value="start_count">
            <input type="hidden" name="assignment_id" value="<?= $activeAssignment['id'] ?>">
            <button type="submit" class="btn btn-primary btn-lg">Start Counting</button>
        </form>
    </div>
</div>
<?php elseif ($activeAssignment['status'] === 'in_progress'): ?>
<!-- Data Entry Form -->
<div class="card">
    <div class="card-header">
        <h3>Physical Count Entry</h3>
        <?= status_badge($activeAssignment['status']) ?>
    </div>
    <div class="card-body">
            <form method="POST">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="submit_count">
                <input type="hidden" name="assignment_id" value="<?= $activeAssignment['id'] ?>">

                <div class="form-group">
                    <label class="form-label">Item</label>
                    <div style="background:var(--bg-secondary);padding:12px;border-radius:6px">
                        <strong><?= e($activeAssignment['item_code']) ?></strong> &mdash; <?= e($activeAssignment['item_name'] ?? 'N/A') ?>
                        <?php if ($activeAssignment['item_description']): ?>
                        <br><small class="text-muted"><?= e($activeAssignment['item_description']) ?></small>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Location</label>
                        <div style="background:var(--bg-secondary);padding:12px;border-radius:6px">
                            <?= format_location($activeAssignment['Stores'], $activeAssignment['Rack'], $activeAssignment['Level'], $activeAssignment['Bin'], $activeAssignment['zone']) ?>
                </div>
                </div>
                </div>

                <div class="form-group">
                        <label class="form-label">Counted Quantity *</label>
                        <input type="number" name="counted_quantity" class="form-control" required min="0" step="0.01"
                               value="<?= e($activeAssignment['existing_count'] ?? '') ?>"
                               placeholder="Enter physical count" autofocus
                               style="font-size:18px;padding:12px">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Count Method</label>
                        <select name="count_method" class="form-control">
                            <option value="manual" <?= ($activeAssignment['existing_method'] ?? 'manual') === 'manual' ? 'selected' : '' ?>>Manual</option>
                            <option value="barcode" <?= ($activeAssignment['existing_method'] ?? '') === 'barcode' ? 'selected' : '' ?>>Barcode</option>
                            <option value="rfid" <?= ($activeAssignment['existing_method'] ?? '') === 'rfid' ? 'selected' : '' ?>>RFID</option>
                        </select>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">Notes</label>
                    <textarea name="notes" class="form-control" rows="3" placeholder="Any observations or discrepancies..."><?= e($activeAssignment['existing_notes'] ?? '') ?></textarea>
                </div>

                <div class="btn-group">
                    <button type="submit" class="btn btn-primary btn-lg">&#10004; Submit Count</button>
                    <a href="<?= APP_URL ?>/counter/count_items.php" class="btn btn-outline">Cancel</a>
                </div>
            </form>
        </div>
    </div>
</div>

<?php elseif ($activeAssignment['status'] === 'counted'): ?>
<!-- Already Counted -->
<div class="card">
    <div class="card-body" style="text-align:center;padding:40px">
        <div style="font-size:48px;margin-bottom:16px">&#9989;</div>
        <h3>Count Already Submitted</h3>
        <p class="text-muted">
            You have already submitted a count of <strong><?= format_number($activeAssignment['existing_count'], 0) ?></strong> <?= e($activeAssignment['unit_of_measure']) ?>
            for this item.
        </p>
        <p>This count is awaiting checker verification.</p>
        <a href="<?= APP_URL ?>/counter/count_items.php" class="btn btn-primary">Back to List</a>
    </div>
</div>
<?php endif; ?>

<?php else: ?>
<!-- ASSIGNMENT LIST -->

    <div class="toolbar" style="display:flex;justify-content:space-between;align-items:center;gap:16px;flex-wrap:wrap">
    <form method="GET" class="count-items-filter-row">
            <input id="itemSearch" type="search" class="form-control" placeholder="Search items..." autocomplete="off" onkeydown="preventEnterSubmit(event)">
            <select id="sessionFilter" name="session_id" class="form-control" onchange="this.form.submit()">
                <option value="">Open Sessions</option>
                <?php foreach ($sessions as $s): ?>
                <option value="<?= $s['id'] ?>" <?= $sessionFilter==$s['id'] ? 'selected' : '' ?>><?= e($s['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="store_filter" class="form-control" onchange="this.form.submit()">
                <option value="">All Stores</option>
                <?php
                // Get unique stores from assignments with same filters as main query
                $storeWhere = "a.counter_id = ? AND a.status IN ('pending', 'in_progress', 'counted', 'recount')";
                $storeParams = [$userId];
                if ($sessionFilter) {
                    $storeWhere .= " AND a.session_id = ?";
                    $storeParams[] = $sessionFilter;
                }
                $stores = $db->fetchAll("SELECT DISTINCT i.Stores FROM items i JOIN assignments a ON a.item_id = i.id WHERE $storeWhere ORDER BY i.Stores", $storeParams);
                foreach ($stores as $store): ?>
                <option value="<?= $store['Stores'] ?>" <?= isset($_GET['store_filter']) && $_GET['store_filter'] == $store['Stores'] ? 'selected' : '' ?>><?= e($store['Stores']) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="rack_filter" class="form-control" onchange="this.form.submit()">
                <option value="">All Racks</option>
                <?php
                // Get unique racks from assignments with same filters as main query
                $rackWhere = "a.counter_id = ? AND a.status IN ('pending', 'in_progress', 'counted', 'recount')";
                $rackParams = [$userId];
                if ($sessionFilter) {
                    $rackWhere .= " AND a.session_id = ?";
                    $rackParams[] = $sessionFilter;
                }
                if ($storeFilter) {
                    $rackWhere .= " AND i.Stores = ?";
                    $rackParams[] = $storeFilter;
                }
                $racks = $db->fetchAll("SELECT DISTINCT i.Rack FROM items i JOIN assignments a ON a.item_id = i.id WHERE $rackWhere ORDER BY i.Rack", $rackParams);
                foreach ($racks as $rack): ?>
                <option value="<?= $rack['Rack'] ?>" <?= isset($_GET['rack_filter']) && $_GET['rack_filter'] == $rack['Rack'] ? 'selected' : '' ?>><?= e($rack['Rack']) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="level_filter" class="form-control" onchange="this.form.submit()">
                <option value="">All Levels</option>
                <?php
                // Get unique levels from assignments with same filters as main query
                $levelWhere = "a.counter_id = ? AND a.status IN ('pending', 'in_progress', 'counted', 'recount')";
                $levelParams = [$userId];
                if ($sessionFilter) {
                    $levelWhere .= " AND a.session_id = ?";
                    $levelParams[] = $sessionFilter;
                }
                if ($storeFilter) {
                    $levelWhere .= " AND i.Stores = ?";
                    $levelParams[] = $storeFilter;
                }
                if ($rackFilter) {
                    $levelWhere .= " AND i.Rack = ?";
                    $levelParams[] = $rackFilter;
                }
                $levels = $db->fetchAll("SELECT DISTINCT i.Level FROM items i JOIN assignments a ON a.item_id = i.id WHERE $levelWhere ORDER BY i.Level", $levelParams);
                foreach ($levels as $level): ?>
                <option value="<?= $level['Level'] ?>" <?= isset($_GET['level_filter']) && $_GET['level_filter'] == $level['Level'] ? 'selected' : '' ?>><?= e($level['Level']) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="bin_filter" class="form-control" onchange="this.form.submit()">
                <option value="">All Bins</option>
                <?php
                // Get unique bins from assignments with same filters as main query
                $binWhere = "a.counter_id = ? AND a.status IN ('pending', 'in_progress', 'counted', 'recount')";
                $binParams = [$userId];
                if ($sessionFilter) {
                    $binWhere .= " AND a.session_id = ?";
                    $binParams[] = $sessionFilter;
                }
                if ($storeFilter) {
                    $binWhere .= " AND i.Stores = ?";
                    $binParams[] = $storeFilter;
                }
                if ($rackFilter) {
                    $binWhere .= " AND i.Rack = ?";
                    $binParams[] = $rackFilter;
                }
                if ($levelFilter) {
                    $binWhere .= " AND i.Level = ?";
                    $binParams[] = $levelFilter;
                }
                $bins = $db->fetchAll("SELECT DISTINCT i.Bin FROM items i JOIN assignments a ON a.item_id = i.id WHERE $binWhere ORDER BY i.Bin", $binParams);
                foreach ($bins as $bin): ?>
                <option value="<?= $bin['Bin'] ?>" <?= isset($_GET['bin_filter']) && $_GET['bin_filter'] == $bin['Bin'] ? 'selected' : '' ?>><?= e($bin['Bin']) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="item_group" id="itemGroupFilter" class="form-control" onchange="this.form.submit()">
                <option value="">All Item Groups</option>
                <?php
                $groupWhere = "a.counter_id = ? AND a.status IN ('pending', 'in_progress', 'counted', 'recount')";
                $groupParams = [$userId];
                if ($sessionFilter) {
                    $groupWhere .= " AND a.session_id = ?";
                    $groupParams[] = $sessionFilter;
                }
                if ($storeFilter) {
                    $groupWhere .= " AND i.Stores = ?";
                    $groupParams[] = $storeFilter;
                }
                if ($rackFilter) {
                    $groupWhere .= " AND i.Rack = ?";
                    $groupParams[] = $rackFilter;
                }
                if ($levelFilter) {
                    $groupWhere .= " AND i.Level = ?";
                    $groupParams[] = $levelFilter;
                }
                if ($binFilter) {
                    $groupWhere .= " AND i.Bin = ?";
                    $groupParams[] = $binFilter;
                }
                $groups = $db->fetchAll("SELECT DISTINCT i.Item_Group FROM items i JOIN assignments a ON a.item_id = i.id WHERE $groupWhere ORDER BY i.Item_Group", $groupParams);
                foreach ($groups as $group): ?>
                <option value="<?= e($group['Item_Group']) ?>" <?= $itemGroupFilter === $group['Item_Group'] ? 'selected' : '' ?>><?= e($group['Item_Group']) ?></option>
                <?php endforeach; ?>
            </select>
            <button type="submit" class="btn btn-outline-sm">Filter</button>
        </form>
        <?php if (!empty($assignments)): ?>
        <div class="text-muted small" style="white-space:nowrap">
            Showing <span id="visibleAssignmentsCount"><?= count($assignments) ?></span> matching items
        </div>
        <?php endif; ?>
    </div>

<div class="card">
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th style="width:40px"><input type="checkbox" id="selectAll" onclick="toggleAll(this)"></th>
                    <th>Qty</th>
                    <th>Item</th>
                    <th>Location</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>

            </thead>
            <tbody>
                <?php if (empty($assignments)): ?>
                <tr><td colspan="6" class="text-center text-muted" style="padding:40px">No assignments available for counting.</td></tr>
                <?php else: foreach ($assignments as $a): ?>
                <tr class="assignment-row" data-item-group="<?= e(strtolower($a['category'] ?? '')) ?>">
                    <td>
                        <?php if (in_array($a['status'], ['pending', 'in_progress', 'recount'])): ?>
                        <input type="checkbox" name="bulk_counts[<?= $a['id'] ?>]" value="<?= $a['id'] ?>" class="bulk-checkbox" onchange="toggleCheckbox(this)">
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (in_array($a['status'], ['pending', 'in_progress', 'recount'])): ?>
                        <input type="number" name="individual_quantity[<?= $a['id'] ?>]" min="0" step="0.01" placeholder="Qty" style="width:80px" class="form-control form-control-sm">
                        <?php endif; ?>
                    </td>
                    <td>
                        <strong><?= e($a['item_code']) ?></strong><br>
                        <small class="text-muted"><?= e($a['item_name'] ?? 'N/A') ?></small>
                    </td>
                    <td><?= format_location($a['Stores'], $a['Rack'], $a['Level'], $a['Bin'], $a['zone']) ?></td>
                    <td><?= status_badge($a['status']) ?></td>
                    <td>

                        <?php if (in_array($a['status'], ['pending', 'in_progress', 'recount'])): ?>
                        <a href="<?= APP_URL ?>/counter/count_items.php?assignment_id=<?= $a['id'] ?>" class="btn btn-sm btn-primary">Count</a>
                        <?php else: ?>
                        <span class="text-muted" style="font-size:12px">Submitted</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <tr id="searchNoResultsRow" style="display:none"><td colspan="6" class="text-center text-muted" style="padding:40px">No items match your search.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if (!empty($assignments)): ?>
    <div class="card-footer" style="background:var(--bg-secondary);border-top:1px solid var(--border-color);padding:16px">
        <form method="POST" id="bulkForm" onsubmit="return validateBulkSubmit()">
            <?= Csrf::field() ?>
            <input type="hidden" name="action" value="bulk_submit_counts">
            <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center">
                <div>
                    <label style="margin-right:8px;font-weight:500">Method:</label>
                    <select name="count_method" class="form-control" style="width:140px">
                        <option value="manual">Manual Count</option>
                        <option value="barcode">Barcode Scan</option>
                        <option value="rfid">RFID</option>
                    </select>
                </div>
                <div style="flex:1;min-width:200px">
                    <textarea name="notes" class="form-control" rows="1" placeholder="Notes (applied to all selected items)..." style="resize:vertical"></textarea>
                </div>
                <button type="submit" class="btn btn-success" id="bulkSubmitBtn" disabled style="white-space:nowrap">
                    <span id="bulkCount">0</span> Items → Submit Bulk
                </button>
            </div>
        </form>
    </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php include APP_ROOT . '/templates/footer.php'; ?>
