<?php
/**
 * subscription_reminder.php
 * Recommended frequency: once a day (set up in cPanel's Cron Job manager).
 *
 * Emails every user whose active subscription expires in 1-5 days, once
 * per user per calendar day (tracked via user_subscriptions.last_reminder_date
 * so re-running this cron the same day never double-sends). 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';
include PROJECT_ROOT . 'includes/notify_lib.php';

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

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

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

$sql = "SELECT us.id AS sub_id, us.end_date, u.id AS user_id, u.name, u.email, sp.plan_name
        FROM user_subscriptions us
        JOIN users u ON u.id = us.user_id
        JOIN subscription_plan sp ON sp.id = us.plan_id
        WHERE us.status = 'Active'
          AND us.end_date BETWEEN '$today' AND DATE_ADD('$today', INTERVAL 5 DAY)
          AND (us.last_reminder_date IS NULL OR us.last_reminder_date != '$today')
          AND u.email IS NOT NULL AND u.email != ''";

$result = mysqli_query($conn, $sql);
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        $daysLeft = (int)ceil((strtotime($row['end_date']) - strtotime($today)) / 86400);
        $daysLeft = max(0, $daysLeft);

        $sent = send_subscription_reminder($conn, $row['user_id'], $row['email'], $row['name'], $row['plan_name'], $daysLeft, $row['end_date']);
        if ($sent) {
            $subId = (int)$row['sub_id'];
            mysqli_query($conn, "UPDATE user_subscriptions SET last_reminder_date = '$today' WHERE id = $subId");
            $sentCount++;
        }
    }
}

cron_mark_ran($conn, 'subscription_reminder', "{$sentCount} reminder email(s) sent");

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