<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;;

use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\Physician;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class PhysicianController extends Controller
{

    protected $baseLabId;
    protected $labs;
    private $physician;

    public function __construct(Physician $physician){
        $this->physician = $physician;
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    public function index(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['view_physician'])) return redirect(url('my-profile'));
        $physicians = $this->physician::with(['lab'])->where('record_status_id', RecordStatusEnum::ACTIVE)
            ->where('lab_id', Session::get('base_lab_id'))
            ->when(!empty($request->kword), function ($physicians) use ($request){
                $physicians->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'");
            })
            ->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('labis.pagination.perpage', 10));
        return view('physician', ['physicians' => $physicians, 'labs' => parent::getAccessAbleLabs()]);
    }

    public function save(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['create_physician'])) return redirect(url('my-profile'));
        $validator = \Validator::make($request->all(), ['name_en' => 'required']);
        if ($validator->fails()) return response()->json(['errors'=>$validator->errors()->all()]);
        $imageName = NULL;
        $footerName = NULL;
        if($request->image)
        {
            request()->validate(['image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
            $imageName = time().'.'.request()->image->getClientOriginalExtension();
            request()->image->move(public_path('storage/images/physician'), $imageName);
        }
        if($request->imageFooter)
        {
            request()->validate(['imageFooter' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
            $footerName = time().'_footer.'.request()->imageFooter->getClientOriginalExtension();
            request()->imageFooter->move(public_path('storage/images/physician'), $footerName);
        }

        $new = $this->physician::query()->firstOrNew(['name_en' => $request->name_en, 'lab_id' => $this->baseLabId]);
        $new->name_en = $request->name_en;
        $new->phone = $request->phone;
        $new->lab_id = $this->baseLabId;
        $new->logo = $imageName;
        $new->footer = $footerName;
        $new->is_default = isset($request->is_default) ? 1 : 0;
        $new->created_at = date('Y-m-d H:i:s');
        $new->created_by = Auth::user()->id;
        $new->record_status_id = RecordStatusEnum::ACTIVE;
        $new->save();

        $request->session()->flash('msg','Physician has been inserted!');
        return redirect()->back();
    }

    public function update(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['update_physician'])) return redirect(url('my-profile'));
        $validator = \Validator::make($request->all(), [
            'name_en' => 'required'
        ]);
        if ($validator->fails()) return response()->json(['errors'=>$validator->errors()->all()]);
        $imageName = NULL;
        $footerName = NULL;
        if($request->image)
        {
            request()->validate(['image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
            $imageName = time().'.'.request()->image->getClientOriginalExtension();
            request()->image->move(public_path('storage/images/physician'), $imageName);
        }
        if($request->imageFooter)
        {
            request()->validate(['imageFooter' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
            $footerName = time().'_footer.'.request()->imageFooter->getClientOriginalExtension();
            request()->imageFooter->move(public_path('storage/images/physician'), $footerName);
        }
        $data = array(
            'name_en' => $request->name_en,
            'name_kh' => $request->name_kh,
			'phone' => $request->phone,
            'is_default' => isset($request->is_default) ? 1: 0,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => Auth::id()
        );
        if(!empty($imageName)){$data = array_merge($data, ['logo' => $imageName]);}
        if(!empty($footerName)){$data = array_merge($data, ['footer' => $footerName]);}
        $status = $this->physician::query()->where('id', $request->uid)->update($data);
        $request->session()->flash('msg','Physician has been updated!');
        return redirect()->back();
    }

    public function deletePhysicianLogo(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_physician'])) return false;
            $physician = $this->physician::query()->find($request->uid);
            if(file_exists(public_path('storage/images/physician/'.$physician->logo))){
                unlink(public_path('storage/images/physician/'.$physician->logo));
                $physician->logo = null;
            }
            $physician->save();
            return response()->json(['success'=> true , 'message' => __('physician.delete_photo_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('physician.delete_photo_failed')]);
        }
    }

    public function deletePhysicianFooter(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_physician'])) return false;
            $physician = $this->physician::query()->find($request->uid);
            if(file_exists(public_path('storage/images/physician/'.$physician->footer))){
                unlink(public_path('storage/images/physician/'.$physician->footer));
                $physician->footer = null;
            }
            $physician->save();
            return response()->json(['success'=> true , 'message' => __('physician.delete_photo_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('physician.delete_photo_failed')]);
        }
    }

    public function get(Request $request){
        try {
            $physician = $this->physician::query()->find($request->uid);
            return response()->json(['success'=> true , 'message' => __('physician.get_success'), 'data' => $physician]);
        } catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('physician.get_fail')]);
        }
    }

    public function delete(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['delete_physician'])) return false;
            $this->physician::query()->where('id', $request->uid)->update(array( BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE));
            return response()->json(['success'=> true , 'message' => __('physician.delete_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success'=> false , 'message' => __('physician.delete_fail')]);
        }

    }

    public function restore(Request $request){
        try {
            $this->physician::query()->where('id', $request->uid)->update(array(BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE));
            return response()->json(['success' => true, 'message' => __('physician.restore_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('physician.restore_fail'), 'errors' => $e->getMessage()]);
        }
    }


}
