<?php

namespace App\Http\Controllers;

use App\Enums\RecordStatusEnum;
use App\Models\BaseModel;
use App\Models\Commune;
use App\Models\District;
use App\Models\Organization;
use App\Models\Province;
use App\Models\UserOrganization;
use App\Models\Village;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

abstract class Controller
{
    function getAccessAbleLabs(){
        $recordStatusCondition = Auth::id()==1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $organizations = Organization::query()->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)->get();
        if(Auth::id()!=1){
            $organizationId = UserOrganization::query()->where('user_id', Auth::id())->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)->pluck('organization_id')->toArray();
            $organizations = $organizations->whereIn('id', $organizationId);
        }
        return $organizations;
    }

    function province(){
        return Province::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)->get(['id','name_en','name_kh']);
    }

    function district($province_id = null){
        return District::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(! is_null($province_id), function ($district) use($province_id){
                $district->where('province_id', $province_id);
            })->orderBy('name_en','asc')->get(['id','name_en','name_kh']);
    }

    function commune($district_id = null){
        return Commune::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(!is_null($district_id), function ($commune) use($district_id){
                $commune->where('district_id', $district_id);
            })->orderBy('name_en','asc')->get(['id','name_en','name_kh']);
    }

    function village($commune_id = null){
        return Village::query()->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->when(!is_null($commune_id), function ($village) use($commune_id){
                $village->where('commune_id', $commune_id);
            })->orderBy('name_en','asc')->get(['id','name_en','name_kh']);
    }

    public function location(){
        return Organization::query()->find(Session::get('base_organization_id'))->only([
            'id',
            'name_en',
            'name_kh'
        ]);
    }

//    public function switchLanguage($locale)
//    {
//        if (array_key_exists($locale, config('app.available_locales'))) {
//            session(['locale' => $locale]);
//        }
//        return redirect()->back();
//    }

}
