<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\Building;
use App\Models\Concept;
use App\Models\Room;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Session;


class RoomController extends Controller
{
    protected $model;
    protected $baseOrganizationId;
    protected $buildingModel;
    protected $conceptModel;

    public function __construct(){
        $this->baseOrganizationId = Session::get('base_organization_id');
        $this->base = Session::get('base_organization');
        $this->model = new Room();
        $this->buildingModel = new Building();
        $this->conceptModel = new Concept();
    }

    public function index(Request $request){
        $buildings = $this->buildingModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->where('organization_id', $this->baseOrganizationId)->get();
        $concepts = $this->conceptModel::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)->get();
        $rooms = $this->model::with(['building', 'bsl'])->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->where('organization_id', $this->baseOrganizationId)
            ->when(!empty($request->kword), function ($query) use($request){
                $query->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhereRaw("replace(name_kh, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhereRaw("replace(code, ' ','') like '%".str_replace(" ","",$request->kword)."%'");
            })->when(!empty(trim($request->building_id)), function ($query) use($request){
                $query->where('building_id', $request->building_id);
            })->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('nrml.pagination.perpage', 10));
        return view('room', ['rooms' => $rooms, 'buildings' => $buildings, 'concepts' => $concepts]);
    }

    public function save(Request $request){
        try {

            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'name_kh' => 'required',
                'building_id' => 'required',
                'code' => 'required',
                'biosafety_level_concept_id' => 'required'
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => __('building.create_fail'), 'errors' => $validator->errors()->all()]);
            }
            $data = array(
                'name_en' => $request->name_en,
                'name_kh' => $request->name_kh,
                'code' => $request->code,
                'description' => $request->description,
                'building_id' => $request->building_id,
                'biosafety_level_concept_id' => $request->biosafety_level_concept_id,
                'temperature_range' => $request->temperature_range,
                'organization_id' => $this->baseOrganizationId,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by' => Auth::id()
            );
            $this->model::query()->insert($data);
            return response()->json(['success' => true, 'message' => __('laboratory.create_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.create_fail'), 'errors' => $e->getMessage()]);
        }
    }


    public function update(Request $request){
        try {

            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'name_kh' => 'required',
                'building_id' => 'required',
                'code' => 'required',
                'biosafety_level_concept_id' => 'required'
            ]);
            if ($validator->fails()) return response()->json(['errors' => $validator->errors()->all()]);
            $data = array(
                'name_en' => $request->name_en,
                'name_kh' => $request->name_kh,
                'code' => $request->code,
                'description' => $request->description,
                'building_id' => $request->building_id,
                'biosafety_level_concept_id' => $request->biosafety_level_concept_id,
                'temperature_range' => $request->temperature_range,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->model::query()->where('id', $request->room_id)->update($data);
            return response()->json(['success' => true, 'message' => __('laboratory.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request){
        try{
            $lab = $this->model::query()->where('id', $request->room_id)->get()->first();
            return response()->json(['success' => true, 'message' => __('laboratory.get_success'), 'data' => $lab]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.get_fail'), 'errors' => $e->getMessage()]);
        }

    }

    public function delete(Request $request){
        try{
            $this->model::query()->where('id', $request->room_id)->update(array(
                BaseModel::DELETED_AT_FIELD => date('Y-m-d H:i:s'),
                BaseModel::DELETED_BY_FIELD => Auth::id(),
                BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE
            ));
            return response()->json(['success' => true, 'message' => __('laboratory.delete_success')]);
        }
        catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('laboratory.delete_fail'), 'errors' => $e->getMessage()]);
        }

    }

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


}
