<?php
/**
 * Admin - Assignment Management
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
admin_only();

$pageTitle = 'Assignment Management';
$db = Database::getInstance();

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

    if ($action === 'create') {
        $sessionId = (int) ($_POST['session_id'] ?? 0);
        $counterId = (int) ($_POST['counter_id'] ?? 0);
        $checkerId = (int) ($_POST['checker_id'] ?? 0);
        $itemId = (int) ($_POST['item_id'] ?? 0);
        $zone = trim($_POST['zone'] ?? '');
        $priority = $_POST['priority'] ?? 'normal';

        if (!$sessionId || !$counterId || !$itemId) {
            set_error('Session, Counter, and Item are required.');
        } else {
            $db->insert('assignments', [
                'session_id' => $sessionId,
                'counter_id' => $counterId,
                'checker_id' => $checkerId ?: null,
                'item_id' => $itemId,
                'zone' => $zone,
                'priority' => $priority,
                'assigned_by' => SessionManager::getUserId(),
                'status' => 'pending',
            ]);
            log_action(SessionManager::getUserId(), 'create', 'assignments', $db->fetchColumn("SELECT LAST_INSERT_ID()"));
            set_success('Assignment created.');
        }
    } elseif ($action === 'bulk_create') {
        $sessionId = (int) ($_POST['session_id'] ?? 0);
        $counterId = (int) ($_POST['counter_id'] ?? 0);
        $checkerId = (int) ($_POST['checker_id'] ?? 0);
        $itemIds = $_POST['item_ids'] ?? [];

        if (!$sessionId || !$counterId || empty($itemIds)) {
            set_error('Please select session, counter, and at least one item.');
        } else {
            $created = 0;
            foreach ($itemIds as $itemId) {
                $db->insert('assignments', [
                    'session_id' => $sessionId,
                    'counter_id' => $counterId,
                    'checker_id' => $checkerId ?: null,
                    'item_id' => (int) $itemId,
                    'assigned_by' => SessionManager::getUserId(),
                    'status' => 'pending',
                ]);
                $created++;
            }
            log_action(SessionManager::getUserId(), 'bulk_create', 'assignments', 0, ['count' => $created]);
            set_success("$created assignments created.");
        }
    } elseif ($action === 'location_assign') {
        $sessionId = (int) ($_POST['session_id'] ?? 0);
        $counterId = (int) ($_POST['counter_id'] ?? 0);
        $checkerId = (int) ($_POST['checker_id'] ?? 0);
        $priority = $_POST['priority'] ?? 'normal';
        $store = trim($_POST['store'] ?? '');
        $rack = trim($_POST['rack'] ?? '');
        $level = trim($_POST['level'] ?? '');
        $bin = trim($_POST['bin'] ?? '');

        if (!$sessionId || !$counterId || !$store) {
            set_error('Session, Counter, and Store are required.');
        } else {
            $conditions = ["`Status` = 'Active'", "`Stores` = ?"];
            $params = [$store];
            if ($rack) { $conditions[] = "`Rack` = ?"; $params[] = $rack; }
            if ($level) { $conditions[] = "`Level` = ?"; $params[] = $level; }
            if ($bin) { $conditions[] = "`Bin` = ?"; $params[] = $bin; }

            $locationWhere = implode(' AND ', $conditions);
            $items = $db->fetchAll("SELECT id FROM items WHERE $locationWhere", $params);

            if (empty($items)) {
                set_error('No items found for the selected location.');
            } else {
                $locationLabel = $store;
                if ($rack) $locationLabel .= ' / ' . $rack;
                if ($level) $locationLabel .= ' / ' . $level;
                if ($bin) $locationLabel .= ' / ' . $bin;

                $db->beginTransaction();
                $created = 0;
                foreach ($items as $item) {
                    $db->insert('assignments', [
                        'session_id' => $sessionId,
                        'counter_id' => $counterId,
                        'checker_id' => $checkerId ?: null,
                        'item_id' => (int) $item['id'],
                        'zone' => $locationLabel,
                        'priority' => $priority,
                        'assigned_by' => SessionManager::getUserId(),
                        'status' => 'pending',
                    ]);
                    $created++;
                }
                $db->commit();
                log_action(SessionManager::getUserId(), 'location_assign', 'assignments', 0, [
                    'count' => $created,
                    'store' => $store,
                    'rack' => $rack,
                    'level' => $level,
                    'bin' => $bin,
                ]);
                set_success("$created assignments created for location: $locationLabel.");
            }
        }
    } elseif ($action === 'delete') {
        $id = (int) ($_POST['assignment_id'] ?? 0);
        $db->delete('assignments', 'id = ?', [$id]);
        set_success('Assignment deleted.');
    }

    redirect(APP_URL . '/admin/assignments.php');
}

// Filters
$sessionFilter = $_GET['session_id'] ?? '';
$statusFilter = $_GET['status'] ?? '';
$counterFilter = $_GET['counter_id'] ?? '';
$page = max(1, (int) ($_GET['page'] ?? 1));

$where = '1=1';
$params = [];
if ($sessionFilter) { $where .= ' AND a.session_id = ?'; $params[] = $sessionFilter; }
if ($statusFilter) { $where .= ' AND a.status = ?'; $params[] = $statusFilter; }
if ($counterFilter) { $where .= ' AND a.counter_id = ?'; $params[] = $counterFilter; }

$total = $db->fetchColumn("SELECT COUNT(*) FROM assignments a WHERE $where", $params);
$pagination = new Pagination($total, ITEMS_PER_PAGE, $page);

$assignments = $db->fetchAll("
    SELECT a.*, s.name as session_name, i.Item_Code as item_code, i.Item_Description AS name,
           i.Stores as store, i.Rack as rack, i.Level as level, i.Bin as bin,
           uc.full_name as counter_name, uk.full_name as checker_name
    FROM assignments a
    JOIN sessions s ON a.session_id = s.id
    JOIN items i ON a.item_id = i.id
    JOIN users uc ON a.counter_id = uc.id
    LEFT JOIN users uk ON a.checker_id = uk.id
    WHERE $where
    ORDER BY a.created_at DESC
    LIMIT {$pagination->getLimit()} OFFSET {$pagination->getOffset()}
", $params);

// Modal data
$sessions = $db->fetchAll("SELECT id, name FROM sessions WHERE status IN ('draft','open','in_progress','completed') ORDER BY name");
$counters = $db->fetchAll("SELECT id, full_name FROM users WHERE role = 'counter' AND status = 'active' ORDER BY full_name");
$checkers = $db->fetchAll("SELECT id, full_name FROM users WHERE role = 'checker' AND status = 'active' ORDER BY full_name");
$itemGroups = $db->fetchAll("SELECT DISTINCT Item_Group FROM items WHERE Item_Group IS NOT NULL AND Item_Group != '' AND Status = 'Active' ORDER BY Item_Group");
$availableItems = $db->fetchAll("SELECT id, Item_Code as item_code, Item_Description AS name, Stores as store, Rack as rack, Level as level, Bin as bin, Item_Group as item_group FROM items WHERE Status = 'Active' ORDER BY Item_Code");

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

<!-- Single Assignment Modal -->
<div class="modal-overlay" id="assignModal">
    <div class="modal">
        <div class="modal-header">
            <h3>Create Assignment</h3>
            <button class="modal-close" onclick="document.getElementById('assignModal').style.display='none'">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="create">
                <div class="form-group">
                    <label class="form-label">Session *</label>
                    <select name="session_id" class="form-control" required>
                        <option value="">Select Session</option>
                        <?php foreach ($sessions as $s): ?>
                        <option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Counter *</label>
                        <select name="counter_id" class="form-control" required>
                            <option value="">Select Counter</option>
                            <?php foreach ($counters as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= e($c['full_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Checker</label>
                        <select name="checker_id" class="form-control">
                            <option value="">No Checker</option>
                            <?php foreach ($checkers as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= e($c['full_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Item *</label>
                    <select name="item_id" class="form-control" required>
                        <option value="">Select Item</option>
                        <?php foreach ($availableItems as $item): ?>
                        <option value="<?= $item['id'] ?>"><?= e($item['item_code']) ?> - <?= e($item['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Zone</label>
                        <input type="text" name="zone" class="form-control" placeholder="e.g., Zone A">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Priority</label>
                        <select name="priority" class="form-control">
                            <option value="normal">Normal</option>
                            <option value="high">High</option>
                            <option value="urgent">Urgent</option>
                            <option value="low">Low</option>
                        </select>
                    </div>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-primary">Create</button>
                    <button type="button" class="btn btn-outline" onclick="document.getElementById('assignModal').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk Assignment Modal -->
<div class="modal-overlay" id="bulkModal">
    <div class="modal" style="max-width:700px">
        <div class="modal-header">
            <h3>Bulk Assignment</h3>
            <button class="modal-close" onclick="document.getElementById('bulkModal').style.display='none'">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="bulk_create">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Session *</label>
                        <select name="session_id" class="form-control" required>
                            <option value="">Select Session</option>
                            <?php foreach ($sessions as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Counter *</label>
                        <select name="counter_id" class="form-control" required>
                            <option value="">Select Counter</option>
                            <?php foreach ($counters as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= e($c['full_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Checker</label>
                    <select name="checker_id" class="form-control">
                        <option value="">No Checker</option>
                        <?php foreach ($checkers as $c): ?>
                        <option value="<?= $c['id'] ?>"><?= e($c['full_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Assignment Source</label>
                        <select id="bulkSource" class="form-control" onchange="onBulkSourceChange()">
                            <option value="manual">Manual Selection</option>
                            <option value="group">By Item Group</option>
                            <option value="location">By Location</option>
                        </select>
                    </div>
                </div>
                <div class="form-row" id="bulkGroupRow" style="display:none">
                    <div class="form-group">
                        <label class="form-label">Item Group</label>
                        <select id="bulkItemGroup" class="form-control" onchange="updateBulkGroupCount(); updateBulkSelectionStatus();">
                            <option value="">Select Item Group</option>
                            <?php foreach ($itemGroups as $g): ?>
                            <option value="<?= e($g['Item_Group']) ?>"><?= e($g['Item_Group']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div id="bulkLocationRow" style="display:none">
                    <hr style="margin:15px 0;border-color:var(--border)">
                    <p class="text-muted" style="margin-bottom:12px"><strong>Select Location</strong> &mdash; Choose Store first, then optionally narrow by Rack, Level, and Bin.</p>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Store</label>
                            <select id="bulk_loc_store" class="form-control" onchange="bulkOnLocationChange()">
                                <option value="">Select Store</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Rack</label>
                            <select id="bulk_loc_rack" class="form-control" onchange="bulkOnLocationChange()" disabled>
                                <option value="">All Racks</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Level</label>
                            <select id="bulk_loc_level" class="form-control" onchange="bulkOnLocationChange()" disabled>
                                <option value="">All Levels</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label class="form-label">Bin</label>
                            <select id="bulk_loc_bin" class="form-control" onchange="bulkOnLocationChange()" disabled>
                                <option value="">All Bins</option>
                            </select>
                        </div>
                    </div>
                    <div class="alert alert-info" id="bulkLocationCount" style="display:none;margin-top:10px">
                        <strong id="bulkMatchedCount">0</strong> items match this location.
                    </div>
                </div>
                <div class="form-group" style="display:flex;align-items:center;gap:10px">
                    <button type="button" class="btn btn-outline" onclick="applyBulkSelection()">Load Matching Items</button>
                    <span class="text-muted small" id="bulkSelectionStatus">Use Item Group or Location to auto-select matching items.</span>
                </div>
                <div class="form-group">
                    <label class="form-label">Select Items *</label>
                    <div style="max-height:300px;overflow-y:auto;border:1px solid var(--border);border-radius:var(--radius-sm);padding:10px">
                        <?php foreach ($availableItems as $item): ?>
                        <label class="bulk-item-row" data-item-group="<?= e($item['item_group']) ?>" data-store="<?= e($item['store']) ?>" data-rack="<?= e($item['rack']) ?>" data-level="<?= e($item['level']) ?>" data-bin="<?= e($item['bin']) ?>" style="display:flex;align-items:center;gap:8px;padding:4px 0;cursor:pointer">
                            <input type="checkbox" name="item_ids[]" value="<?= $item['id'] ?>" class="bulk-item-checkbox">
                            <strong><?= e($item['item_code']) ?></strong> - <?= e($item['name']) ?>
                            <?php if ($item['store'] || $item['rack'] || $item['level'] || $item['bin']): ?><span class="text-muted">(<?= e(implode(' / ', array_filter([$item['store'], $item['rack'] ? 'R:' . $item['rack'] : '', $item['level'] ? 'L:' . $item['level'] : '', $item['bin'] ? 'B:' . $item['bin'] : '']))) ?>)</span><?php endif; ?>
                        </label>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-success">Create Assignments</button>
                    <button type="button" class="btn btn-outline" onclick="document.getElementById('bulkModal').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Assign by Location Modal -->
<div class="modal-overlay" id="locationModal">
    <div class="modal" style="max-width:600px">
        <div class="modal-header">
            <h3>Assign by Location</h3>
            <button class="modal-close" onclick="document.getElementById('locationModal').style.display='none'">&times;</button>
        </div>
        <div class="modal-body">
            <form method="POST" id="locationForm">
                <?= Csrf::field() ?>
                <input type="hidden" name="action" value="location_assign">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Session *</label>
                        <select name="session_id" class="form-control" required>
                            <option value="">Select Session</option>
                            <?php foreach ($sessions as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= e($s['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Counter *</label>
                        <select name="counter_id" class="form-control" required>
                            <option value="">Select Counter</option>
                            <?php foreach ($counters as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= e($c['full_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Checker</label>
                        <select name="checker_id" class="form-control">
                            <option value="">No Checker</option>
                            <?php foreach ($checkers as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= e($c['full_name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Priority</label>
                        <select name="priority" class="form-control">
                            <option value="normal">Normal</option>
                            <option value="high">High</option>
                            <option value="urgent">Urgent</option>
                            <option value="low">Low</option>
                        </select>
                    </div>
                </div>
                <hr style="margin:15px 0;border-color:var(--border)">
                <p class="text-muted" style="margin-bottom:12px"><strong>Select Location</strong> &mdash; Choose Store first, then optionally narrow by Rack, Level, and Bin.</p>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Store *</label>
                        <select name="store" id="loc_store" class="form-control" required onchange="onLocationChange()">
                            <option value="">Select Store</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Rack</label>
                        <select name="rack" id="loc_rack" class="form-control" onchange="onLocationChange()" disabled>
                            <option value="">All Racks</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Level</label>
                        <select name="level" id="loc_level" class="form-control" onchange="onLocationChange()" disabled>
                            <option value="">All Levels</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Bin</label>
                        <select name="bin" id="loc_bin" class="form-control" onchange="onLocationChange()" disabled>
                            <option value="">All Bins</option>
                        </select>
                    </div>
                </div>
                <div id="locationItemCount" class="alert alert-info" style="display:none;margin-top:10px">
                    <strong id="itemCountValue">0</strong> items will be assigned from the selected location.
                </div>
                <div class="btn-group">
                    <button type="submit" class="btn btn-info" id="locationSubmitBtn" disabled>Assign Items</button>
                    <button type="button" class="btn btn-outline" onclick="document.getElementById('locationModal').style.display='none'">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="toolbar">
    <div class="toolbar-left" style="display:flex;gap:10px;flex-wrap:wrap">
        <button class="btn btn-primary" onclick="document.getElementById('assignModal').style.display='flex'">+ Single Assign</button>
        <button class="btn btn-success" onclick="openBulkModal()">+ Bulk Assign</button>
        <button class="btn btn-info" onclick="openLocationModal()">+ Assign by Location</button>
    </div>
    <form method="GET" class="toolbar-right" style="display:flex;gap:10px;flex-wrap:wrap">
        <select name="session_id" class="form-control" style="width:auto">
            <option value="">All Sessions</option>
            <?php foreach ($sessions as $s): ?>
            <option value="<?= $s['id'] ?>" <?= $sessionFilter==$s['id']?'selected':'' ?>><?= e($s['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <select name="status" class="form-control" style="width:auto">
            <option value="">All Status</option>
            <?php foreach (['pending','in_progress','counted','approved','rejected','recount'] as $s): ?>
            <option value="<?= $s ?>" <?= $statusFilter===$s?'selected':'' ?>><?= ucwords(str_replace('_',' ',$s)) ?></option>
            <?php endforeach; ?>
        </select>
        <button type="submit" class="btn btn-outline">Filter</button>
    </form>
</div>

<div class="card">
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Session</th>
                    <th>Item</th>
                    <th>Location</th>
                    <th>Counter</th>
                    <th>Checker</th>
                    <th>Priority</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($assignments)): ?>
                <tr><td colspan="8" class="text-center text-muted" style="padding:40px">No assignments found.</td></tr>
                <?php else: foreach ($assignments as $a):
                    $locParts = [];
                    if ($a['store']) $locParts[] = $a['store'];
                    if ($a['rack']) $locParts[] = 'R:' . $a['rack'];
                    if ($a['level']) $locParts[] = 'L:' . $a['level'];
                    if ($a['bin']) $locParts[] = 'B:' . $a['bin'];
                    $location = $locParts ? implode(' / ', $locParts) : ($a['zone'] ?: '-');
                ?>
                <tr>
                    <td><?= e($a['session_name']) ?></td>
                    <td><strong><?= e($a['item_code']) ?></strong><br><small class="text-muted"><?= e($a['name']) ?></small></td>
                    <td><?= e($location) ?></td>
                    <td><?= e($a['counter_name']) ?></td>
                    <td><?= e($a['checker_name'] ?: '-') ?></td>
                    <td><?= priority_badge($a['priority']) ?></td>
                    <td><?= status_badge($a['status']) ?></td>
                    <td>
                        <form method="POST" style="display:inline" onsubmit="return confirm('Delete this assignment?')">
                            <?= Csrf::field() ?>
                            <input type="hidden" name="assignment_id" value="<?= $a['id'] ?>">
                            <input type="hidden" name="action" value="delete">
                            <button type="submit" class="btn btn-sm btn-danger">&#128465;</button>
                        </form>
                    </td>
                </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
    <?php if ($pagination->getTotalPages() > 1): ?>
    <div class="card-footer"><?= $pagination->render(get_current_url()) ?></div>
    <?php endif; ?>
</div>

<script>
var apiBase = '<?= APP_URL ?>/admin/api_locations.php';

function openLocationModal() {
    document.getElementById('loc_rack').innerHTML = '<option value="">All Racks</option>';
    document.getElementById('loc_rack').disabled = true;
    document.getElementById('loc_level').innerHTML = '<option value="">All Levels</option>';
    document.getElementById('loc_level').disabled = true;
    document.getElementById('loc_bin').innerHTML = '<option value="">All Bins</option>';
    document.getElementById('loc_bin').disabled = true;
    document.getElementById('locationItemCount').style.display = 'none';
    document.getElementById('locationSubmitBtn').disabled = true;
    document.getElementById('loc_store').innerHTML = '<option value="">Loading...</option>';
    document.getElementById('locationModal').style.display = 'flex';
    loadStores();
}

function loadStores() {
    var sel = document.getElementById('loc_store');
    fetch(apiBase + '?action=stores')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">Select Store</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '">' + escHtml(data[i]) + '</option>'; }
            sel.innerHTML = html;
        })
        .catch(function() { sel.innerHTML = '<option value="">Error loading stores</option>'; });
}

function onLocationChange() {
    var store = document.getElementById('loc_store').value;
    var rack = document.getElementById('loc_rack').value;
    var level = document.getElementById('loc_level').value;

    if (!store) {
        document.getElementById('loc_rack').innerHTML = '<option value="">All Racks</option>';
        document.getElementById('loc_rack').disabled = true;
        document.getElementById('loc_level').innerHTML = '<option value="">All Levels</option>';
        document.getElementById('loc_level').disabled = true;
        document.getElementById('loc_bin').innerHTML = '<option value="">All Bins</option>';
        document.getElementById('loc_bin').disabled = true;
        updateItemCount();
        return;
    }

    // Load racks
    var rackSel = document.getElementById('loc_rack');
    rackSel.innerHTML = '<option value="">Loading...</option>';
    fetch(apiBase + '?action=racks&store=' + encodeURIComponent(store))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">All Racks</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '"' + (rack === data[i] ? ' selected' : '') + '>' + escHtml(data[i]) + '</option>'; }
            rackSel.innerHTML = html;
            rackSel.disabled = false;
        })
        .catch(function() { rackSel.innerHTML = '<option value="">All Racks</option>'; rackSel.disabled = false; });

    if (!rack) {
        document.getElementById('loc_level').innerHTML = '<option value="">All Levels</option>';
        document.getElementById('loc_level').disabled = true;
        document.getElementById('loc_bin').innerHTML = '<option value="">All Bins</option>';
        document.getElementById('loc_bin').disabled = true;
        updateItemCount();
        return;
    }

    // Load levels
    var levelSel = document.getElementById('loc_level');
    levelSel.innerHTML = '<option value="">Loading...</option>';
    fetch(apiBase + '?action=levels&store=' + encodeURIComponent(store) + '&rack=' + encodeURIComponent(rack))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">All Levels</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '"' + (level === data[i] ? ' selected' : '') + '>' + escHtml(data[i]) + '</option>'; }
            levelSel.innerHTML = html;
            levelSel.disabled = false;
        })
        .catch(function() { levelSel.innerHTML = '<option value="">All Levels</option>'; levelSel.disabled = false; });

    if (!level) {
        document.getElementById('loc_bin').innerHTML = '<option value="">All Bins</option>';
        document.getElementById('loc_bin').disabled = true;
        updateItemCount();
        return;
    }

    // Load bins
    var binSel = document.getElementById('loc_bin');
    binSel.innerHTML = '<option value="">Loading...</option>';
    fetch(apiBase + '?action=bins&store=' + encodeURIComponent(store) + '&rack=' + encodeURIComponent(rack) + '&level=' + encodeURIComponent(level))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">All Bins</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '">' + escHtml(data[i]) + '</option>'; }
            binSel.innerHTML = html;
            binSel.disabled = false;
        })
        .catch(function() { binSel.innerHTML = '<option value="">All Bins</option>'; binSel.disabled = false; });

    updateItemCount();
}

function updateItemCount() {
    var store = document.getElementById('loc_store').value;
    var rack = document.getElementById('loc_rack').value;
    var level = document.getElementById('loc_level').value;
    var bin = document.getElementById('loc_bin').value;
    var box = document.getElementById('locationItemCount');
    var btn = document.getElementById('locationSubmitBtn');

    if (!store) {
        box.style.display = 'none';
        btn.disabled = true;
        return;
    }

    var url = apiBase + '?action=count&store=' + encodeURIComponent(store);
    if (rack) url += '&rack=' + encodeURIComponent(rack);
    if (level) url += '&level=' + encodeURIComponent(level);
    if (bin) url += '&bin=' + encodeURIComponent(bin);

    fetch(url)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            document.getElementById('itemCountValue').textContent = data.count;
            box.style.display = 'block';
            btn.disabled = (data.count === 0);
        })
        .catch(function(err) {
            console.error('Failed to fetch item count:', err);
            box.style.display = 'block';
            document.getElementById('itemCountValue').textContent = '?';
            btn.disabled = false;
        });
}

function openBulkModal() {
    document.getElementById('bulkModal').style.display = 'flex';
    if (!document.getElementById('bulkSource').value) {
        document.getElementById('bulkSource').value = 'manual';
    }
    onBulkSourceChange();
    if (!document.getElementById('bulk_loc_store').options.length || document.getElementById('bulk_loc_store').options.length === 1) {
        loadBulkStores();
    }
    updateBulkSelectionStatus();
    updateBulkGroupCount();
}

function onBulkSourceChange() {
    var source = document.getElementById('bulkSource').value;
    document.getElementById('bulkGroupRow').style.display = source === 'group' ? '' : 'none';
    document.getElementById('bulkLocationRow').style.display = source === 'location' ? '' : 'none';
    if (source === 'group') {
        updateBulkGroupCount();
    } else if (source === 'location') {
        bulkOnLocationChange();
    } else {
        filterBulkItems();
    }
    updateBulkSelectionStatus();
}

function updateBulkSelectionStatus() {
    var source = document.getElementById('bulkSource').value;
    var status = document.getElementById('bulkSelectionStatus');
    if (source === 'manual') {
        status.textContent = 'Select items manually using the checkboxes below.';
    } else if (source === 'group') {
        status.textContent = 'Choose an item group and click Load Matching Items to select matching items.';
    } else if (source === 'location') {
        status.textContent = 'Choose a location and click Load Matching Items to select matching items.';
    }
}

function loadBulkStores() {
    var sel = document.getElementById('bulk_loc_store');
    fetch(apiBase + '?action=stores')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">Select Store</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '">' + escHtml(data[i]) + '</option>'; }
            sel.innerHTML = html;
        })
        .catch(function() { sel.innerHTML = '<option value="">Error loading stores</option>'; });
}

function bulkOnLocationChange() {
    var store = document.getElementById('bulk_loc_store').value;
    var rack = document.getElementById('bulk_loc_rack').value;
    var level = document.getElementById('bulk_loc_level').value;
    var bin = document.getElementById('bulk_loc_bin').value;

    if (!store) {
        document.getElementById('bulk_loc_rack').innerHTML = '<option value="">All Racks</option>';
        document.getElementById('bulk_loc_rack').disabled = true;
        document.getElementById('bulk_loc_level').innerHTML = '<option value="">All Levels</option>';
        document.getElementById('bulk_loc_level').disabled = true;
        document.getElementById('bulk_loc_bin').innerHTML = '<option value="">All Bins</option>';
        document.getElementById('bulk_loc_bin').disabled = true;
        updateBulkLocationCount();
        return;
    }

    var rackSel = document.getElementById('bulk_loc_rack');
    rackSel.innerHTML = '<option value="">Loading...</option>';
    fetch(apiBase + '?action=racks&store=' + encodeURIComponent(store))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">All Racks</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '"' + (rack === data[i] ? ' selected' : '') + '>' + escHtml(data[i]) + '</option>'; }
            rackSel.innerHTML = html;
            rackSel.disabled = false;
        })
        .catch(function() { rackSel.innerHTML = '<option value="">All Racks</option>'; rackSel.disabled = false; });

    if (!rack) {
        document.getElementById('bulk_loc_level').innerHTML = '<option value="">All Levels</option>';
        document.getElementById('bulk_loc_level').disabled = true;
        document.getElementById('bulk_loc_bin').innerHTML = '<option value="">All Bins</option>';
        document.getElementById('bulk_loc_bin').disabled = true;
        updateBulkLocationCount();
        return;
    }

    var levelSel = document.getElementById('bulk_loc_level');
    levelSel.innerHTML = '<option value="">Loading...</option>';
    fetch(apiBase + '?action=levels&store=' + encodeURIComponent(store) + '&rack=' + encodeURIComponent(rack))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">All Levels</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '"' + (level === data[i] ? ' selected' : '') + '>' + escHtml(data[i]) + '</option>'; }
            levelSel.innerHTML = html;
            levelSel.disabled = false;
        })
        .catch(function() { levelSel.innerHTML = '<option value="">All Levels</option>'; levelSel.disabled = false; });

    if (!level) {
        document.getElementById('bulk_loc_bin').innerHTML = '<option value="">All Bins</option>';
        document.getElementById('bulk_loc_bin').disabled = true;
        updateBulkLocationCount();
        return;
    }

    var binSel = document.getElementById('bulk_loc_bin');
    binSel.innerHTML = '<option value="">Loading...</option>';
    fetch(apiBase + '?action=bins&store=' + encodeURIComponent(store) + '&rack=' + encodeURIComponent(rack) + '&level=' + encodeURIComponent(level))
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var html = '<option value="">All Bins</option>';
            for (var i = 0; i < data.length; i++) { html += '<option value="' + escHtml(data[i]) + '">' + escHtml(data[i]) + '</option>'; }
            binSel.innerHTML = html;
            binSel.disabled = false;
        })
        .catch(function() { binSel.innerHTML = '<option value="">All Bins</option>'; binSel.disabled = false; });

    updateBulkLocationCount();
    if (document.getElementById('bulkSource').value === 'location') {
        filterBulkItems();
    }
}

function updateBulkLocationCount() {
    var store = document.getElementById('bulk_loc_store').value;
    if (!store) {
        document.getElementById('bulkLocationCount').style.display = 'none';
        return;
    }
    var url = apiBase + '?action=count&store=' + encodeURIComponent(store);
    var rack = document.getElementById('bulk_loc_rack').value;
    var level = document.getElementById('bulk_loc_level').value;
    var bin = document.getElementById('bulk_loc_bin').value;
    if (rack) url += '&rack=' + encodeURIComponent(rack);
    if (level) url += '&level=' + encodeURIComponent(level);
    if (bin) url += '&bin=' + encodeURIComponent(bin);
    fetch(url)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            document.getElementById('bulkMatchedCount').textContent = data.count;
            document.getElementById('bulkLocationCount').style.display = 'block';
        })
        .catch(function() {
            document.getElementById('bulkMatchedCount').textContent = '0';
            document.getElementById('bulkLocationCount').style.display = 'block';
        });
}

function applyBulkSelection() {
    var source = document.getElementById('bulkSource').value;
    var total = 0;
    var labels = document.querySelectorAll('#bulkModal .bulk-item-row');
    var group = document.getElementById('bulkItemGroup').value;
    var store = document.getElementById('bulk_loc_store').value;
    var rack = document.getElementById('bulk_loc_rack').value;
    var level = document.getElementById('bulk_loc_level').value;
    var bin = document.getElementById('bulk_loc_bin').value;
    labels.forEach(function(label) {
        var checkbox = label.querySelector('.bulk-item-checkbox');
        var matches = false;
        if (source === 'manual') {
            matches = checkbox.checked;
            label.style.display = '';
        } else if (source === 'group') {
            matches = group && label.dataset.itemGroup === group;
            label.style.display = matches ? '' : 'none';
        } else if (source === 'location') {
            if (!store) {
                matches = false;
                label.style.display = '';
            } else {
                matches = label.dataset.store === store;
                if (matches && rack) matches = label.dataset.rack === rack;
                if (matches && level) matches = label.dataset.level === level;
                if (matches && bin) matches = label.dataset.bin === bin;
                label.style.display = matches ? '' : 'none';
            }
        }
        if (source !== 'manual') {
            checkbox.checked = matches;
        }
        if (checkbox.checked) { total++; }
    });
    document.getElementById('bulkSelectionStatus').textContent = total + ' item' + (total === 1 ? '' : 's') + ' selected.';
}

function filterBulkItems() {
    var source = document.getElementById('bulkSource').value;
    var group = document.getElementById('bulkItemGroup').value;
    var store = document.getElementById('bulk_loc_store').value;
    var rack = document.getElementById('bulk_loc_rack').value;
    var level = document.getElementById('bulk_loc_level').value;
    var bin = document.getElementById('bulk_loc_bin').value;
    document.querySelectorAll('#bulkModal .bulk-item-row').forEach(function(label) {
        if (source === 'manual') {
            label.style.display = '';
            return;
        }
        if (source === 'group') {
            if (!group) {
                label.style.display = '';
                return;
            }
            label.style.display = label.dataset.itemGroup === group ? '' : 'none';
            return;
        }
        if (source === 'location') {
            if (!store) {
                label.style.display = '';
                return;
            }
            var matches = label.dataset.store === store;
            if (matches && rack) matches = label.dataset.rack === rack;
            if (matches && level) matches = label.dataset.level === level;
            if (matches && bin) matches = label.dataset.bin === bin;
            label.style.display = matches ? '' : 'none';
            return;
        }
        label.style.display = '';
    });
}

function updateBulkGroupCount() {
    var source = document.getElementById('bulkSource').value;
    var group = document.getElementById('bulkItemGroup').value;
    var countBox = document.getElementById('bulkLocationCount');
    var countLabel = document.getElementById('bulkMatchedCount');
    if (source !== 'group' || !group) {
        countBox.style.display = 'none';
        return;
    }
    var total = 0;
    document.querySelectorAll('#bulkModal .bulk-item-row').forEach(function(label) {
        if (label.dataset.itemGroup === group) { total++; }
    });
    countLabel.textContent = total;
    countBox.style.display = 'block';
    filterBulkItems();
}

function escHtml(s) {
    var d = document.createElement('div');
    d.appendChild(document.createTextNode(s));
    return d.innerHTML;
}
</script>

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