<?php
/**
 * Weekly Report Cron Job
 *
 * Run every Sunday night (or Monday morning):
 *   0 20 * * 0 php /path/to/cron_weekly_reports.php
 *
 * - Subscribers: auto-sends the full report (free)
 * - Credit users: sends a notification with a "Generate Report" button
 */

$config = include __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions/credits.php';
require_once __DIR__ . '/functions/subscription.php';
require_once __DIR__ . '/functions/streak.php';
require_once __DIR__ . '/functions/reports.php';

// Only run on Sunday (ISO weekday 7)
if (php_sapi_name() !== 'cli' && date('N') !== '7') {
    exit("Run on Sundays only, or via CLI for testing.\n");
}

$weekStart = date('Y-m-d', strtotime('last Monday'));
$users     = $pdo->query("SELECT chat_id FROM users")->fetchAll(PDO::FETCH_COLUMN);

$sentSub    = 0;
$sentNotif  = 0;
$skipped    = 0;

echo "[" . date('H:i:s') . "] Weekly reports: " . count($users) . " users\n";

foreach ($users as $chat_id) {
    // Already sent this week?
    $already = $pdo->prepare("SELECT id FROM weekly_reports WHERE chat_id = ? AND week_start = ?");
    $already->execute([$chat_id, $weekStart]);
    if ($already->fetchColumn()) {
        $skipped++;
        continue;
    }

    if (hasActiveSubscription($chat_id)) {
        // Subscribers get the full report automatically
        if (sendWeeklyReport($chat_id)) {
            $sentSub++;
        }
    } else {
        // Credit users get a notification with a button
        sendWeeklyReportNotification($chat_id);
        $sentNotif++;
    }

    usleep(50000); // 50 ms rate limit between sends
}

echo "[" . date('H:i:s') . "] Done.\n";
echo "  Subscriber reports sent: {$sentSub}\n";
echo "  Credit user notifications: {$sentNotif}\n";
echo "  Already sent (skipped): {$skipped}\n";

// ─── Standalone message sender (no bot.php dependency) ───────────────────────
function sendMessage($chat_id, $text, $keyboard = null) {
    global $config;
    $data = [
        'chat_id'    => $chat_id,
        'text'       => $text,
        'parse_mode' => 'HTML',
    ];
    if ($keyboard) $data['reply_markup'] = json_encode($keyboard);

    $body = http_build_query($data);
    $ctx  = stream_context_create(['http' => [
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $body,
        'timeout' => 10,
    ]]);
    return @file_get_contents(
        "https://api.telegram.org/bot{$config['telegram_token']}/sendMessage",
        false,
        $ctx
    );
}
