<?php

namespace App\Http\Controllers;

use App\User;
use App\Http\Requests\UserRequest;
use Illuminate\Support\Facades\Hash;

use Auth;
use DB;
use App\Http\Helpers;

class UserController extends Controller {
    /**
     * Display a listing of the users
     *
     * @param  \App\User  $model
     * @return \Illuminate\View\View
     */
    public function index(User $model) {
        $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 players WHERE email= '$player_email';"));

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

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

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

            $id = $owner_id;
        }

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

        $club_info = DB::table('clubs')
            ->where('owner_id', $id)
            ->first();

        $club_id = $club_info->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();

        //The following holds relevant information from various DB tables in order to form a collection of data to be used for the club list/leaderboard page. route: /user.
        $clubs = DB::table('session_data')
            ->select('session_data_id', 'session_id', 'hits', 'misses', 'accuracy', 'games.game_id', 'session_data.player_id', 'players.first_name', 'players.last_name', 'clubs.club_id', 'clubs.owner_id', 'clubs.club_name', 'game_type', 'mode', 'time', 'delay_time', 'num_of_pads', 'type', 'station_id')
            ->leftJoin('games','session_data.game_id','=', 'games.game_id')
            ->leftJoin('club_membership', 'session_data.player_id', '=', 'club_membership.player_id')
            ->leftJoin('clubs', 'clubs.club_id' ,'=', 'club_membership.club_id')
            ->leftJoin('players', 'players.player_id' ,'=', 'club_membership.player_id')
            ->paginate(12);

        return view('users.index', ['clubs' => $clubs])
            ->with('owner_clubs', $owner_clubs)
            ->with('notifications', $notifications);
    }
}
