<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\Department;
use App\Models\SampleType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class SampleTypeController extends Controller
{

    protected $model;
    protected $departmentModel;
    protected $sampleTypeModel;

    protected $baseLabId;
    protected $labs;

    public function __construct(Department $departmentModel,SampleType $sampleTypeModel){
        $this->departmentModel = $departmentModel;
        $this->sampleTypeModel = $sampleTypeModel;
        $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_sample_type'])) return redirect(url('my-profile'));
        $standardSampleTypes = $this->sampleTypeModel::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'is_standard' => 1])->get(['id','name_en'])->unique('name_en');
        $departments = $this->departmentModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)->where('lab_id', $this->baseLabId)->get();
        $recordStatusCondition = Auth::id()==1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $sampleTypes = $this->sampleTypeModel::with(['department'=>function($query) {return $query->orderBy('id','ASC');}])->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->where('lab_id', $this->baseLabId)
            ->when(!empty($request->kword), function ($sampleTypes) use($request, $recordStatusCondition){
                $sampleTypes->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhereIn('department_id', $this->departmentModel::query()
                        ->where('lab_id', $this->baseLabId)
                        ->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'")->pluck('id')->toArray()
                    )->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition);;
            })->orderBy('weight','ASC')->paginate(config('labis.pagination.perpage', 10));
        return view('sample-type', ['sampleTypes' => $sampleTypes, 'departments' => $departments, 'standardSampleTypes' => $standardSampleTypes]);
    }

    public function save(Request $request){
        try {
            if(!GlobalController::user_can(Auth::user()->role_id, ['create_sample_type'])) return false;
            $validator = \Validator::make($request->all(), ['name_en' => 'required', 'department_id' => 'required']);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('sample_type.create_fail'), 'errors' => $validator->errors()->all()]);
            $new = $this->sampleTypeModel::query()->firstOrNew(['name_en' => $request->name_en, 'department_id' => $request->department_id]);
            $new->name_en = $request->name_en;
            $new->weight = $request->weight;
            $new->tube = $request->tube;
            $new->bg_color = $request->bg_color;
            $new->color = $request->color;
            $new->lab_id = $this->baseLabId;
            $new->department_id = $request->department_id;
            $new->enter_form_id = $request->enter_form_id;
            $new->preview_form_id = $request->preview_form_id;
            $new->description = is_array($request->description) ? json_encode($request->description) : NULL;
            $new->save();

            return response()->json(['success' => true, 'message' => __('sample_type.create_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('sample_type.create_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_sample_type'])) return false;
            $validator = \Validator::make($request->all(), ['uid' => 'required', 'name_en' => 'required' /*,'department_ids' => 'required'*/]);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('sample_type.update_fail'), 'errors' => $validator->errors()->all()]);
            $data = array(
                'name_en' => $request->name_en,
                'weight' => $request->weight,
                'tube' => $request->tube,
                'bg_color' => $request->bg_color,
                'color' => $request->color,
                'department_id' =>$request->department_id,
                'enter_form_id' => $request->enter_form_id,
                'preview_form_id' => $request->preview_form_id,
                'description' => is_array($request->description) ? json_encode($request->description) : NULL
            );
            $this->sampleTypeModel::query()->where('id', $request->uid)->update($data);
            return response()->json(['success' => true, 'message' => __('sample_type.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('sample_type.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

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

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

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

    public function getById($id){
        try{
            $sampleType = $this->sampleTypeModel::query()->find($id);
            return response()->json(['success' => true, 'message' => __('sample_type.get_success'), 'data' => $sampleType]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('sample_type.get_fail'), 'errors' => $e->getMessage()]);
        }
    }



}
