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

$token = $_GET['t'] ?? '';
$worker = $token ? db()->fetch("SELECT * FROM workers WHERE entry_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']]);

$pageTitle = 'My History - ChuckCo Time Keeper';
require_once __DIR__ . '/includes/header.php';
?>
<div class="topbar">
    <h1>My History</h1>
    <a href="/w.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): ?>
                <?php
                $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();
                $entriesByDate = [];
                foreach ($entries as $en) { $entriesByDate[$en['work_date']] = $en; }
                ?>
                <div class="card" style="background:var(--bg); box-shadow:none;">
                    <h4 style="margin-top:0;">Week of <?= e(dayLabel($pw['week_start'])) ?></h4>
                    <?php foreach ($dates as $d):
                        $entry = $entriesByDate[$d] ?? null;
                        if (!$entry) continue;
                    ?>
                    <div class="screenshot-day">
                        <div>
                            <div class="date"><?= e(dayLabel($d)) ?></div>
                            <?php if (!empty($entry['location'])): ?>
                                <div class="reason-text"><?= e($entry['location']) ?></div>
                            <?php endif; ?>
                        </div>
                        <span class="badge badge-<?= e($entry['status']) ?>"><?= ucfirst($entry['status']) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
