<?php

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

use Illuminate\Support\Facades\Session;


class EquipmentController extends Controller
{
    protected $model;
    protected $baseOrganizationId;
    protected $roomModel;
    protected $conceptModel;

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

    public function index(Request $request){
        $recordStatusCondition = Auth::id()==1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $rooms = $this->roomModel::with(['building'])->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();

        $equipments = $this->model::with(['room'])->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->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(code, ' ','') like '%".str_replace(" ","",$request->kword)."%'");
            })->when(!empty(trim($request->room_id)), function ($query) use($request){
                $query->where('room_id', $request->room_id);
            })->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('nrml.pagination.perpage', 10));
        return view('equipment', ['equipments' => $equipments, 'rooms' => $rooms, 'concepts' => $concepts]);
    }

    public function save(Request $request){
        try {
            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'capacity' => 'required',
                'room_id' => 'required',
                'code' => 'required',
                'equipment_type_concept_id' => 'required',
                'installed_date' => 'required'
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => __('building.create_fail'), 'errors' => $validator->errors()->all()]);
            }
            $data = array(
                'name_en' => $request->name_en,
                'capacity' => $request->capacity,
                'code' => $request->code,
                'equipment_type_concept_id' => $request->equipment_type_concept_id,
                'room_id' => $request->room_id,
                'model' => $request->model,
                'serial_number' => $request->serial_number,
                'min_temperature' => $request->min_temperature,
                'max_temperature' => $request->max_temperature,
                'status' => BaseModel::RECORD_STATUS_ACTIVE,
                'installed_date' => date('Y-m-d', strtotime($request->installed_date)),
                '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',
                'capacity' => 'required',
                'room_id' => 'required',
                'code' => 'required',
                'equipment_type_concept_id' => 'required',
                'installed_date' => 'required'
            ]);
            if ($validator->fails()) return response()->json(['errors' => $validator->errors()->all()]);
            $data = array(
                'name_en' => $request->name_en,
                'capacity' => $request->capacity,
                'code' => $request->code,
                'equipment_type_concept_id' => $request->equipment_type_concept_id,
                'room_id' => $request->room_id,
                'model' => $request->model,
                'serial_number' => $request->serial_number,
                'min_temperature' => $request->min_temperature,
                'max_temperature' => $request->max_temperature,
                'installed_date' => date('Y-m-d', strtotime($request->installed_date)),
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->model::query()->where('id', $request->equipment_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->equipment_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->equipment_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->equipment_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()]);
        }
    }


}
