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

$markPaidError = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'mark_paid' && isValidDateStr($_POST['week_start'] ?? '')) {
    $weekStart = $_POST['week_start'];
    $weekDates = getWeekDates($weekStart);
    $ph = implode(',', array_fill(0, count($weekDates), '?'));
    $weekEntries = db()->query("SELECT work_date FROM day_entries WHERE worker_id = ? AND work_date IN ({$ph})", array_merge([$worker['id']], $weekDates))->fetchAll();
    $filledDates = array_column($weekEntries, 'work_date');
    $missing = array_diff($weekDates, $filledDates);

    if (!empty($missing)) {
        $markPaidError = 'Cannot mark paid - ' . count($missing) . ' day(s) still need an entry.';
    } else {
        $existing = db()->fetch("SELECT * FROM week_settlements WHERE worker_id = :wid AND week_start = :w", ['wid' => $worker['id'], 'w' => $weekStart]);
        if ($existing) {
            db()->update('week_settlements', ['paid' => 1, 'paid_at' => date('Y-m-d H:i:s')], 'id = :id', ['id' => $existing['id']]);
        } else {
            db()->insert('week_settlements', ['worker_id' => $worker['id'], 'week_start' => $weekStart, 'paid' => 1, 'paid_at' => date('Y-m-d H:i:s')]);
        }
        header('Location: /p.php?t=' . urlencode($token) . '&week=' . urlencode(nextWeekStart($weekStart)));
        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; }

$owed = calcOwed($entries);
$settlement = db()->fetch("SELECT * FROM week_settlements WHERE worker_id = :wid AND week_start = :w", ['wid' => $worker['id'], 'w' => $weekStart]);
$isPaid = $settlement ? (bool) $settlement['paid'] : false;

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

$pageTitle = 'Week Summary (Payer) - 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)) ?> &middot; <?= $isPaid ? 'Paid' : 'Unpaid' ?></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; ?>

        <div class="owed-total">
            <span>Owed</span>
            <span><?= formatCurrency($owed) ?></span>
        </div>

        <?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; ?>

        <?php if ($markPaidError): ?>
        <div class="alert alert-error" style="margin-top:1rem;"><?= e($markPaidError) ?></div>
        <?php endif; ?>
        <?php if (!$isPaid): ?>
        <form method="POST" style="margin-top:1rem;" onsubmit="return confirm('Time will be locked in and start new week. Are you sure?');">
            <input type="hidden" name="action" value="mark_paid">
            <input type="hidden" name="week_start" value="<?= e($weekStart) ?>">
            <button type="submit" class="btn btn-success btn-block">Mark Paid &amp; Advance to Next Week</button>
        </form>
        <?php endif; ?>
        <div class="link-row" style="margin-top:0.75rem; justify-content:center;">
            <a class="btn btn-sm btn-secondary" href="/history.php?t=<?= e($token) ?>">View History</a>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>
