<?php
/**
 * subscription_expiry.php
 * Recommended frequency: every 5-10 minutes (set this up in cPanel's Cron
 * Job manager, hitting this file's URL).
 *
 * Expires any user_subscriptions row whose end_date has passed and is
 * still marked 'Active' - this works identically for Day, Week, Month, and
 * Year plans, since expiry is purely a date comparison, not tied to the
 * period_type. Can be switched off from Website Manage -> Cron Jobs.
 */

define('PROJECT_ROOT', realpath(dirname(__FILE__)) . '/../');
include PROJECT_ROOT . 'pages/dbFunctions.php';
include PROJECT_ROOT . 'auth/config.php';
include PROJECT_ROOT . 'includes/cron_lib.php';

header('Content-Type: application/json');

if (!cron_is_enabled($conn, 'subscription_expiry')) {
    echo json_encode(['status' => 'skipped', 'reason' => 'Disabled from Website Manage']);
    exit;
}

$today = date('Y-m-d');
$expiredCount = 0;

$result = mysqli_query($conn, "SELECT id, user_id FROM user_subscriptions WHERE status = 'Active' AND end_date < '$today'");
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $id = (int)$row['id'];
        mysqli_query($conn, "UPDATE user_subscriptions SET status = 'Expired' WHERE id = $id");
        $expiredCount++;
    }
}

cron_mark_ran($conn, 'subscription_expiry', "{$expiredCount} subscription(s) expired");

echo json_encode(['status' => 'ok', 'expired_count' => $expiredCount, 'ran_at' => date('Y-m-d H:i:s')]);
