<?php
/**
 * CRON Job Script - Expire Old Subscriptions
 * 
 * This script should be called daily via cron job to check and expire subscriptions
 * Since shared hosting doesn't allow MySQL events, we use this PHP script instead
 * 
 * SETUP INSTRUCTIONS:
 * 
 * 1. In cPanel or your hosting control panel, go to Cron Jobs
 * 
 * 2. Add a new cron job with this schedule:
 *    Frequency: Daily at 2:00 AM
 *    Command: curl "https://yoursite.com/api/cron_expire_subscriptions.php?secret=YOUR_SECRET_KEY"
 *    
 *    OR if curl is not available:
 *    Command: wget -q -O /dev/null "https://yoursite.com/api/cron_expire_subscriptions.php?secret=YOUR_SECRET_KEY"
 *    
 *    OR run directly with PHP:
 *    Command: /usr/bin/php /path/to/ensi/api/cron_expire_subscriptions.php YOUR_SECRET_KEY
 * 
 * 3. Change YOUR_SECRET_KEY below to a random secret string (keep it secure!)
 * 
 * CRON SCHEDULE EXAMPLES:
 * - Daily at 2 AM: 0 2 * * *
 * - Every 6 hours: 0 */6 * * *
 * - Every hour: 0 * * * *
 */

// Security: Define a secret key to prevent unauthorized access
define('CRON_SECRET_KEY', 'change_this_to_a_random_secret_key_12345');

require_once 'config.php';

// Validate access
if (php_sapi_name() === 'cli') {
    // Running from command line - check command line argument
    if (!isset($argv[1]) || $argv[1] !== CRON_SECRET_KEY) {
        die("Error: Invalid secret key\n");
    }
} else {
    // Running from web - check GET parameter
    $secret = $_GET['secret'] ?? '';
    if ($secret !== CRON_SECRET_KEY) {
        http_response_code(403);
        die(json_encode([
            'success' => false,
            'message' => 'Unauthorized access. Invalid secret key.'
        ]));
    }
}

try {
    $conn = getDBConnection();
    
    if (!$conn) {
        throw new Exception('Database connection failed');
    }
    
    // Call the stored procedure to expire old subscriptions
    $stmt = $conn->prepare("CALL update_expired_subscriptions()");
    $stmt->execute();
    
    // Log the execution
    $logMessage = date('Y-m-d H:i:s') . " - Subscription expiration check completed successfully\n";
    error_log($logMessage);
    
    // Get some statistics
    $stmt = $conn->prepare("
        SELECT 
            COUNT(*) as total_active,
            SUM(CASE WHEN DATEDIFF(end_date, NOW()) <= 7 THEN 1 ELSE 0 END) as expiring_soon
        FROM user_subscriptions 
        WHERE status = 'active'
    ");
    $stmt->execute();
    $stats = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $response = [
        'success' => true,
        'message' => 'Subscription expiration check completed',
        'timestamp' => date('Y-m-d H:i:s'),
        'statistics' => [
            'total_active_subscriptions' => (int)$stats['total_active'],
            'expiring_within_7_days' => (int)$stats['expiring_soon']
        ]
    ];
    
    if (php_sapi_name() === 'cli') {
        // Command line output
        echo "Subscription Expiration Check\n";
        echo "============================\n";
        echo "Status: Success\n";
        echo "Time: " . $response['timestamp'] . "\n";
        echo "Active Subscriptions: " . $response['statistics']['total_active_subscriptions'] . "\n";
        echo "Expiring Soon (7 days): " . $response['statistics']['expiring_within_7_days'] . "\n";
    } else {
        // Web output (JSON)
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
    
} catch (PDOException $e) {
    $errorMessage = date('Y-m-d H:i:s') . " - Database error: " . $e->getMessage() . "\n";
    error_log($errorMessage);
    
    if (php_sapi_name() === 'cli') {
        echo "Error: Database error occurred\n";
        echo $e->getMessage() . "\n";
        exit(1);
    } else {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => 'Database error occurred',
            'error' => $e->getMessage()
        ]);
    }
} catch (Exception $e) {
    $errorMessage = date('Y-m-d H:i:s') . " - Error: " . $e->getMessage() . "\n";
    error_log($errorMessage);
    
    if (php_sapi_name() === 'cli') {
        echo "Error: " . $e->getMessage() . "\n";
        exit(1);
    } else {
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
}
