<?php

define('PYTHON_SCRIPT', __DIR__ . '/gieniutkowo_donations.py');
define('CACHE_FILE',    __DIR__ . '/donations_cache.json');
define('CACHE_TTL',     1 * 3600);

// ── Fixed starting point ──────────────────────────────────────────────────
// This is the baseline total from when tracking started.
// "Raised since" = current total − this value.

define('BASELINE_DATE',   '03.05.2026');
define('BASELINE_AMOUNT', 461849);     // zł

// ── Load or refresh cache ─────────────────────────────────────────────────

$cache_valid = file_exists(CACHE_FILE)
    && (time() - filemtime(CACHE_FILE)) < CACHE_TTL;

$error_msg = null;

if ($cache_valid) {
    $data       = json_decode(file_get_contents(CACHE_FILE), true);
    $from_cache = true;
} else {
    $python = trim(shell_exec('which python3') ?: '');
    if (!$python) $python = '/usr/bin/python3';

    $cmd  = $python . ' ' . escapeshellarg(PYTHON_SCRIPT) . ' 2>&1';
    $raw  = shell_exec($cmd);
    $data = json_decode($raw, true);

    if (!empty($data['total'])) {
        file_put_contents(CACHE_FILE, json_encode($data));
        $from_cache = false;
    } else {
        $error_msg  = $raw;
        $data       = file_exists(CACHE_FILE) ? json_decode(file_get_contents(CACHE_FILE), true) : null;
        $from_cache = true;
    }
}

// ── Calculate raised since baseline ───────────────────────────────────────

$raised_since = 0;
if ($data && !empty($data['total'])) {
    $raised_since = max(0, $data['total'] - BASELINE_AMOUNT);
}

function fmt(int $n): string {
    return number_format($n, 0, ',', ' ') . ' zł';
}

$cached_at = file_exists(CACHE_FILE) ? filemtime(CACHE_FILE) : time();
$next_run  = $cached_at + CACHE_TTL;
$campaigns = $data['campaigns'] ?? [];
$total     = $data['total']     ?? 0;
$count     = $data['count']     ?? 0;

?><!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gieniutkowo — Donation Totals</title>
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        body { background: #141414; color: #ccc; font-family: 'Segoe UI', system-ui, sans-serif; padding: 2rem 1rem; }
        .container { max-width: 860px; margin: 0 auto; }
        header { margin-bottom: 2rem; }
        header h1 { font-size: 1.4rem; color: #f0c080; display: flex; align-items: center; gap: .5rem; }
        header p  { font-size: .8rem; color: #555; margin-top: .3rem; }
        .badge { font-size: .65rem; padding: 2px 8px; border-radius: 20px; font-weight: 600; text-transform: uppercase; }
        .cached { background: #2a2a2a; color: #666; }
        .fresh  { background: #0d2e1e; color: #4ec9b0; }
        .stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
        .card { background: #1e1e1e; border: 1px solid #2a2a2a; border-radius: 10px; padding: 1.2rem 1.4rem; }
        .card .label { font-size: .72rem; color: #666; text-transform: uppercase; letter-spacing: .06em; margin-bottom: .4rem; }
        .card .value { font-size: 1.6rem; font-weight: 700; color: #fff; }
        .card .sub   { font-size: .7rem; color: #555; margin-top: .3rem; }
        .card.highlight { border-color: #4ec9b040; background: #0d2e1e; }
        .card.highlight .value { color: #4ec9b0; }
        .table-wrap { background: #1e1e1e; border: 1px solid #2a2a2a; border-radius: 10px; overflow: hidden; }
        table { width: 100%; border-collapse: collapse; font-size: .85rem; }
        thead th { background: #252525; color: #777; font-weight: 600; text-transform: uppercase; font-size: .7rem; letter-spacing: .06em; padding: .75rem 1rem; text-align: left; }
        thead th:last-child { text-align: right; }
        tbody tr { border-top: 1px solid #252525; }
        tbody tr:hover { background: #242424; }
        td { padding: .65rem 1rem; }
        td:last-child { text-align: right; font-weight: 600; color: #f0c080; white-space: nowrap; }
        td a { color: #ccc; text-decoration: none; }
        td a:hover { color: #fff; text-decoration: underline; }

        .error-box { background: #2a1010; border: 1px solid #5a2020; border-radius: 10px; padding: 1.2rem 1.4rem; margin-bottom: 2rem; }
        .error-box h2 { color: #f44; font-size: .9rem; margin-bottom: .8rem; }
        .error-box pre { color: #f99; font-size: .78rem; white-space: pre-wrap; word-break: break-all; max-height: 300px; overflow-y: auto; }

        footer { margin-top: 1.5rem; font-size: .75rem; color: #444; text-align: center; }
    </style>
</head>
<body>
<div class="container">

    <header>
        <h1>🐷 Gieniutkowo — Donation Totals
            <?php if ($data): ?>
            <span class="badge <?= $from_cache ? 'cached' : 'fresh' ?>">
                <?= $from_cache ? 'cached' : 'fresh' ?>
            </span>
            <?php endif; ?>
        </h1>
        <?php if (file_exists(CACHE_FILE)): ?>
        <p>
            Last updated: <?= date('d.m.Y H:i:s', $cached_at) ?>
            &nbsp;·&nbsp;
            Next refresh: <?= date('d.m.Y H:i:s', $next_run) ?>
        </p>
        <?php endif; ?>
    </header>

    <?php if ($error_msg): ?>
    <div class="error-box">
        <h2>⚠ Python script error — showing stale cache (if available)</h2>
        <pre><?= htmlspecialchars($error_msg) ?></pre>
    </div>
    <?php endif; ?>

    <?php if (!$data): ?>
        <p style="color:#f44">No data available and no cache found. See error above.</p>
    <?php else: ?>

    <div class="stats">
        <div class="card highlight">
            <div class="label">Raised since <?= BASELINE_DATE ?></div>
            <div class="value"><?= fmt($raised_since) ?></div>
            <div class="sub">starting baseline: <?= fmt(BASELINE_AMOUNT) ?></div>
        </div>
        <div class="card">
            <div class="label">All-time total</div>
            <div class="value"><?= fmt($total) ?></div>
        </div>
        <div class="card">
            <div class="label">Active campaigns</div>
            <div class="value"><?= $count ?></div>
        </div>
    </div>

    <div class="table-wrap">
        <table>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Campaign</th>
                    <th>Amount raised</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($campaigns as $i => $c): ?>
                <tr>
                    <td style="color:#555;font-size:.75rem"><?= $i + 1 ?></td>
                    <td><a href="<?= htmlspecialchars($c['url']) ?>" target="_blank"><?= htmlspecialchars($c['title']) ?></a></td>
                    <td><?= fmt($c['amount']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php endif; ?>

    <footer>
        Data source: <a href="https://pomagam.pl/org/gieniutkowo" target="_blank" style="color:#555">pomagam.pl/org/gieniutkowo</a>
        &nbsp;·&nbsp; Cache TTL: <?= CACHE_TTL / 3600 ?>h
    </footer>

</div>
</body>
</html
