<?php
// admin/cron-expiry-reminder.php
// ============================================================
// CRON JOB: Send VIP expiry reminder emails to users whose
// VIP will expire in the next 7 days.
// Run this script daily (e.g., at 09:00 AM).
// ============================================================

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/includes/EmailService.php';

// Security: allow execution only via CLI or with a secret key in URL
if (php_sapi_name() !== 'cli') {
    $secret = 'your-secret-key-here'; // CHANGE THIS
    if (!isset($_GET['key']) || $_GET['key'] !== $secret) {
        die("Access denied. Use CLI or provide valid key.");
    }
}

echo "Starting VIP expiry reminders...\n";

$emailService = new EmailService($pdo);

// Users whose VIP expires between now and 7 days from now
$stmt = $pdo->prepare("
    SELECT id, full_name, email, vip_expires_at 
    FROM users 
    WHERE user_tier = 'VIP' 
    AND vip_expires_at BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 7 DAY)
");
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

$sent = 0;
$failed = 0;

foreach ($users as $user) {
    $result = $emailService->sendTemplateEmail('subscription_expiry', $user['email'], [
        'user_name'   => $user['full_name'],
        'expiry_date' => date('F j, Y', strtotime($user['vip_expires_at'])),
        'renewal_link'=> SITE_URL . '/user/billing.php'
    ]);
    if ($result) {
        $sent++;
    } else {
        $failed++;
    }
}

echo "✅ Expiry reminders sent: {$sent}\n";
echo "❌ Failed: {$failed}\n";
echo "Total users expiring in 7 days: " . count($users) . "\n";