<?php

namespace App\Http\Controllers;

use App\Http\Requests\ClubRequest;
use Illuminate\Support\Facades\Hash;
use App\Http\Requests\ProfileRequest;
use App\Http\Requests\PasswordRequest;

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


class ProfileController extends Controller {
    /**
     * Show the form for editing the profile.
     *
     * @return \Illuminate\View\View
     */
    public function edit() {
        $user = Auth::user();

        $id = Auth::id();

        if($user->hasRole('admin')){
            //Needs to be modified for when a user switches between owned clubs. Currently getting first match.
            $club_info = DB::table('clubs')->where('owner_id', $id)->first();

            $club_id = $club_info->club_id;

            $owner_clubs = Helpers::findClubsByOwnerId(Auth::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();

            return view('profile.edit')
                ->with('club_info', json_decode(json_encode($club_info), true))
                ->with('owner_clubs', $owner_clubs)
                ->with('user', $user)
                ->with('notifications', $notifications);

        } else {
            return view('profile.edit');
        }

    }

    /**
     * Update the profile
     *
     * @param  \App\Http\Requests\ProfileRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(ProfileRequest $request) {
        auth()
            ->user()
            ->update($request->all());

        return back()
            ->withProfileStatus(__('Profile successfully updated.'));
    }

    /**
     * Update the profile
     *
     * @param  \App\Http\Requests\ClubRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function club(ClubRequest $request) {
        $clubUpdate = [
            auth()
                ->user()
                ->id,
            $request['club_name'],
            'Update'
        ];

        DB::update('CALL AssignClub (?,?,?)', $clubUpdate);

        return back()
            ->withClubStatus(__('Club successfully changed.'));
    }

    /**
     * Change the password
     *
     * @param  \App\Http\Requests\PasswordRequest  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function password(PasswordRequest $request) {
        auth()
            ->user()
            ->update(['password' => Hash::make($request->get('password'))]);

        return back()
            ->withPasswordStatus(__('Password successfully updated.'));
    }
}
