<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Models\User;
use App\Models\Campaign;
use App\Models\Proposal;
use App\Models\AiJob;
use App\Models\RegistrationRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;

class SidebarController extends Controller
{
    /**
     * Get badge counts for super admin sidebar
     *
     * @return array
     */
    public static function getBadgeCounts(): array
    {
        // Cache badge counts for 5 minutes to improve performance
        return Cache::remember('superadmin_sidebar_badges', 300, function () {
            return [
                'badge_dashboard_count' => null, // Dashboard doesn't need a count
                'badge_tenants_count' => Tenant::count(),
                'badge_pending_requests' => RegistrationRequest::where('status', 'pending')->count(),
                'badge_users_count' => User::count(),
                'badge_campaigns_count' => Campaign::count(),
                'badge_active_campaigns' => Campaign::where('status', 'active')->count(),
                'badge_proposals_count' => Proposal::count(),
                'badge_pending_proposals' => Proposal::where('status', 'pending')->count(),
                'badge_ai_jobs_count' => self::getAiJobsCount(),
                'badge_failed_jobs' => self::getFailedJobsCount(),
                'badge_queue_failed' => DB::table('failed_jobs')->count(),
                'badge_processing_reels' => self::getProcessingReelsCount(),
                'badge_failed_payments' => self::getFailedPaymentsCount(),
                'badge_errors' => self::getRecentErrorsCount(),
                'badge_alerts_count' => self::getActiveAlertsCount(),
                'badge_active_alerts' => self::getActiveAlertsCount(),
            ];
        });
    }

    /**
     * Get AI jobs count
     */
    private static function getAiJobsCount(): int
    {
        try {
            return AiJob::count();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Get failed AI jobs count
     */
    private static function getFailedJobsCount(): int
    {
        try {
            return AiJob::where('status', 'failed')->count();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Get processing reels count
     */
    private static function getProcessingReelsCount(): int
    {
        try {
            return DB::table('reels')
                ->whereIn('status', ['pending', 'processing'])
                ->count();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Get failed payments count (last 30 days)
     */
    private static function getFailedPaymentsCount(): int
    {
        try {
            return DB::table('payments')
                ->where('status', 'failed')
                ->where('created_at', '>=', now()->subDays(30))
                ->count();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Get recent errors count (last 24 hours)
     */
    private static function getRecentErrorsCount(): int
    {
        try {
            $logFile = storage_path('logs/laravel.log');
            if (!file_exists($logFile)) {
                return 0;
            }

            $errors = 0;
            $handle = fopen($logFile, 'r');
            $yesterday = now()->subDay();

            while (($line = fgets($handle)) !== false) {
                if (str_contains($line, '.ERROR:') || str_contains($line, '.CRITICAL:')) {
                    // Simple date check - can be improved
                    $errors++;
                }
            }
            fclose($handle);

            return min($errors, 99); // Cap at 99+
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Get active alerts count
     */
    private static function getActiveAlertsCount(): int
    {
        try {
            return DB::table('system_alerts')
                ->where('status', 'active')
                ->where('resolved_at', null)
                ->count();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Clear badge counts cache
     */
    public static function clearCache(): void
    {
        Cache::forget('superadmin_sidebar_badges');
    }

    /**
     * Format badge count for display (cap at 99+)
     */
    public static function formatBadgeCount(int $count): string
    {
        return $count > 99 ? '99+' : (string) $count;
    }
}