<?php

namespace Plugins\SAMBans\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Plugins\SAMBans\Models\Ban;
use Plugins\SAMBans\Models\Player;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class BansController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index(Request $request)
    {
        try {
            $query = Ban::query()
                ->leftJoin('sam_players', 'sam_bans.steamid', '=', 'sam_players.steamid')
                ->leftJoin('sam_players as admin_players', 'sam_bans.admin', '=', 'admin_players.steamid')
                ->select(
                    'sam_bans.*',
                    'sam_players.name as player_name',
                    'admin_players.name as admin_name'
                );

            // Filter by status
            $status = $request->get('status', 'active');
            switch ($status) {
                case 'active':
                    $query->active();
                    break;
                case 'expired':
                    $query->expired();
                    break;
                case 'all':
                    // No filter
                    break;
            }

            // Search functionality
            if ($search = $request->get('search')) {
                $query->where(function($q) use ($search) {
                    $q->where('sam_bans.steamid', 'LIKE', "%{$search}%")
                      ->orWhere('sam_bans.reason', 'LIKE', "%{$search}%")
                      ->orWhere('sam_bans.admin', 'LIKE', "%{$search}%")
                      ->orWhere('sam_players.name', 'LIKE', "%{$search}%")
                      ->orWhere('admin_players.name', 'LIKE', "%{$search}%");
                });
            }

            // Sort by most recent bans first
            $query->recent();

            // Get pagination settings
            $perPage = $request->get('per_page', 25);
            $perPage = in_array($perPage, [10, 25, 50, 100]) ? $perPage : 25;

            // Paginate results
            $bans = $query->paginate($perPage);

            // Append query parameters to pagination links
            $bans->appends($request->query());

            // Get statistics
            $stats = $this->getBanStatistics();

            return view('sambans::bans.index', compact('bans', 'stats', 'status', 'search', 'perPage'));

        } catch (\Exception $e) {
            Log::error('SAM Bans: Error loading bans page: ' . $e->getMessage());
            
            return view('sambans::bans.error', [
                'error' => 'Unable to connect to SAM database. Please check the plugin configuration.',
                'details' => config('app.debug') ? $e->getMessage() : null
            ]);
        }
    }

    public function show(Request $request, $steamid)
    {
        try {
            $ban = Ban::leftJoin('sam_players', 'sam_bans.steamid', '=', 'sam_players.steamid')
                ->leftJoin('sam_players as admin_players', 'sam_bans.admin', '=', 'admin_players.steamid')
                ->select(
                    'sam_bans.*',
                    'sam_players.name as player_name',
                    'admin_players.name as admin_name'
                )
                ->where('sam_bans.steamid', $steamid)
                ->first();

            if (!$ban) {
                abort(404, 'Ban not found');
            }

            // Get player's ban history if sam_players table exists
            $playerHistory = [];
            try {
                $playerHistory = Ban::leftJoin('sam_players as admin_players', 'sam_bans.admin', '=', 'admin_players.steamid')
                    ->select(
                        'sam_bans.*',
                        'admin_players.name as admin_name'
                    )
                    ->where('sam_bans.steamid', $steamid)
                    ->orderBy('unban_date', 'desc')
                    ->get();
            } catch (\Exception $e) {
                Log::warning('SAM Bans: Could not load player history: ' . $e->getMessage());
            }

            return view('sambans::bans.show', compact('ban', 'playerHistory'));

        } catch (\Exception $e) {
            Log::error('SAM Bans: Error loading ban details: ' . $e->getMessage());
            abort(500, 'Error loading ban details');
        }
    }

    public function players(Request $request)
    {
        try {
            $query = Player::query();

            // Search functionality
            if ($search = $request->get('search')) {
                $query->search($search);
            }

            // Filter by ban status
            $filter = $request->get('filter', 'all');
            switch ($filter) {
                case 'banned':
                    $query->whereHas('bans', function($q) {
                        $q->active();
                    });
                    break;
                case 'clean':
                    $query->whereDoesntHave('bans', function($q) {
                        $q->active();
                    });
                    break;
            }

            $query->recentlyActive();

            $perPage = $request->get('per_page', 25);
            $perPage = in_array($perPage, [10, 25, 50, 100]) ? $perPage : 25;

            $players = $query->paginate($perPage);
            $players->appends($request->query());

            return view('sambans::players.index', compact('players', 'search', 'filter', 'perPage'));

        } catch (\Exception $e) {
            Log::error('SAM Bans: Error loading players page: ' . $e->getMessage());
            
            return view('sambans::bans.error', [
                'error' => 'Unable to load players data.',
                'details' => config('app.debug') ? $e->getMessage() : null
            ]);
        }
    }

    public function statistics()
    {
        try {
            $stats = $this->getBanStatistics();
            
            // Additional detailed statistics
            $detailedStats = [
                'bans_by_month' => $this->getBansByMonth(),
                'top_ban_reasons' => $this->getTopBanReasons(),
                'top_admins' => $this->getTopAdmins(),
                'ban_duration_breakdown' => $this->getBanDurationBreakdown()
            ];

            return view('sambans::statistics.index', compact('stats', 'detailedStats'));

        } catch (\Exception $e) {
            Log::error('SAM Bans: Error loading statistics: ' . $e->getMessage());
            
            return view('sambans::bans.error', [
                'error' => 'Unable to load statistics.',
                'details' => config('app.debug') ? $e->getMessage() : null
            ]);
        }
    }

    private function getBanStatistics()
    {
        try {
            return [
                'total_bans' => Ban::count(),
                'active_bans' => Ban::active()->count(),
                'expired_bans' => Ban::expired()->count(),
                'permanent_bans' => Ban::where('unban_date', 0)->count(),
                'bans_today' => Ban::where('unban_date', '>=', strtotime('today'))->count(),
                'bans_this_week' => Ban::where('unban_date', '>=', strtotime('-1 week'))->count(),
                'bans_this_month' => Ban::where('unban_date', '>=', strtotime('-1 month'))->count(),
            ];
        } catch (\Exception $e) {
            Log::warning('SAM Bans: Error getting ban statistics: ' . $e->getMessage());
            return [
                'total_bans' => 0,
                'active_bans' => 0,
                'expired_bans' => 0,
                'permanent_bans' => 0,
                'bans_today' => 0,
                'bans_this_week' => 0,
                'bans_this_month' => 0,
            ];
        }
    }

    private function getBansByMonth()
    {
        try {
            return DB::connection('sambans')
                ->table('sam_bans')
                ->selectRaw('DATE_FORMAT(FROM_UNIXTIME(unban_date), "%Y-%m") as month, COUNT(*) as count')
                ->where('unban_date', '>', 0)
                ->groupBy('month')
                ->orderBy('month', 'desc')
                ->limit(12)
                ->get();
        } catch (\Exception $e) {
            return collect();
        }
    }

    private function getTopBanReasons()
    {
        try {
            return DB::connection('sambans')
                ->table('sam_bans')
                ->selectRaw('reason, COUNT(*) as count')
                ->whereNotNull('reason')
                ->where('reason', '!=', '')
                ->groupBy('reason')
                ->orderBy('count', 'desc')
                ->limit(10)
                ->get();
        } catch (\Exception $e) {
            return collect();
        }
    }

    private function getTopAdmins()
    {
        try {
            return DB::connection('sambans')
                ->table('sam_bans')
                ->leftJoin('sam_players', 'sam_bans.admin', '=', 'sam_players.steamid')
                ->selectRaw('sam_bans.admin, COALESCE(sam_players.name, sam_bans.admin) as admin_name, COUNT(*) as ban_count')
                ->groupBy('sam_bans.admin', 'sam_players.name')
                ->orderBy('ban_count', 'desc')
                ->limit(10)
                ->get();
        } catch (\Exception $e) {
            return collect();
        }
    }

    private function getBanDurationBreakdown()
    {
        try {
            return [
                'permanent' => Ban::where('unban_date', 0)->count(),
                'temporary' => Ban::where('unban_date', '>', 0)->count(),
            ];
        } catch (\Exception $e) {
            return ['permanent' => 0, 'temporary' => 0];
        }
    }
}