<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Enums\UtilEnum;
use App\Models\Role;
use App\Models\User;
use App\Models\UserOrganization;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Organization;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;

class BaseController extends Controller
{

    public function __construct()
    {
    }

    function getLabs(){
        return parent::getAccessAbleLabs();
    }

    public function index(Request $request){
        $organizations = Organization::query()->where('record_status_id', RecordStatusEnum::ACTIVE)
            ->whereIn('id', $this->getLabs()->pluck('id')->toArray())
            ->orderBy('created_at','desc')->get();

        $request->session()->put('base_organization_coverages', $organizations->pluck('name_en')->toArray());

        // check it only one base default assign base session, else redirect to base view
        if(count($organizations)==1){
            $request->session()->put('base_organization_id', $organizations->first()->id);
            $request->session()->put('base_organization_name', $organizations->first()->name_en);
            $request->session()->put('base_organization', $organizations[0]->toArray());
            if ($request->session()->has('base_organization_id')) {
                return redirect('/dashboard');
            }
        }
        return view('base', ['organizations' => $organizations]);
    }

    public function forget(Request $request){
        if ($request->session()->has('base_organization_id')) {
            $request->session()->forget('base_organization_id');
            $request->session()->forget('base_organization_name');
            $request->session()->forget('base_organization');
            $request->session()->forget('base_organization_coverages');
            return redirect()->route('base');
        }
    }

    public function store(Request $request){
        $validator = \Validator::make($request->all(), [ 'organization_id' => 'required']);
        if ($validator->fails())
        {
            session()->flash('error', 'Invalid credentials');
            return redirect()->route('base');
        }
        $organization = Organization::query()->find($request->organization_id);
        $request->session()->put('base_organization_id', $request->organization_id);
        $request->session()->put('base_organization_name', $organization->name_en);
        $request->session()->put('base_organization', $organization->toArray());
        if (!$request->session()->has('base_organization_id')) {
            return redirect()->route('base');
        }
        return redirect('/dashboard');
    }
}
