<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\SampleType;
use Illuminate\Http\Request;
use App\Models\Organization;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Session;
use function Yajra\DataTables\Html\data;


class OrganizationController extends Controller
{
    protected $model;
    protected $baseOrganizationId;
    protected $labs;

    public function __construct(Organization $model){
        $this->model = $model;
        $this->baseOrganizationId = Session::get('base_organization_id');
        $this->base = Session::get('base_organization');
    }

    public function index(Request $request){
        $labs = $this->model::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(Auth::id()!=1, function ($labs){
                $labs->whereIn('id', $this->labs->pluck('id'));
            })->when(!empty($request->kword), function ($labs) use($request){
                $labs->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhereRaw("replace(name_kh, ' ','') like '%".str_replace(" ","",$request->kword)."%'")
                    ->orWhere('address_en','like','%'.$request->kword.'%')
                    ->orWhere('address_kh','like','%'.$request->kword.'%');
            })->orderBy(BaseModel::CREATED_AT,'desc')->paginate(config('nrml.pagination.perpage', 10));
        return view('laboratory', ['laboratories' => $labs]);
    }

    public function save(Request $request){
        try {

            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'name_kh' => 'required',
                'code' => 'required|max:10'
            ]);
            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => __('laboratory.create_fail'), 'errors' => $validator->errors()->all()]);
            }
            $data = array(
                'name_en' => $request->name_en,
                'name_kh' => $request->name_kh,
                'code' => $request->code,
                'phone' => $request->phone,
                'email' => $request->email,
                'address_en' => $request->address_en,
                'address_kh' => $request->address_kh,
                '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 updateInfo(Request $request){
        try {
            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'name_kh' => 'required',
                'code' => 'required|max:10'
            ]);
            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,
                'email' => $request->email,
                'phone' => $request->phone,
                'address_en' => $request->address_en,
                'address_kh' => $request->address_kh,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->model::query()->where('id', $this->baseOrganizationId)->update($data);
            return redirect()->back();
        } catch (\Exception $e){
            dd($e);
            return response()->json(['success' => false, 'message' => __('laboratory.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try {

            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'name_kh' => 'required',
                'code' => 'required|max:10'
            ]);
            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,
                'email' => $request->email,
                'phone' => $request->phone,
                'address_en' => $request->address_en,
                'address_kh' => $request->address_kh,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->model::query()->where('id', $request->organization_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{
            $organization_id = $request->organization_id;
            $lab = $this->model::query()->where('id', $organization_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->organization_id)->update(array(
                BaseModel::DELETED_AT_FIELD => data('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->organization_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()]);
        }
    }

    public function profile(){
        if(!GlobalController::user_can(Auth::user()->role_id, ['update_laboratory_information'])) return redirect(url('my-profile'));
        $organization = $this->model::query()->find($this->baseOrganizationId);
        return view('organization_profile', ['info' => $organization]);
    }


}
