<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Collection;
use App\Http\Helpers;

class PlayerController extends Controller {
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct() {
        $this->middleware('role:admin|player');
    }

    /**
     * Show the application dashboard of the
     *
     * @return \Illuminate\View\View
     */
    public function index($playerid = null) {
        $user = Auth::user();
        $id = Auth::id();

        if($user->hasRole('player')){
            //Retrive owner id from url when logged in as player(need to change for when the player belongs to many clubs, etc.)
            $player_email = DB::select(DB::raw("SELECT email FROM Users WHERE id= '$id';"));

            $player_email = $player_email[0]->email;

            $player_id = DB::select(DB::raw("SELECT player_id FROM Player WHERE email= '$player_email';"));

            $player_id = $player_id[0]->player_id;

            $owner_id = DB::select(DB::raw("SELECT owner_id FROM Player WHERE player_id= '$player_id';"));

            //This is an inefficient way to retrieve the owner_id when logged in as player. Probably better ways to do this.
            $owner_id = $owner_id[0]->owner_id;

            $owner_clubs = Helpers::findClubsByOwnerId($owner_id);
        } else {
            //list of clubs the user has created, used in nav bar item
            $owner_clubs = Helpers::findClubsByOwnerId($id);
        }

        $id = -1;

        if (!empty($playerid)) {
            $id = $playerid;
        } else {
            $id = Auth::id();
        }

        $player_info = DB::select(DB::raw("SELECT TOP 1 first_name, last_name, rating FROM Player WHERE player_id= '$id';"));

        if ($player_info == null) {
            abort(404);
        }

        $player_info = $player_info[0];

        $all_player_games = collect(DB::select(DB::raw("SELECT * FROM (SELECT * FROM dbo.SessionData WHERE player_id = '$id') AS SessionData INNER JOIN dbo.Game ON SessionData.game_id = dbo.Game.game_id;")));

        $all_session_info = DB::select(DB::raw("SELECT * FROM (SELECT DISTINCT session_id FROM dbo.SessionData WHERE player_id = '$id') AS SessionData INNER JOIN dbo.Session ON SessionData.session_id = dbo.Session.session_id;"));

        $session_ids = collect($all_session_info)
            ->pluck('session_id');

        $data = collect([]);

        foreach ($all_session_info as $session_info) {
            $session_bundle = collect([]);

            $session_bundle->put('info', $session_info);

            $temp_games = json_decode($all_player_games->where('session_id', $session_info->session_id));

            $games = collect([]);

            foreach ($temp_games as $game) {
                $games->add($game);
            }

            $session_bundle->put('games', $games);

            $data->push($session_bundle);
        }

        error_log($data);

        $query = 'SELECT COUNT(player_id) AS total FROM Player WHERE rating <> \'\'';

        $total_players = DB::select($query);

        $total_players = $total_players[0]->total;

        $club_id = DB::select("SELECT club_id FROM ClubMembership WHERE player_id = '$id';");

        $club_id = $club_id[0]->club_id;

        $club_name = DB::select("SELECT club_name FROM Club WHERE club_id = '$club_id';");

        $club_name = $club_name[0]->club_name;

        $player_info->percentile = Helpers::findPercentile($player_info, $total_players);

        $player_info->club_id = $club_id;

        $player_info->club_name = $club_name;

        //Notifications are currently retrieved from a Test DB Table. These notifications currently hold no true value as the computed statistics are wrongly computed. Needs to be looked into.
        // get players and notifications for club
        $notifications = DB::table('StatsTest')
            ->select('player_id','full_name', 'notification')
            ->where('club_id','=', $club_id)
            ->whereNotNull('notification')
            ->get();

        return view('dashboard')
        ->with('data', json_decode($data, true))
        ->with('player_info', json_decode(json_encode($player_info), true))
        ->with('owner_clubs', $owner_clubs)
        ->with('notifications', $notifications);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\View\View
     */
    public function noparam() {
        // in this situation we should return the data of the logged in account. must check they are a player and not an owner first
        // probably doesnt work rn, need to put above method in its own function and call it from both of these functions with dif playerid
        $id = Auth::id();

        $name = DB::table('Player')
            ->select('first_name', 'last_name', 'rating')
            ->where('player_id', $id)
            ->first();

        $data = DB::table('SessionData')
            ->where('player_id', $id)
            ->get();

        return view('dashboard')
            ->with('data', compact($data))
            ->with('name', json_decode(json_encode($name), true));
    }
}
