<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\TrainnerRequest;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;

use App\User;
use App\BranchUser;
use App\UserDescription;
use App\Trainner;
use App\Branch;
use App\Specialty;

class TrainnerController extends Controller
{
    /** Redirect to this path after each operation success*/
    private $redirectSuccessPath= '/admin/trainners';
    /** View folder */
    private $viewDirectory= 'admin.trainners.';

    /**
     * Display a listing of the resource.
     * @param Request $request
     * @return View
     */
    public function index(Request $request) :View
    {
        $title= __('trainners.head');
        $request= $request->toArray();
        return view($this->viewDirectory.'index',compact('title'));
    }

    /**
     * return data of the trainners.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $query = User::where('role_id','5')->orderBy('id', 'DESC');

        if ($request->date_from) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }

        if ($request->date_to) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        if ($request->name) {
            $query->where('name', 'LIKE', '%'.$request->name.'%');
        }


        if ( !is_null($request->status) && $request->status == 0) {
            $query->onlyTrashed();
        }

        $trainners= $query->paginate(100);

        return view($this->viewDirectory.'grid',compact('trainners'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('trainners.store');
        $head = metaFields('trainners', 'add_new', getCurrentLocale()) ?? __('trainners.new');
        $specialties = Specialty::all();
        
        $branches = Branch::all();
       

        return view( $this->viewDirectory.'form', compact('action', 'head','specialties','branches') );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param TrainnerRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(TrainnerRequest $request) :RedirectResponse
    {
     
        $request->merge(['password'=>bcrypt($request->password)]);
        $request->merge(['role_id'=>'5']);
        
        $trainner= User::create($request->only('name','email','password','role_id'));
         $request->merge(['user_id' => $trainner->id]);
       
        $data = $request->except(['branches','name','email','password','role_id']);
       
        $details = UserDescription::create($data);
       $trainner->branches()->attach($request->branches);
       
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  User  $trainner
     * @return View
     */
    public function edit(User $trainner): View
    {
        $action= route('trainners.update', $trainner->id);
        $head = metaFields('trainners', 'edit', getCurrentLocale()) ?? __('trainners.edit');
        $specialties = Specialty::all();
        
        $branches = Branch::all();


        return view( $this->viewDirectory.'form', compact('trainner', 'action', 'head','specialties','branches') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  TrainnerRequest  $request
     * @param  User  $systemfood
     * @return RedirectResponse|Redirector
     */
        public function update(TrainnerRequest $request, User $trainner) :RedirectResponse
    {
      
       $request->merge(['role_id'=>'5']);
        if(!is_null($request->password)){
        $request->merge(['password'=>bcrypt($request->password)]);
        $trainner->update($request->only('name','email','password','role_id'));
        }
        else{
        $trainner->update($request->only('name','email','role_id'));
        }
        
        
         $request->merge(['user_id' => $trainner->id]);
       $old = UserDescription::where('user_id',$trainner->id)->forceDelete();
        $data = $request->except(['branches','name','email','password','role_id']);
       
        $details = UserDescription::create($data);
       $trainner->branches()->sync($request->branches);

        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     * @throws Exception
     */
    public function destroy(Request $request, int $id) :JsonResponse
    {
        $user = User::withTrashed()->find($id);
        if ($user) {
            if ($user->deleted_at) {
                $user->forceDelete();
            } else {
                $user->delete();
            }
            return response()->json(['message'=> __('dashboard.deletedDone')]);
        } else{
            return response()->json(['message'=> __('dashboard.noResult')], 400);
        }
    }

    /**
     * Remove several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function destroyAll(Request $request) :JsonResponse
    {
        $ids= $request->ids;
        if ($request->force) {
            User::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            User::whereIn('id', $ids)->delete();
        }

        return response()->json(['message'=> __('dashboard.deletedDone')]);
    }

    /**
     * Restore the specified category from storage
     *
     * @param Request $request
     * @param int $id
     * @return JsonResponse
     */
    public function restore(Request $request, int $id) :JsonResponse
    {
        $user = User::withTrashed()->find($id);

        if ($user){
            $user->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
        return response()->json(['message'=> __('dashboard.noResult')], 400);
    }

    /**
     * Restore several pages by IDs.
     *
     * @param Request $request
     * @return JsonResponse
     */
    public function restoreAll(Request $request) :JsonResponse
    {
        $user = User::whereIn('id', $request->ids)->onlyTrashed();
        if ($user){
            $user->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
