<?php
// filepath: c:\Users\KAMRAN\Desktop\AdaWizard-feat-ada-compliance-checker\ada_wizard_app\public\api\check_expired_subscriptions.php

// This script should be run daily via cron job or manually
// Example cron entry: 0 2 * * * /usr/bin/php /path/to/your/app/public/api/check_expired_subscriptions.php

require_once __DIR__ . '/../../config/db_connect.php';
require_once __DIR__ . '/../../config/db_config.php';
require_once __DIR__ . '/../../vendor/autoload.php';

\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);

// Create logs directory if it doesn't exist
$log_dir = __DIR__ . '/logs/';
if (!is_dir($log_dir)) {
    mkdir($log_dir, 0755, true);
}

$log_file = $log_dir . 'subscription_check_' . date('Y-m-d') . '.log';

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

logMessage("=== Starting Subscription Expiry Check ===");

try {
    // Find all active subscriptions that might be expired
    $query = "
        SELECT id, user_id, domain_name, plan_type, subscription_end_date, 
               stripe_subscription_id, subscription_status 
        FROM websites 
        WHERE subscription_status = 'active' 
        AND plan_type IN ('monthly', 'yearly')
        AND subscription_end_date IS NOT NULL
        AND subscription_end_date <= NOW()
    ";
    
    $result = $mysqli->query($query);
    
    if (!$result) {
        throw new Exception("Database query failed: " . $mysqli->error);
    }
    
    $expired_count = 0;
    $updated_count = 0;
    
    logMessage("Found " . $result->num_rows . " potentially expired subscriptions");
    
    while ($website = $result->fetch_assoc()) {
        $expired_count++;
        logMessage("Processing website ID {$website['id']} - Domain: {$website['domain_name']} - Plan: {$website['plan_type']}");
        
        $should_deactivate = true;
        
        // Check with Stripe if subscription is still active (in case of webhook failures)
        if (!empty($website['stripe_subscription_id'])) {
            try {
                $stripe_subscription = \Stripe\Subscription::retrieve($website['stripe_subscription_id']);
                
                if ($stripe_subscription->status === 'active') {
                    // Subscription is still active in Stripe, update our end date
                    $new_end_date = date('Y-m-d H:i:s', $stripe_subscription->current_period_end);
                    
                    $update_stmt = $mysqli->prepare("
                        UPDATE websites 
                        SET subscription_end_date = ? 
                        WHERE id = ?
                    ");
                    $update_stmt->bind_param("si", $new_end_date, $website['id']);
                    
                    if ($update_stmt->execute()) {
                        logMessage("Updated subscription end date for website ID {$website['id']} to {$new_end_date}");
                        $should_deactivate = false;
                    }
                    $update_stmt->close();
                    
                } elseif (in_array($stripe_subscription->status, ['canceled', 'incomplete_expired', 'unpaid'])) {
                    logMessage("Stripe subscription {$website['stripe_subscription_id']} is {$stripe_subscription->status}");
                }
                
            } catch (\Stripe\Exception\ApiErrorException $e) {
                logMessage("Stripe API error for subscription {$website['stripe_subscription_id']}: " . $e->getMessage());
                // Continue with deactivation if we can't verify with Stripe
            }
        }
        
        // Deactivate the subscription
        if ($should_deactivate) {
            $deactivate_stmt = $mysqli->prepare("
                UPDATE websites 
                SET subscription_status = 'inactive' 
                WHERE id = ? AND subscription_status = 'active'
            ");
            $deactivate_stmt->bind_param("i", $website['id']);
            
            if ($deactivate_stmt->execute() && $deactivate_stmt->affected_rows > 0) {
                $updated_count++;
                logMessage("Deactivated website ID {$website['id']} - {$website['domain_name']}");
                
                // Optional: Send email notification to user
                // sendExpirationNotification($website);
                
            } else {
                logMessage("Failed to deactivate website ID {$website['id']} or already inactive");
            }
            $deactivate_stmt->close();
        }
    }
    
    logMessage("=== Subscription Check Complete ===");
    logMessage("Expired subscriptions found: $expired_count");
    logMessage("Subscriptions deactivated: $updated_count");
    
} catch (Exception $e) {
    logMessage("ERROR: " . $e->getMessage());
    logMessage("ERROR Trace: " . $e->getTraceAsString());
} finally {
    if (isset($mysqli)) {
        $mysqli->close();
    }
}

// Optional: Clean up old log files (keep last 30 days)
if (is_dir($log_dir)) {
    $files = glob($log_dir . 'subscription_check_*.log');
    foreach ($files as $file) {
        if (filemtime($file) < strtotime('-30 days')) {
            unlink($file);
        }
    }
}

logMessage("=== Script finished ===");
?>