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

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

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

$weekStart = $_GET['week'] ?? '';
$weekStart = isValidDateStr($weekStart) ? $weekStart : currentWeekStart();
$dates = getWeekDates($weekStart);
$detail = !empty($_GET['detail']);

$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; }

$hasLongReason = false;
foreach ($entriesByDate as $en) {
    if (!empty($en['absence_reason']) && strlen($en['absence_reason']) > 40) $hasLongReason = true;
}

$pageTitle = 'Week Summary - ChuckCo Time Keeper';
require_once __DIR__ . '/includes/header.php';
?>
<div class="container" style="padding-top:1.5rem;">
    <div class="screenshot-card">
        <div class="screenshot-header">
            <div class="name"><?= e($worker['name']) ?></div>
            <div class="range">Week of <?= e(dayLabel($weekStart)) ?></div>
        </div>

        <?php foreach ($dates as $date):
            $entry = $entriesByDate[$date] ?? null;
            $status = $entry['status'] ?? null;
            $reason = $entry['absence_reason'] ?? '';
            $location = $entry['location'] ?? '';
        ?>
        <div class="screenshot-day">
            <div>
                <div class="date"><?= e(dayLabel($date)) ?></div>
                <?php if ($location): ?>
                    <div class="reason-text"><?= e($location) ?></div>
                <?php endif; ?>
                <?php if ($status === 'absent' && $reason): ?>
                    <div class="reason-text"><?= e($detail ? $reason : (strlen($reason) > 40 ? substr($reason, 0, 40) . '…' : $reason)) ?></div>
                <?php endif; ?>
            </div>
            <span class="badge badge-<?= $status ? e($status) : 'unset' ?>"><?= $status ? ucfirst($status) : 'Not set' ?></span>
        </div>
        <?php endforeach; ?>

        <?php if ($hasLongReason && !$detail): ?>
        <div class="more-link"><a href="?t=<?= e($token) ?>&week=<?= e($weekStart) ?>&detail=1">More detail &rarr;</a></div>
        <?php elseif ($detail): ?>
        <div class="more-link"><a href="?t=<?= e($token) ?>&week=<?= e($weekStart) ?>">&larr; Back</a></div>
        <?php endif; ?>
    </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
