<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\DoctorReservationRequest;
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\History;
use App\User;
use App\Reservation;
use App\DoctorReservation;
use App\PhyscalNeed;
use App\ReservationPrescription;
use App\Ultrasound;
use App\ReservationAnatomy;
use App\Code;
use App\ReservationMeal;
use App\Answer;
use App\TrainReservation;
use App\NotificationAbsence;
use App\Notification;

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

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

    /**
     * return data of the doctorreservations.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        $user= \Auth::user();
        $today =date("Y-m-d"); 
        $query = Reservation::where('doctor_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();
        }

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('doctorreservations.store');
        $head = metaFields('doctorreservations', 'add_new', getCurrentLocale()) ?? __('doctorreservations.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(Reservation $doctorreservation): View
    {
        
        $action= route('doctorreservations.update', $doctorreservation->id);
        $head = metaFields('doctorreservations', 'new', getCurrentLocale()) ?? __('doctorreservations.new');
        $reservation = $doctorreservation;   
        $systemfoods = SystemFood::cursor();
        
        $systemphysics = SystemPhysic::cursor();
        $patient = User::find($doctorreservation->patient_id);
        $histories = History::where('user_id',$doctorreservation->patient_id)->get();
        $reserved = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->count();
        $reservations = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->get();
       
        $last = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->where('system_food_id','!=',NULL)->orderBy('id','DESC')->first();
        if($last){
        $meal = ReservationMeal::where('reservation_id',$last->id)->first();
        $codes = Code::where('system_food_id',$last->system_food_id)->get();
        }
        else{
            $meal = null;
            $codes = null;
        }
        
        $code = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->where('code_id','!=',NULL)->orderBy('id','DESC')->first();

      

        return view( $this->viewDirectory.'form', compact('reservation','meal','action','codes', 'head','systemfoods','reservations','systemphysics','patient','reserved','last','code','histories') );
    }
    public function prescriptionshow($id){
         $head = metaFields('doctorreservations', 'prescriptionsshow', getCurrentLocale()) ?? __('doctorreservations.prescriptionsshow');
        $reserved = DoctorReservation::where('doctor_reservation_id',$id)->pluck('id'); 
        $prescriptions = ReservationPrescription::whereIn('doctor_reservation_details_id',$reserved)->get();
        
         return view( $this->viewDirectory.'prescriptionshow', compact('prescriptions','head') );
    }
    public function anatomyshow($id){
       
        $head = metaFields('doctorreservations', 'anatomyshow', getCurrentLocale()) ?? __('doctorreservations.anatomyshow');
        $reserved = DoctorReservation::where('doctor_reservation_id',$id)->pluck('id'); 
        
        $anatomies = ReservationAnatomy::whereIn('doctor_reservation_details_id',$reserved)->get();
        
         return view( $this->viewDirectory.'anatomyshow', compact('anatomies','head') );
  
    }
    public function ultrasoundshow($id){
       
        $head = 'ultrasound';
        $reserved = DoctorReservation::where('doctor_reservation_id',$id)->pluck('id'); 
        
        $ultrasounds = Ultrasound::whereIn('reservation_id',$reserved)->get();
        
         return view( $this->viewDirectory.'ultrasoundshow', compact('ultrasounds','head') );
  
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  ReservationRequest  $request
     * @param  Reservation  $systemfood
     * @return RedirectResponse|Redirector
     */
        public function update(DoctorReservationRequest $request, Reservation $doctorreservation) :RedirectResponse
    {
        $user = \Auth::user();
         
        $reserved = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->count();
        
        
        
    
        if(is_null($request->count)){
        $reservation_data = $request->only('dating','timing','expired');
        
        }
        else{
            $reservation_data = $request->only('dating','timing','count','expired');
           
        }
        
        $doctorreservation->update($reservation_data);
        $patient_id =$doctorreservation->patient_id;
        $dating = date('Y-m-d');
        if($request->type=='0'){
             $type=0;
             $last = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->orderBy('id','DESC')->first();
            if($last){
               
                if($last->type == 0){
                   $type=1;
                   $doctorreservation->update(['expired'=>'1']);
                }
            }
             $reservations = DoctorReservation::create(['patient_id'=>$doctorreservation->patient_id ,'type'=>'0','next_date'=>$request->dating,'next_time'=>$request->timing,'physcal'=>$last->physcal,'code_id'=>$last->code_id,'calorie_id'=>$last->calorie_id,'category_id'=>$last->category_id,'doctor_id'=>\Auth::user()->id,'doctor_reservation_id'=>$doctorreservation->id]);
             $data = 'قام'.$reservations->reservation->patient->name.'بالغياب عن الجلسة';
                Notification::create(['title'=>'غياب','description'=>$data]);
        }
        else{
            $alllast = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->where('physcal','1')->orderBy('id','DESC')->get();
            if(count($alllast) == 0){
                PhyscalNeed::create(['patient_id'=>$doctorreservation->patient_id]);
            }
        $request->merge(['next_date'=>$request->dating,'next_time'=>$request->timing,'doctor_reservation_id'=>$doctorreservation->id,'doctor_id'=>$user->id,'doctor_id'=>\Auth::user()->id]);
        if(isset($request->code_id)){
        $reservations_data = $request->only('system_food_id','doctor_id','category_id','calorie_id','physcal','next_date','code_id','next_time','doctor_reservation_id','doctor_id','patient_id','dating');
        }
        else{
            
            $last = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->orderBy('id','DESC')->first();
            $request->merge(['patient_id'=>$doctorreservation->patient_id ,'calorie_id'=>$last->calorie_id,'category_id'=>$last->category_id,'code_id'=>$last->code_id,'system_food_id'=>$last->system_food_id,'doctor_reservation_id'=>$doctorreservation->id,'doctor_id'=>\Auth::user()->id]);
            $reservations_data = $request->only('physcal','doctor_id','next_date','next_time','doctor_reservation_id','doctor_id','calorie_id','category_id','code_id','system_food_id','patient_id','dating');
        }
        $reservations = DoctorReservation::create($reservations_data);
        if(!is_null($request->system_food_id)){
          
            
                 ReservationMeal::create([
                    
                    'description'=>$request->description,
                    'reservation_id'=>$reservations->id
                    ]);
    
            
        }
        $data = 'قام'.$reservations->reservation->patient->name.'بحضور  الجلسة';
                Notification::create(['title'=>'حضور','description'=>$data]);
        if(!is_null($request->anatomy)){
           foreach($request->anatomy as $row){
            
                 if(!is_null($row['description'])){$description=$row['description'];}else{$description=NULL;}
                 if(!is_null($row['cost'])){$cost=$row['cost'];}else{$cost=NULL;}
                 if(!is_null($row['anatomy_id'])){$type=$row['anatomy_id'];}else{$type=NULL;}
                $data = ReservationAnatomy::create([
                    'description'=>$description,
                    'cost'=>$cost,
                    'anatomy_id'=>$type,
                    'doctor_reservation_details_id'=>$reservations->id,
                    'user_id'=>$patient_id
                    ]);
                      if ($row->hasFile('image_anatomy')) {
        $img=$request->file('image_anatomy');
        $name=mt_rand(1000000, 9999999).time().'img-'.$img->getClientOriginalExtension();
        $img->move(public_path('/uploads/images/'),$name);
        $data->image=$name;
        $data->save();
}
            } 
        }
        if(!is_null($request->prescription)){
              foreach($request->prescription as $row){
                 if(!is_null($row['name'])){$name=$row['name'];}else{$name=NULL;}
                 if(!is_null($row['count'])){$count=$row['count'];}else{$count=NULL;}
                 if(!is_null($row['duration'])){$duration=$row['duration'];}else{$duration=NULL;}
                 ReservationPrescription::create([
                    'name'=>$name,
                    'count'=>$count,
                    'duration'=>$duration,
                    'doctor_reservation_details_id'=>$reservations->id
                    ]);
            }
            
            
        }
        
        
        if(!is_null($request->ultra)){
              foreach($request->ultra as $key=>$row){
                 if(!is_null($row['description'])){$name=$row['description'];}else{$name=NULL;}
                  $data= Ultrasound::create([
                    'description'=>$name,
                    'reservation_id'=>$reservations->id
                    ]);
                    if ($request->hasFile('image_ultra')) {
                        if($request->file('image_ultra')[$key]){
        $img=$request->file('image_ultra')[$key];
        $name=mt_rand(1000000, 9999999).time().'img-'.$img->getClientOriginalExtension();
        $img->move(public_path('/uploads/images/'),$name);
        $data->image=$name;
        $data->save();
                        }
}
            }
            
            
        }
        }
        if($doctorreservation->expired == '0'){
         $reserved = DoctorReservation::where('doctor_reservation_id',$doctorreservation->id)->count();
        if(($doctorreservation->count+1) == $reserved  ){
            $request->merge(['expired'=>'1']);
        }
        else{
             $request->merge(['expired'=>'0']);
        }
        $doctorreservation->update(['expired'=>$request->expired]);
        }
        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 = Reservation::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) {
            Reservation::onlyTrashed()->whereIn('id', $ids)->where('role', '!=', 'admin')->forceDelete();
        } else {
            Reservation::whereIn('id', $ids)->where('role', '!=', 'admin')->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 = Reservation::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 = Reservation::whereIn('id', $request->ids)->onlyTrashed();
        if ($user){
            $user->restore();
            return response()->json(['message'=> __('dashboard.saveDone')]);
        }
    }
}
