<?php

namespace App\Http\Controllers;

use App\Models\Player;
use App\Models\Prize;
use App\Models\PrizeDistribution;
use App\Models\PrizeDistributionConfiguration;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class GameController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function index()
    {
        // if prizes are left then we redirect the user to the index page else to the game over page
        if (Prize::anyPrizeAvailable())
            return view('index');

        return redirect()->route('game-over');
    }

    public function register_player()
    {
        $player = new Player();
        $player->name = 'Random';
        $player->has_played = false;
        $player->has_played_puzzle = false;

        if ($player->save()) {
            $player->update([
                'name' => 'Random ' . $player->id
            ]);

            //return response()->json([
            //   'redirect_url' => route('player.game', $player->uuid)
            //]);

            return response()->json([
                'redirect_url' => route('player.puzzle', [$player->uuid, 1])
            ]);

        }
    }


    // Get the puzzle
    public function puzzle($uuid, $step)
    {
        // get the unique identifier from the query string and check if the player has not already played the game
        $player = Player::findByUuidOrFail($uuid);
        if ($player) {
            // we have the player information - check if the player has already played the game or not
            if (!$player->has_played_puzzle) {

                return view('puzzle-' . $step, compact('uuid', 'player'));
            } else
                return redirect()->route('home');
        } else
            return redirect()->route('home');
    }

    // submit puzzle
    public function puzzlePost($uuid)
    {
        // get the unique identifier from the query string and check if the player has not already played the game
        $player = Player::findByUuidOrFail($uuid);
        if ($player) {
            // we have the player information - check if the player has already played the game or not
            if (!$player->has_played_puzzle) {

                // store the prizes
                $player->has_played_puzzle = true;
                $player->save();

                return redirect()->route('player.game', $player->uuid);
            } else
                return redirect()->route('home');
        } else
            return redirect()->route('home');
    }


    // Get the prize that we need to give
    public function game($uuid)
    {
        // get the unique identifier from the query string and check if the player has not already played the game
        $player = Player::findByUuidOrFail($uuid);
        if ($player) {
            // we have the player information - check if the player has already played the game or not
            if (!$player->has_played) {

                // we need to find which prize we need to give to this user
                $prizeWon = Prize::findRandomPrize($uuid);

                // we encrypted the prize and store it in the session - decrypting the same in the game
                session(['gamePrize' => encrypt($prizeWon), 'freeSpin' => $prizeWon['id'] == '9' ? 1 : 0]);
                return view('game', compact('uuid', 'player'));
            } else
                return redirect()->route('home');
        } else
            return redirect()->route('home');
    }

    public function store_game_prize(Request $request)
    {
        // we need to store the prize won by this user
        // get the unique identifier and get the player details
        $player = Player::findByUuidOrFail($request->uuid);
        $isFreeSpin = session('freeSpin');

        if ($isFreeSpin) {
            // store the last prize distributed
            PrizeDistributionConfiguration::setKeyValue('LastPrizeDistributedId', $request->prize_id);
            PrizeDistributionConfiguration::setKeyValue('FreeSpinCount:' . $player->uuid, 1);

            //store for distribution
            PrizeDistribution::create([
                'prize_id' => $request->prize_id,
                'player_id' => $player->id,
                'selected_day' => config('app.selected_day'),
                'created_at' => Carbon::now()
            ]);

            return response()->json(array('success' => true, 'freeSpin' => 1));
        }

        if ($player && !$player->has_played) {
            DB::transaction(function () use ($request, $player) {

                // store the prize
                $player->has_played = true;
                $player->prize_id = $request->prize_id;
                $player->save();

                //store for distribution
                PrizeDistribution::create([
                    'prize_id' => $player->prize_id,
                    'player_id' => $player->id,
                    'selected_day' => config('app.selected_day'),
                    'created_at' => Carbon::now()
                ]);

                // update the prizes table with the count
                Prize::find($player->prize_id)->increment('total_allocated_count');

                // store the last prize distributed
                PrizeDistributionConfiguration::setKeyValue('LastPrizeDistributedId', $player->prize_id);

                // delete earlier
                PrizeDistributionConfiguration::where('key', 'FreeSpinCount:' . $player->uuid)->delete();
            });

            return response()->json(array('success' => true, 'freeSpin' => 0));
        }

        return response()->json(array('success' => false, 'message' => 'You have already participated'));
    }
}
