<?php
/**
 * Hostxolo - Plan Expiry Checker
 * Cron job to check for expiring subscriptions and send notifications
 */

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

class PlanExpiryChecker {
    
    private $db;
    
    public function __construct() {
        $this->db = db();
    }
    
    /**
     * Check for expiring subscriptions
     */
    public function checkExpiringSubscriptions() {
        try {
            // Get subscriptions expiring in next 3 days
            $stmt = $this->db->prepare("
                SELECT us.*, u.full_name, u.email, u.phone, sp.name as plan_name
                FROM user_subscriptions us
                JOIN users u ON us.user_id = u.id
                JOIN subscription_plans sp ON us.plan_id = sp.id
                WHERE us.status = 'active' 
                AND us.end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
                AND (us.expiry_notified = 0 OR us.expiry_notified IS NULL)
            ");
            $stmt->execute();
            $expiring_soon = $stmt->fetchAll();
            
            // Get subscriptions that expired today
            $stmt = $this->db->prepare("
                SELECT us.*, u.full_name, u.email, u.phone, sp.name as plan_name
                FROM user_subscriptions us
                JOIN users u ON us.user_id = u.id
                JOIN subscription_plans sp ON us.plan_id = sp.id
                WHERE us.status = 'active' 
                AND us.end_date < CURDATE()
            ");
            $stmt->execute();
            $expired = $stmt->fetchAll();
            
            // Process expiring soon notifications
            foreach ($expiring_soon as $subscription) {
                $this->sendExpiryNotification($subscription, 'expiring_soon');
                $this->markAsNotified($subscription['id']);
            }
            
            // Process expired notifications
            foreach ($expired as $subscription) {
                $this->sendExpiryNotification($subscription, 'expired');
                $this->updateExpiredStatus($subscription['id']);
            }
            
            echo "Processed " . count($expiring_soon) . " expiring soon and " . count($expired) . " expired subscriptions\n";
            
        } catch (PDOException $e) {
            error_log("Plan expiry check error: " . $e->getMessage());
            echo "Error: " . $e->getMessage() . "\n";
        }
    }
    
    /**
     * Send expiry notification
     */
    private function sendExpiryNotification($subscription, $type) {
        require_once __DIR__ . '/notification-system.php';
        
        $notification_data = [
            'plan_name' => $subscription['plan_name'],
            'end_date' => $subscription['end_date'],
            'amount' => $subscription['amount']
        ];
        
        if ($type === 'expiring_soon') {
            triggerExpiryNotification($subscription['user_id'], $notification_data);
        } else {
            triggerExpiryNotification($subscription['user_id'], $notification_data);
        }
    }
    
    /**
     * Mark subscription as notified
     */
    private function markAsNotified($subscription_id) {
        try {
            $stmt = $this->db->prepare("UPDATE user_subscriptions SET expiry_notified = 1 WHERE id = ?");
            $stmt->execute([$subscription_id]);
        } catch (PDOException $e) {
            error_log("Error marking subscription as notified: " . $e->getMessage());
        }
    }
    
    /**
     * Update expired subscription status
     */
    private function updateExpiredStatus($subscription_id) {
        try {
            $stmt = $this->db->prepare("UPDATE user_subscriptions SET status = 'expired' WHERE id = ?");
            $stmt->execute([$subscription_id]);
        } catch (PDOException $e) {
            error_log("Error updating expired subscription: " . $e->getMessage());
        }
    }
}

// Run the checker if accessed directly
if (php_sapi_name() === 'cli' || isset($_GET['run'])) {
    $checker = new PlanExpiryChecker();
    $checker->checkExpiringSubscriptions();
}
