<?php

namespace App\Http\Controllers;

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

use Illuminate\Support\Facades\View;

use Illuminate\Http\Request;

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

    public function getClubGroupData($club_id) {
        $total_players = DB::table('players')->where('rating', '<>', '')->count();

        //TODO: Turn this into a stored procedure so it isnt so messy and ugly
        $club_groups = DB::table('club_groups')->where('club_id', $club_id)->get();

        $groups = collect([]);

        foreach ($club_groups as $group) {
            $group->players = collect([]);

            $group_members = DB::select('CALL GetPlayersWithGroup (?,?)', [$club_id, $group->group_id]);

            foreach ($group_members as $member) {
                $player = DB::table('players')
                    ->select('player_id', 'first_name', 'last_name', 'rating')
                    ->where('player_id', $member->player_id)
                    ->first();

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

                $group->players->push($player);
            }

            $groups->push($group);
        }

        //Definitely a better way to optimize this, like using the player list below then finding groups for each player rather than searching group membership table
        $no_group_players = collect(DB::select('CALL GetPlayersWithoutGroup (?)', [$club_id]));

        if (!$no_group_players->isEmpty()) {
            foreach ($no_group_players as $player) {
                $player->percentile = Helpers::findPercentile($player, $total_players);
            }

            $no_group = collect([]);
            $no_group->group_name = "No Group";
            $no_group->group_desc = "Players in club but not assigned to a group";
            $no_group->players = $no_group_players;
            $groups->push($no_group);
        }

        error_log($groups);
        return $groups;
    }

    /* Previously used function, not in use anymore */
    public function getClubPlayerData($club_id) {
        $player_ids = DB::table('club_membership')
            ->where('club_id', $club_id)
            ->pluck('player_id');

        $total_players = DB::table('players')
           ->where('rating', '<>', '')
           ->count();

        $index = 0;

        $players = collect([]);

        foreach ($player_ids as $player_id) {
            $player = DB::table('players')
                ->select('player_id', 'first_name', 'last_name', 'rating')
                ->where('player_id', $player_id)
                ->first();

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

            $group = DB::table('club_membership')
                ->where('club_id', $club_id)
                ->where('player_id', $player_id)
                ->first();

            $players->push($player);
        }

        $this->getClubGroupData($club_id);

        return $players;
    }

    public function sendDataToView($club_id) {
        $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::Table('users')
                ->where('id', $id)
                ->value('email');

            $player_id = DB::Table('players')
                ->where('email', $player_email)
                ->value('player_id');

            $owner_id = DB::table('players')
                ->where('player_id', '=', $player_id)
                ->pluck('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);
        }

        // The rest of this function generates all data needed to show on the club page,
        // starting with club info such as club name and club id, then player data.
        // If no club id was given, we default to first created club attached to account.
        // Later we can have last viewed club id saved and show that one by default
        if ($club_id == null) {
            $club_info = $owner_clubs->first();
        } else {  //Else we server club info for club id they requested
            //Restric club information retrieved to that belonging to the owner.
            if ($user->hasRole('player')) {
                $club_info = DB::table('clubs')
                    ->where([['club_id','=', $club_id],['owner_id','=', $owner_id]])
                    ->first();
            } else{
                $club_info = DB::table('clubs')
                    ->where([['club_id','=', $club_id],['owner_id','=', $id]])
                    ->first();
            }
            //Abort when user tries to access a club not belonging to the onwer.
            if ($club_info == null) {
                abort(401);
            }
        }

        $club_id = $club_info->club_id;

        $group_data = $this->getClubGroupData($club_id);
        //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.
        $notifications = DB::table('stats_test')
            ->select('player_id','full_name', 'notification')
            ->where('club_id','=', $club_id)
            ->whereNotNull('notification')
            ->get();//get players and notifications for club

        return view('admin.clubdashboard')
            ->with('club_info', json_decode(json_encode($club_info), true))
            ->with('club_groups', $group_data)
            ->with('owner_clubs', $owner_clubs)
            ->with('notifications', $notifications);
    }

    public function search (Request $request) {
        $search = $request->get('search');

        $id = Auth::id();

        $owner_clubs = Helpers::findClubsByOwnerId(Auth::id());

        //Currently we are identifying the first found Club for the owner, and searching based on that club. Unsure how to address searching
        //when a user changes Club.
        $club_info = DB::table('clubs')
            ->where('owner_id', $id)
            ->first();

        $club_id = $club_info->club_id;

        //list of player(s) that match the search input and belong to the owners' club, found by joining and querying into the ClubMembership table
        $players = DB::table('players')
            ->join('club_membership', 'player.player_id', '=', 'club_membership.player_id')
            ->select('club_membership.club_id', 'player.player_id','player.first_name', 'player.last_name','player.rating',)
            ->where([
                ['club_membership.club_id', '=', $club_id],
                ['first_name', 'like', '%'.$search.'%']
            ])
            ->orWhere([
                ['club_membership.club_id', '=', $club_id],
                ['last_name', 'like', '%'.$search.'%']
            ])
            ->orWhere([
                ['club_membership.club_id', '=', $club_id],
                ['player.player_id', 'like', '%'.$search.'%']
            ])
            ->paginate(10);

        $notifications = DB::table('stats_test')
            ->select('player_id','full_name', 'notification')
            ->where('club_id','=', $club_id)
            ->whereNotNull('notification')
            ->get();//get players and notifications for club

        return view('admin.club_players', ['players' => $players])
            ->with('owner_clubs', $owner_clubs)
            ->with('notifications', $notifications);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\View\View
     */
    public function index($clubid = null) {
        return $this->sendDataToView($clubid);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\View\View
     */
    public function noparam() {
        return $this->sendDataToView(null);
    }
}
