<?php
/**
 * OpenVPN | L2TP Bot - Credential Warnings Cron Script
 * 
 * This script should be run periodically via cron (e.g., every hour)
 * 
 * Functions:
 * 1. 5-day warning: Alert admin when credential is 5+ days old
 * 2. Capacity warning: Alert admin when used_seats >= 10
 * 3. Auto-disable: Mark credentials as not sellable after sellable_until
 * 
 * Cron example (run every hour):
 * 0 * * * * php /path/to/scripts/cron_check_credentials.php >> /path/to/storage/logs/cron.log 2>&1
 */

declare(strict_types=1);

// Load config
require __DIR__ . '/../src/config.php';

echo "[" . date('Y-m-d H:i:s') . "] Starting credential check...\n";

try {
    $pdo = db();
    
    // ═══════════════════════════════════════════════════════════════════════
    // 1. Check for 5-day warnings
    // ═══════════════════════════════════════════════════════════════════════
    $stmt = $pdo->query("
        SELECT * FROM credentials 
        WHERE DATEDIFF(NOW(), created_at) >= 5 
          AND warning_5d_sent = 0 
          AND is_active = 1
    ");
    $fiveDayWarnings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($fiveDayWarnings as $cred) {
        $durationLabel = $cred['duration'] === '1Y' ? 'یک‌ساله' : 'یک‌ماهه';
        $remaining = $cred['max_seats'] - $cred['used_seats'];
        $daysSinceCreated = (int)((time() - strtotime($cred['created_at'])) / 86400);
        
        $text = "⚠️ **هشدار ۵ روزه**\n\n";
        $text .= "اشتراک #{$cred['id']} بیش از ۵ روز از ایجادش گذشته است.\n\n";
        $text .= "📅 مدت: {$durationLabel}\n";
        $text .= "📧 ایمیل: `{$cred['email']}`\n";
        $text .= "👥 صندلی باقی‌مانده: {$remaining}/15\n";
        $text .= "⏰ ایجاد شده: {$daysSinceCreated} روز پیش\n";
        $text .= "📆 قابل فروش تا: {$cred['sellable_until']}\n";
        
        // Send to admin
        $keyboard = [
            'inline_keyboard' => [
                [['text' => '➕ افزودن اشتراک جدید در همین دسته', 'callback_data' => "ADMIN_ADD_CREDENTIAL_{$cred['duration']}"]],
            ],
        ];
        
        notifyAdminsWithKeyboard($text, $keyboard);
        
        // Mark as sent
        $updateStmt = $pdo->prepare("UPDATE credentials SET warning_5d_sent = 1 WHERE id = ?");
        $updateStmt->execute([$cred['id']]);
        
        echo "  - Sent 5-day warning for credential #{$cred['id']}\n";
    }
    
    echo "  5-day warnings sent: " . count($fiveDayWarnings) . "\n";
    
    // ═══════════════════════════════════════════════════════════════════════
    // 2. Check for capacity warnings (used_seats >= 10)
    // ═══════════════════════════════════════════════════════════════════════
    $stmt = $pdo->query("
        SELECT * FROM credentials 
        WHERE used_seats >= 10 
          AND capacity_warn_sent = 0 
          AND is_active = 1
    ");
    $capacityWarnings = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($capacityWarnings as $cred) {
        $durationLabel = $cred['duration'] === '1Y' ? 'یک‌ساله' : 'یک‌ماهه';
        $remaining = $cred['max_seats'] - $cred['used_seats'];
        
        $text = "🔴 **هشدار ظرفیت**\n\n";
        $text .= "اشتراک #{$cred['id']} به ظرفیت بحرانی رسیده است.\n\n";
        $text .= "📅 مدت: {$durationLabel}\n";
        $text .= "📧 ایمیل: `{$cred['email']}`\n";
        $text .= "👥 استفاده شده: {$cred['used_seats']}/15\n";
        $text .= "📊 باقی‌مانده: {$remaining} صندلی\n";
        $text .= "📆 قابل فروش تا: {$cred['sellable_until']}\n\n";
        $text .= "لطفاً اشتراک جدید اضافه کنید.";
        
        $keyboard = [
            'inline_keyboard' => [
                [['text' => '➕ افزودن اشتراک جدید در همین دسته', 'callback_data' => "ADMIN_ADD_CREDENTIAL_{$cred['duration']}"]],
            ],
        ];
        
        notifyAdminsWithKeyboard($text, $keyboard);
        
        // Mark as sent
        $updateStmt = $pdo->prepare("UPDATE credentials SET capacity_warn_sent = 1 WHERE id = ?");
        $updateStmt->execute([$cred['id']]);
        
        echo "  - Sent capacity warning for credential #{$cred['id']}\n";
    }
    
    echo "  Capacity warnings sent: " . count($capacityWarnings) . "\n";
    
    // ═══════════════════════════════════════════════════════════════════════
    // 3. Check for expired sellable_until (auto-disable)
    // ═══════════════════════════════════════════════════════════════════════
    $stmt = $pdo->query("
        SELECT id, email, duration FROM credentials 
        WHERE sellable_until < NOW() 
          AND is_active = 1
    ");
    $expired = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (!empty($expired)) {
        // Mark as inactive
        $pdo->exec("UPDATE credentials SET is_active = 0 WHERE sellable_until < NOW() AND is_active = 1");
        
        echo "  Expired credentials marked inactive: " . count($expired) . "\n";
        
        // Notify admin about expired credentials
        if (count($expired) > 0) {
            $text = "⏰ **اشتراک‌های منقضی شده**\n\n";
            $text .= count($expired) . " اشتراک به دلیل پایان پنجره فروش غیرفعال شدند:\n\n";
            
            foreach (array_slice($expired, 0, 5) as $cred) {
                $durationLabel = $cred['duration'] === '1Y' ? 'یک‌ساله' : 'یک‌ماهه';
                $text .= "• #{$cred['id']} - {$durationLabel}\n";
            }
            
            if (count($expired) > 5) {
                $text .= "• و " . (count($expired) - 5) . " مورد دیگر...\n";
            }
            
            notifyAdminsWithKeyboard($text, null);
        }
    }
    
    // ═══════════════════════════════════════════════════════════════════════
    // 4. Summary of available inventory
    // ═══════════════════════════════════════════════════════════════════════
    $stmt = $pdo->query("
        SELECT 
            duration,
            COUNT(*) as total,
            SUM(max_seats - used_seats) as remaining_seats
        FROM credentials 
        WHERE is_active = 1 
          AND sellable_until >= NOW()
          AND used_seats < max_seats
        GROUP BY duration
    ");
    $inventory = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $inventoryLow = false;
    foreach ($inventory as $inv) {
        if ($inv['remaining_seats'] < 10) {
            $inventoryLow = true;
            break;
        }
    }
    
    // If inventory is critically low, send warning
    if ($inventoryLow || empty($inventory)) {
        $text = "📦 **وضعیت موجودی**\n\n";
        
        if (empty($inventory)) {
            $text .= "⚠️ موجودی خالی است!\n";
        } else {
            foreach ($inventory as $inv) {
                $durationLabel = $inv['duration'] === '1Y' ? 'یک‌ساله' : 'یک‌ماهه';
                $status = $inv['remaining_seats'] < 10 ? '🔴' : '🟢';
                $text .= "{$status} {$durationLabel}: {$inv['remaining_seats']} صندلی\n";
            }
        }
        
        $text .= "\nلطفاً موجودی را بررسی کنید.";
        
        notifyAdminsWithKeyboard($text, [
            'inline_keyboard' => [
                [['text' => '➕ افزودن اشتراک', 'callback_data' => 'ADMIN_ADD_CREDENTIAL']],
            ],
        ]);
    }
    
    echo "[" . date('Y-m-d H:i:s') . "] Credential check completed.\n\n";

} catch (Throwable $e) {
    echo "[" . date('Y-m-d H:i:s') . "] ERROR: " . $e->getMessage() . "\n";
    error_log("cron_check_credentials error: " . $e->getMessage());
}

/**
 * Send notification to all admins with optional keyboard
 */
function notifyAdminsWithKeyboard(string $text, ?array $keyboard): void {
    $admins = array_filter(array_map('trim', explode(',', ADMIN_IDS)));
    
    foreach ($admins as $adminId) {
        $params = [
            'chat_id'    => $adminId,
            'text'       => $text,
            'parse_mode' => 'Markdown',
        ];
        
        if ($keyboard) {
            $params['reply_markup'] = json_encode($keyboard, JSON_UNESCAPED_UNICODE);
        }
        
        tg('sendMessage', $params);
        
        // Small delay to avoid rate limiting
        usleep(100000); // 100ms
    }
}

