<?php
require_once __DIR__ . '/../includes/auth.php';
AdminAuth::require();

$rows = db()->fetchAll("
    SELECT ws.worker_id, ws.week_start, ws.paid_at, w.name
    FROM week_settlements ws
    JOIN workers w ON w.id = ws.worker_id
    WHERE ws.paid = 1
    ORDER BY ws.week_start DESC, w.name ASC
");

$owedByRow = [];
foreach ($rows as $i => $r) {
    $dates = getWeekDates($r['week_start']);
    $placeholders = implode(',', array_fill(0, count($dates), '?'));
    $entries = db()->query("SELECT * FROM day_entries WHERE worker_id = ? AND work_date IN ({$placeholders})", array_merge([$r['worker_id']], $dates))->fetchAll();
    $owedByRow[$i] = calcOwed($entries);
}

$pageTitle = 'Full History - ChuckCo Time Keeper';
require_once __DIR__ . '/../includes/header.php';
?>
<div class="topbar">
    <h1>Full Payment History</h1>
    <a href="/admin/index.php" class="logout">&larr; Back</a>
</div>
<div class="container">
    <div class="card">
        <h3>All Paid Weeks</h3>
        <?php if (empty($rows)): ?>
            <p class="text-muted">No paid weeks yet.</p>
        <?php else: ?>
            <?php foreach ($rows as $i => $r): ?>
                <div class="worker-row">
                    <a href="/admin/worker.php?id=<?= (int)$r['worker_id'] ?>" style="color:inherit; text-decoration:none;">
                        <strong><?= e($r['name']) ?></strong> &middot; Week of <?= e(dayLabel($r['week_start'])) ?>
                    </a>
                    <span class="worker-owed"><?= formatCurrency($owedByRow[$i] ?? 0) ?></span>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
