<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\AnatomyRequest;
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\ReservationAnatomy;
use App\SystemPhysic;
use App\Anatomy;
use App\Category;
use App\Physical;

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

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

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


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

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return View
     */
    public function create() :View
    {
        $action= route('anatomies.store');
        $head = metaFields('anatomies', 'add_new', getCurrentLocale()) ?? __('anatomies.new');
        $users = User::where('role_id','6')->get();
       

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

    /**
     * Store a newly created resource in storage.
     *
     * @param AnatomyRequest $request
     * @return RedirectResponse|Redirector
     */
    public function store(AnatomyRequest $request) :RedirectResponse
    {
     
        $this->saveData( $request, $request->user_id );
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  Code  $codephyscal
     * @return View
     */
    public function edit(User $anatomy): View
    {
        $action= route('anatomies.update', $anatomy->id);
        $head = metaFields('anatomies', 'edit', getCurrentLocale()) ?? __('anatomies.edit');
        $anatomies = ReservationAnatomy::where('user_id',$anatomy->id)->get();
        $users = User::cursor();
        $categories = Category::cursor();
        $anatomycats =   Anatomy::all();
        
        

        return view( $this->viewDirectory.'form', compact('anatomies','anatomycats','anatomy','action', 'head','users','categories') );
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  AnatomyRequest  $request
     * @param  Code  $systemfood
     * @return RedirectResponse|Redirector
     */
        public function update(AnatomyRequest $request, int $id) :RedirectResponse
    {
        
      foreach ($request->anatomy as $key=>$row) {
          
          if(!isset($row['id'])){
           $anatomy =  ReservationAnatomy::create([
                    'description'=>$row['description'],
                    'cost'=>$row['cost'],
                    'anatomy_id'=>$row['anatomy_id'],
                    'category_id'=>$row['category_id'],
                    'doctor_reservation_details_id'=>null,
                    'user_id'=>$request->user_id,
                    'result'=>$request->result,
                    ]);
            if(isset($request['anatomy'][$key]['image_anatomy'])){
                 $img= $request['anatomy'][$key]['image_anatomy'];
        $name=mt_rand(1000000, 9999999).time().'img-'.$img->getClientOriginalExtension();
        $img->move(public_path('/uploads/images/'),$name);
        $anatomy->image=$name;
        $anatomy->save();
            }
          }
          else{
              $anatomy = ReservationAnatomy::find($row['id']);
              
              $anatomy->update([
                    'description'=>$row['description'],
                    'cost'=>$row['cost'],
                    'anatomy_id'=>$row['anatomy_id'],
                    'category_id'=>$row['category_id'],
                    'doctor_reservation_details_id'=>null,
                    'result'=>$request->result,
                    'user_id'=>$request->user_id,
                    ]); 
                    if(isset($request['anatomy'][$key]['image_anatomy'])){
                 $img= $request['anatomy'][$key]['image_anatomy'];
        $name=mt_rand(1000000, 9999999).time().'img-'.$img->getClientOriginalExtension();
        $img->move(public_path('/uploads/images/'),$name);
        $anatomy->image=$name;
        $anatomy->save();
            }
          }
                    
        }
        
       
        return redirect($this->redirectSuccessPath)->with('message', __('dashboard.saveDone'));
    }
     private function saveData(AnatomyRequest $request, int $user_id ):void
    {
        $requestData= $request->all();
        if(isset($request->anatomy)){
        foreach ($request->anatomy as $key=>$row) {
           $anatomy =  ReservationAnatomy::create([
                    'description'=>$row['description'],
                    'cost'=>$row['cost'],
                    'anatomy_id'=>$row['anatomy_id'],
                    'category_id'=>$row['category_id'],
                    'doctor_reservation_details_id'=>null,
                    'user_id'=>$request->user_id,
                    'result'=>$request->result,
                    ]);
            if(isset($request['anatomy'][$key]['image_anatomy'])){
                 $img= $request['anatomy'][$key]['image_anatomy'];
        $name=mt_rand(1000000, 9999999).time().'img-'.$img->getClientOriginalExtension();
        $img->move(public_path('/uploads/images/'),$name);
        $anatomy->image=$name;
        $anatomy->save();
            }
                    
        }
        }

        

    }
    
    
}
