<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\DoctorRequest;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Routing\Redirector;
use Illuminate\View\View;
use App\BranchUser;
use App\UserDescription;
use App\User;
use App\Doctor;
use App\Branch;
use App\Specialty;
use App\DoctorReservation;
use App\DoctorExperience;
use App\DoctorImage;
use App\DoctorLanguage;

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

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

    /**
     * return data of the doctors.
     *
     * @param Request $request
     * @return View
     */
    public function grid(Request $request) :View
    {
        
        $query = User::where('role_id','4')->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();
        }

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('doctors.store');
        $head = metaFields('doctors', 'add_new', getCurrentLocale()) ?? __('doctors.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 DoctorRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(DoctorRequest $request) :RedirectResponse
    {
      
        $request->merge(['password'=>bcrypt($request->password)]);
        $request->merge(['role_id'=>'4']);
        
        $doctor= User::create($request->only('name','email','password','role_id','photo'));
         $request->merge(['user_id' => $doctor->id]);
       
        $data = $request->except(['branches','name','email','password','role_id','photo']);
       
        $details = UserDescription::create($data);
       $doctor->branches()->attach($request->branches);
       $this->saveData( $request, $doctor->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  User  $doctor
     * @return View
     */
    public function edit(User $doctor): View
    {
       
        $action= route('doctors.update', $doctor->id);
        $head = metaFields('doctors', 'edit', getCurrentLocale()) ?? __('doctors.edit');
        $specialties = Specialty::all();
        $branches = Branch::all();
        $allreservations= DoctorReservation::where('doctor_id',$doctor->id)->count();
        
        
        $difDays = date('d');
        $difMonths = date('n');
        $difDays = 30 - $difDays . ' day';
        $difMonths = 12 - $difMonths . ' month';

        $lastYear = date("Y-m-d", strtotime("-1 year $difMonths $difDays"));
        $nextYear = date("Y-m-d", strtotime("0 year $difMonths $difDays"));

        
        $toDay = date("Y-m-d");
        $days = [];


        $websiteVisitors = DB::table('doctor_reservation_details')
            ->where('doctor_id',$doctor->id)
            ->orderBy('dating', 'asc')
            ->whereBetween('dating', [$lastYear, $nextYear])
            ->pluck('dating')->toArray();

        

        foreach ($websiteVisitors as $key => $websiteVisitor) {
            $websiteVisitors[$key] = date('n', strtotime($websiteVisitor));
            $days[] = date('Y-m-d', strtotime($websiteVisitor));
        }
        
        $monthVisitCounts = array_count_values($websiteVisitors);
        
        
        
        return view( $this->viewDirectory.'form', compact('doctor', 'action', 'head','specialties','branches','allreservations','monthVisitCounts') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  DoctorRequest  $request
     * @param  User  $systemfood
     * @return RedirectResponse|Redirector
     */
        public function update(DoctorRequest $request, User $doctor) :RedirectResponse
    {
      $request->merge(['role_id'=>'4']);
        if(!is_null($request->password)){
        $request->merge(['password'=>bcrypt($request->password)]);
        $doctor->update($request->only('name','email','password','role_id','joinned','photo'));
        }
        else{
        $doctor->update($request->only('name','email','role_id','photo'));
        }
        
        
         $request->merge(['user_id' => $doctor->id]);
       $old = UserDescription::where('user_id',$doctor->id)->forceDelete();
        $data = $request->except(['branches','name','email','password','role_id']);
       
        $details = UserDescription::create($data);
       $doctor->branches()->sync($request->branches);
       DoctorExperience::where('user_id',$doctor->id)->delete();
       DoctorImage::where('user_id',$doctor->id)->delete();
       DoctorLanguage::where('user_id',$doctor->id)->delete();
$this->saveData( $request, $doctor->id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }
     private function saveData(DoctorRequest $request, int $doctor_id ) :void
     {
        if($request->langs){
            foreach($request->langs as $row){
               DoctorLanguage::create([
                    'user_id'=>$doctor_id,
                    'language'=>$row['lang']
                    ]);
            }
            
        }
        if($request->images){
            foreach($request->images as $row){
               DoctorImage::create([
                    'user_id'=>$doctor_id,
                    'image'=>$row
                    ]);
            }
            
        }
        if($request->experiences){
            foreach($request->experiences as $row){
               DoctorExperience::create([
                    'user_id'=>$doctor_id,
                    'name'=>$row['name'],
                    'description'=>$row['description']
                    ]);
            }
            
        }
     }
    /**
     * 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')]);
        }
    }
}
