<?php

namespace App\Http\Controllers\Admin;

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

use App\SystemFood;
use App\SystemPhysic;
use App\User;
use App\Reservation;
use App\TrainnerReservation;
use App\ReservationPrescription;
use App\ReservationAnatomy;
use App\DoctorReservation;
use App\CodePhysic;
use App\Answer;
use App\TrainReservation;
use App\ReservationPhyscal;

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

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

    /**
     * return data of the trainnerreservations.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $user= \Auth::user();
        $today =date("Y-m-d");   
        $query = TrainReservation::where('trainner_id',$user->id)->where('dating','>=',$today)->orderBy('dating')->orderBy('timing');

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

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

        
        if ($request->patient) {
            $query->where('patient_id', patient($request->patient));
        }
        if ($request->branch) {
            $query->where('branch_id', branch($request->branch));
        }
        if ($request->dating) {
            $query->where('dating', '=', $request->dating);
        }
        if ($request->timing) {
            $query->where('timing', '=', $request->timing);
        }
        if ($request->type) {
            $query->where('type', type($request->type));
        }


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

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

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

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param ReservationRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(ReservationRequest $request) :RedirectResponse
    {//
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  Reservation  $reservation
     * @return View
     */
    public function edit(TrainReservation $trainnerreservation): View
    {
        
        $action= route('trainnerreservations.update', $trainnerreservation->id);
        $head = metaFields('trainnerreservations', 'new', getCurrentLocale()) ?? __('trainnerreservations.new');
        $reservation = $trainnerreservation;   
        $systemphysics = SystemPhysic::cursor();
        $patient = User::find($trainnerreservation->patient_id);
        $reserved = TrainnerReservation::where('physical_reservation_id',$trainnerreservation->id)->count();
        $reservations = TrainnerReservation::where('physical_reservation_id',$trainnerreservation->id)->get();
        $allreserved = TrainnerReservation::where('physical_reservation_id',$trainnerreservation->id)->get();
        $last = TrainnerReservation::where('physical_reservation_id',$trainnerreservation->id)->where('system_physic_id','!=',NULL)->orderBy('id','DESC')->first();
        if($last){
        $physcals = ReservationPhyscal::where('reservation_id',$last->id)->get();
        $codes = CodePhysic::where('system_physcal_id',$last->system_physic_id)->get();
        }
        else{
            $physcals = null;
            $codes = null;
        }
       $reserved_ids = Reservation::where('patient_id',$trainnerreservation->patient_id)->pluck('id');
       $systemfood_ids = DoctorReservation::whereIn('doctor_reservation_id',$reserved_ids)->pluck('system_food_id');
       $systemfoods = SystemFood::find($systemfood_ids);
              

        return view( $this->viewDirectory.'form', compact('reservation', 'action', 'head','physcals','codes','systemphysics','systemfoods','allreserved','reservations','patient','reserved','last') );
    }
   

    /**
     * Update the specified resource in storage.
     *
     * @param  ReservationRequest  $request
     * @param  Reservation  $systemfood
     * @return RedirectResponse|Redirector
     */
        public function update(TrainnerReservationRequest $request, TrainReservation $trainnerreservation) :RedirectResponse
    {
        $user = \Auth::user();
          
        $reserved = TrainnerReservation::where('physical_reservation_id',$trainnerreservation->id)->count();
        $allcount =$trainnerreservation->count - 1;
         $patient_id =$trainnerreservation->patient_id;
        $dating = date('Y-m-d');
        if($allcount == $reserved  ){
            $request->merge(['expired'=>'1']);
        }
        else{
             $request->merge(['expired'=>'0']);
        }
        if(is_null($request->count)){
        $reservation_data = $request->only('dating','timing','expired','system_physic_id');
        
        }
        else{
            $reservation_data = $request->only('dating','timing','count','expired','system_physic_id');
           
        }
        
        
        if($request->type=='0'){
            $reservation_data =$request->only('dating','timing','expired');
            $trainnerreservation->update($reservation_data);
             $reservations = TrainnerReservation::create(['type'=>'0','trainner_id'=>$user->id,'physical_reservation_id'=>$trainnerreservation->id,'patinet_id'=>$patient_id,'dating'=>$dating]);
        }
        else{
             $trainnerreservation->update($reservation_data);
        $request->merge(['next_date'=>$request->dating,'next_time'=>$request->timing,'physical_reservation_id'=>$trainnerreservation->id,'trainner_id'=>$user->id]);
        $reservations_data = $request->only('system_physic_id','code_id','next_date','next_time','physical_reservation_id','trainner_id','patient_id','dating');
        $reservations = TrainnerReservation::create($reservations_data);
        
        }
        if(!is_null($request->physcal)){
           foreach($request->physcal as $row){
            
                 ReservationPhyscal::create([
                    'physcal_id'=>$row['physcal_id'],
                    'num'=>$row['num'],
                    'user_id'=>$patient_id,
                    'reservation_id'=>$reservations->id
                    ]);
    
            } 
        }
        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 = TrainReservation::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) {
            TrainReservation::onlyTrashed()->whereIn('id', $ids)->forceDelete();
        } else {
            TrainReservation::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 = TrainReservation::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 = TrainReservation::whereIn('id', $request->ids)->onlyTrashed();
        if ($user){
            $user->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
