<?php
require_once __DIR__ . '/includes/functions.php';

$token = $_GET['t'] ?? '';
$worker = $token ? db()->fetch("SELECT * FROM workers WHERE payer_token = :t AND active = 1", ['t' => $token]) : null;

if (!$worker) {
    http_response_code(404);
    echo 'Link not found.';
    exit;
}

$paidWeeks = db()->fetchAll("
    SELECT week_start, paid_at FROM week_settlements
    WHERE worker_id = :wid AND paid = 1
    ORDER BY week_start DESC
", ['wid' => $worker['id']]);

$owedByWeek = [];
foreach ($paidWeeks as $pw) {
    $dates = getWeekDates($pw['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([$worker['id']], $dates))->fetchAll();
    $owedByWeek[$pw['week_start']] = calcOwed($entries);
}

$pageTitle = 'Payment History - ChuckCo Time Keeper';
require_once __DIR__ . '/includes/header.php';
?>
<div class="topbar">
    <h1><?= e($worker['name']) ?> - History</h1>
    <a href="/p.php?t=<?= e($token) ?>" class="logout">&larr; Back</a>
</div>
<div class="container">
    <div class="card">
        <h3>Paid Weeks</h3>
        <?php if (empty($paidWeeks)): ?>
            <p class="text-muted">No paid weeks yet.</p>
        <?php else: ?>
            <?php foreach ($paidWeeks as $pw): ?>
                <div class="worker-row">
                    <a href="/p.php?t=<?= e($token) ?>&week=<?= e($pw['week_start']) ?>" style="color:inherit; text-decoration:none;">
                        Week of <?= e(dayLabel($pw['week_start'])) ?>
                    </a>
                    <span class="worker-owed"><?= formatCurrency($owedByWeek[$pw['week_start']] ?? 0) ?></span>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
