<?php

namespace App\Http\Controllers\Admin\Manage;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class GMController extends Controller
{
    public function index()
    {
        $gms = DB::table('auth')
            ->join('users', 'auth.userid', '=', 'users.ID')
            ->select('users.ID', 'users.name', 'users.email', DB::raw('GROUP_CONCAT(auth.rid) as permissions'))
            ->groupBy('users.ID', 'users.name', 'users.email')
            ->get();

        return Inertia::render('admin/manage/gm/index', [
            'gms' => $gms,
        ]);
    }

    public function search(Request $request)
    {
        $request->validate([
            'account_id' => 'required|numeric|min:1'
        ]);

        $user = User::find($request->account_id);
        
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found with ID: ' . $request->account_id
            ], 404);
        }

        $isGM = DB::table('auth')->where('userid', $request->account_id)->exists();

        return response()->json([
            'success' => true,
            'user' => [
                'id' => $user->ID,
                'name' => $user->name,
                'email' => $user->email,
            ],
            'is_gm' => $isGM
        ]);
    }

    public function searchByName(Request $request)
    {
        $request->validate([
            'query' => 'required|string|min:1'
        ]);

        $query = $request->input('query');

        $results = DB::table('users')
            ->where('name', 'like', '%' . $query . '%')
            ->limit(10)
            ->get(['ID', 'name', 'email'])
            ->map(function ($user) {
                return [
                    'id' => $user->ID,
                    'name' => $user->name,
                    'email' => $user->email,
                ];
            });

        return response()->json([
            'success' => true,
            'results' => $results
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'account_id' => 'required|numeric|min:1'
        ]);

        $user = User::find($request->account_id);
        
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'User not found with ID: ' . $request->account_id
            ], 404);
        }

        if (DB::table('auth')->where('userid', $request->account_id)->exists()) {
            return response()->json([
                'success' => false,
                'message' => 'User ' . $user->name . ' is already a GM'
            ], 400);
        }

        DB::statement("CALL addGM(?, 1)", [$request->account_id]);

        return response()->json([
            'success' => true,
            'message' => 'Successfully added ' . $user->name . ' as GM'
        ]);
    }

    public function edit(User $user)
    {
        $permissions = DB::table('auth')->where('userid', $user->ID)->pluck('rid')->toArray();

        $rights = [
            1 => 'System Administrator',
            2 => 'Game Master',
            3 => 'Teleport',
            4 => 'Kick Player',
            5 => 'Ban Player',
            6 => 'Mute Player',
            7 => 'View Player Info',
            8 => 'Modify Player',
            9 => 'Send Mail',
            10 => 'Broadcast',
        ];

        return response()->json([
            'user' => [
                'id' => $user->ID,
                'name' => $user->name,
                'email' => $user->email,
            ],
            'permissions' => $permissions,
            'rights' => $rights
        ]);
    }

    public function update(Request $request, User $user)
    {
        $request->validate([
            'permissions' => 'required|array'
        ]);

        foreach ($request->permissions as $rid => $enabled) {
            if ($enabled) {
                if (DB::table('auth')->where('userid', $user->ID)->where('rid', $rid)->count() === 0) {
                    DB::table('auth')->insert([
                        'userid' => $user->ID,
                        'zoneid' => 1,
                        'rid' => $rid
                    ]);
                }
            } else {
                DB::table('auth')->where('userid', $user->ID)->where('rid', $rid)->delete();
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Successfully updated permissions for ' . $user->name
        ]);
    }

    public function destroy(User $user)
    {
        DB::table('auth')->where('userid', $user->ID)->delete();

        return response()->json([
            'success' => true,
            'message' => 'Successfully removed ' . $user->name . ' from GM'
        ]);
    }
}
