<?php
/**
 * Check Expired Subscriptions Cron Job
 * Run every 1 hour
 */

declare(strict_types=1);

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../Database.php';
require_once __DIR__ . '/../Telegram.php';
require_once __DIR__ . '/../SubscriptionManager.php';

set_time_limit(60);

$db = Database::getInstance();
$telegram = Telegram::getInstance();
$subManager = SubscriptionManager::getInstance();

// Check and expire subscriptions
$expiredCount = $subManager->checkExpiredSubscriptions();

if ($expiredCount > 0) {
    echo "Expired {$expiredCount} subscriptions\n";
}

// Notify users about expiring subscriptions (3 days before)
$expiringSoon = $db->fetchAll(
    "SELECT us.*, m.first_name 
     FROM `user_subscriptions` us
     LEFT JOIN `members` m ON us.user_id = m.id
     WHERE us.status = 'active' 
     AND us.end_date BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 3 DAY)
     AND us.notified_expiry IS NULL"
);

foreach ($expiringSoon as $sub) {
    $daysLeft = ceil((strtotime($sub['end_date']) - time()) / 86400);
    
    $message = "⚠️ *اخطار انقضای اشتراک*\n\n" .
               "اشتراک شما {$daysLeft} روز دیگر منقضی می‌شود!\n\n" .
               "📅 تاریخ انقضا: " . date('Y/m/d', strtotime($sub['end_date'])) . "\n\n" .
               "برای تمدید اشتراک از دستور /subscribe استفاده کنید.";
    
    $telegram->sendMessage($sub['user_id'], $message);
    
    // Mark as notified
    $db->query(
        "UPDATE `user_subscriptions` SET notified_expiry = NOW() WHERE id = {$sub['id']}"
    );
    
    echo "Notified user {$sub['user_id']} about expiring subscription\n";
    
    // Sleep to avoid rate limit
    sleep(1);
}

echo "Check subscriptions cron completed at " . date('Y-m-d H:i:s') . "\n";
