#!/usr/bin/env php
<?php
/**
 * Check Expired Subscriptions
 * Cron job: Daily at midnight
 * Deactivates expired subscriptions and sends notifications
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';

$pdo = getDB();
$logFile = __DIR__ . '/../logs/cron.log';

function logMessage($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

logMessage("=== Starting subscription check ===");

// Deactivate expired subscriptions
$stmt = $pdo->prepare("UPDATE subscriptions 
                       SET is_active = 0 
                       WHERE plan_type != 'unlimited' 
                       AND end_date < CURDATE() 
                       AND is_active = 1");
$stmt->execute();
$deactivated = $stmt->rowCount();
logMessage("Deactivated $deactivated expired subscriptions");

// Get expiring subscriptions (7 days)
$stmt = $pdo->prepare("SELECT s.*, u.email, u.full_name 
                       FROM subscriptions s
                       JOIN users u ON s.user_id = u.id
                       WHERE s.is_active = 1 
                       AND s.plan_type != 'unlimited'
                       AND s.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)");
$stmt->execute();
$expiring = $stmt->fetchAll();

foreach ($expiring as $sub) {
    $daysLeft = (strtotime($sub['end_date']) - time()) / 86400;
    $subject = "Subscription Expiring Soon - $daysLeft Days Left";
    $message = "Dear Dr. {$sub['full_name']},\n\n";
    $message .= "Your subscription will expire on " . date('d-m-Y', strtotime($sub['end_date'])) . ".\n";
    $message .= "Please renew to continue using the system.\n\n";
    $message .= "Best regards,\nHomoeopathy System";
    
    // Send email (implement your mail function)
    // mail($sub['email'], $subject, $message);
    
    logMessage("Notification sent to {$sub['email']} - Expires: {$sub['end_date']}");
}

logMessage("=== Subscription check completed ===");