<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Team;
use App\Models\Champion;
use Storage;

class PanelController extends Controller
{
    public function teams()
    {
        return view('panel.enter-teams');
    }

    public function createLink(Request $request)
    {
        $blueName = $request->blue ?? 'Blue';
        $redName = $request->red ?? 'Red';
        $type = $request->type;

        $data = [
            'blueTeam' => $this->randomString(),
            'redTeam' => $this->randomString()
        ];

        $roomId = $this->randomString();
        $password = $this->randomString();

        Team::create([
            'room_id'   => $roomId,
            'password'  => $password,
            'blue_name' => $blueName,
            'red_name'  => $redName,
            'blue_team' => $data['blueTeam'],
            'red_team'  => $data['redTeam'],
            'type'      => $type
        ]);

        return redirect()->route('links', [$roomId, $password, $data['blueTeam'], $data['redTeam']]);
    }

    public function links($roomId, $password, $blueTeam, $redTeam)
    {
        $data = [
            'room_id' => $roomId,
            'password' => $password,
            'blue_team' => $blueTeam,
            'red_team' => $redTeam
        ];

        $team = Team::where($data)->first();
        if (!$team) {
            abort(404);
        }

        return view('panel.link', compact('team'));
    }

    public function randomString($number = 8)
    {
        return \Str::random(8);
    }

    public function gamePlayers($roomId, $teamToken=null)
    {
        $team = Team::where('room_id', $roomId)->first();
        if (!$team) {
            abort(404);
        }
        $champions = Champion::orderBy('image', 'asc')->get();

        return view('panel.select-player', compact('team', 'champions'));
    }

    public function champions(Request $request)
    {
        $champions = new Champion;
        if ($request->name) {
            $champions = $champions->where('name', 'like', '%'.$request->name.'%');
        }
        $champions = $champions->get();

        $championsHtml = view('panel.champions', compact('champions'))->render();

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

    public function updateResult(Request $request, $id)
    {
        $arr = [
            "room_id" => $id,
            "blue_team_status" => $request->blue_button_type ?? NULL,
            "red_team_status" => $request->red_button_type ?? NULL,
            "blue_team_time" => in_array($request->blue_button_type, ['lock']) ? now() : NULL,
            "red_team_time" => in_array($request->red_button_type, ['lock']) ? now() : NULL,
            "blue_team" => [
                "champion_1" => $request->champion1 ?? NULL,
                "champion_3" => $request->champion3 ?? NULL,
                "champion_5" => $request->champion5 ?? NULL,
                "champion_7" => $request->champion7 ?? NULL,
                "champion_10" => $request->champion10 ?? NULL,
                "champion_11" => $request->champion11 ?? NULL,
                "champion_13" => $request->champion13 ?? NULL,
                "champion_15" => $request->champion15 ?? NULL,
                "champion_17" => $request->champion17 ?? NULL,
                "champion_19" => $request->champion19 ?? NULL,
            ],
            "red_team" => [
                "champion_2" => $request->champion2 ?? NULL,
                "champion_4" => $request->champion4 ?? NULL,
                "champion_6" => $request->champion6 ?? NULL,
                "champion_8" => $request->champion8 ?? NULL,
                "champion_9" => $request->champion9 ?? NULL,
                "champion_12" => $request->champion12 ?? NULL,
                "champion_14" => $request->champion14 ?? NULL,
                "champion_16" => $request->champion16 ?? NULL,
                "champion_18" => $request->champion18 ?? NULL,
                "champion_20" => $request->champion20 ?? NULL,
            ]
        ];

        Team::where('room_id', $id)->update(['data' => json_encode($arr)]);

        return true;
    }

    public function export($id)
    {
        $team = Team::where('room_id', $id)->first();
        if ($team) {
            $data = $team->data;

            $filename = "result.json";
            Storage::put($filename, json_encode($data, JSON_PRETTY_PRINT));

            $headers = array('Content-type' => 'application/json');

            return Storage::download($filename, 'result.json', $headers);
        } else {
            abort(404);
        }
    }

    public function updateSetting(Request $request, $id)
    {
        $teamType = $request->teamType;
        if ($request->type == 'sound') {
            $data = [$teamType.'_sound' => $request->newVal == 'On' ? 0 : 1];
        } else {
            $data = [$teamType.'_size' => $request->newVal == 'Small' ? 'Large' : 'Small'];
        }

        Team::where('room_id', $id)->update($data);
        return true;
    }

    public function import(Request $request, $id)
    {
        if ($request->hasFile('file')) {
            $file = $request->file('file');
            $reportJson = file_get_contents($file->getPathname());

            $report = json_decode(json_decode($reportJson, true), true);
            $teamType = $request->teamType;
            $arrayValues = array_values($report[$teamType.'_team']);
            $team = Team::where('room_id', $id)->update([
                $teamType.'_import' => $arrayValues
            ]);

            if (json_last_error() !== JSON_ERROR_NONE) {
                return response()->json(['success' => false, 'message' => 'Invalid JSON format']);
            }

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

        return response()->json(['success' => false, 'message' => 'No file uploaded']);
    }

    public function cancel($roomId)
    {
        $team = Team::where('room_id', $roomId)->update(['data' => NULL]);

        return true;
    }

    public function banPlayer(Request $request, $roomId)
    {
        $team = Team::where('room_id', $roomId)->update([
            $request->team.'_ban' => $request->value
        ]);

        return true;
    }
}
