<?php
/**
 * Admin - Pending Counts View
 */
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../middleware/role_middleware.php';
admin_only();

$pageTitle = 'Pending Counts';
$db = Database::getInstance();

$statusFilter = $_GET['status'] ?? 'counted';
$sessionFilter = $_GET['session_id'] ?? '';
$page = max(1, (int)($_GET['page'] ?? 1));

$where = "a.status IN ('counted','approved','rejected','pending','in_progress','recount')";
$params = [];
if ($statusFilter && $statusFilter !== 'all') {
    $where = "a.status = ?";
    $params[] = $statusFilter;
}
if ($sessionFilter) {
    $where .= " AND a.session_id = ?";
    $params[] = $sessionFilter;
}

$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 item_name, i.System_Qty as system_quantity, i.Stores, i.Rack, i.Level, i.Bin, a.zone,
           uc.full_name as counter_name, uk.full_name as checker_name,
           ce.counted_quantity, ce.counted_at, ce.notes as count_notes,
           cr.decision, cr.comments as review_comments
    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
    LEFT JOIN count_entries ce ON ce.assignment_id = a.id
    LEFT JOIN check_reviews cr ON cr.assignment_id = a.id
    WHERE $where
    ORDER BY a.updated_at DESC
    LIMIT {$pagination->getLimit()} OFFSET {$pagination->getOffset()}
", $params);

$sessions = $db->fetchAll("SELECT id, name FROM sessions ORDER BY name");

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

<div class="toolbar">
    <form method="GET" class="toolbar-left" style="display:flex;gap:10px;flex-wrap:wrap">
        <select name="status" class="form-control" style="width:auto">
            <option value="all" <?= $statusFilter==='all'?'selected':'' ?>>All Status</option>
            <option value="pending" <?= $statusFilter==='pending'?'selected':'' ?>>Pending</option>
            <option value="in_progress" <?= $statusFilter==='in_progress'?'selected':'' ?>>In Progress</option>
            <option value="counted" <?= $statusFilter==='counted'?'selected':'' ?>>Awaiting Review</option>
            <option value="approved" <?= $statusFilter==='approved'?'selected':'' ?>>Approved</option>
            <option value="rejected" <?= $statusFilter==='rejected'?'selected':'' ?>>Rejected</option>
            <option value="recount" <?= $statusFilter==='recount'?'selected':'' ?>>Recount</option>
        </select>
        <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>
        <button type="submit" class="btn btn-outline">Filter</button>
    </form>
</div>

<div class="card">
    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Location</th>
                    <th>Session</th>
                    <th>Counter</th>
                    <th>System Qty</th>
                    <th>Counted Qty</th>
                    <th>Variance</th>
                    <th>Checker</th>
                    <th>Status</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($assignments)): ?>
                <tr><td colspan="9" class="text-center text-muted" style="padding:40px">No records found.</td></tr>
                <?php else: foreach ($assignments as $a): ?>
                <tr>
                    <td><strong><?= e($a['item_code']) ?></strong><br><small class="text-muted"><?= e($a['item_name']) ?></small></td>
                    <td><?= format_location($a['Stores'], $a['Rack'], $a['Level'], $a['Bin'], $a['zone']) ?></td>
                    <td><?= e($a['session_name']) ?></td>
                    <td><?= e($a['counter_name']) ?></td>
                    <td><?= format_number($a['system_quantity']) ?></td>
                    <td><?= $a['counted_quantity'] !== null ? format_number($a['counted_quantity']) : '-' ?></td>
                    <td>
                        <?php if ($a['counted_quantity'] !== null):
                            $variance = $a['counted_quantity'] - $a['system_quantity'];
                        ?>
                        <span class="variance <?= $variance > 0 ? 'positive' : ($variance < 0 ? 'negative' : 'zero') ?>">
                            <?= $variance > 0 ? '+' : '' ?><?= format_number($variance) ?>
                        </span>
                        <?php else: ?>-<?php endif; ?>
                    </td>
                    <td><?= e($a['checker_name'] ?: '-') ?></td>
                    <td><?= status_badge($a['status']) ?></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>

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