<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Enums\UtilEnum;
use App\Models\AgeGroup;
use App\Models\Department;
use App\Models\PatientType;
use App\Models\Role;
use App\Models\User;
use App\Models\UserLabCover;
use App\Models\WardTransaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Models\Laboratory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;

class BaseController extends Controller
{

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

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

        $request->session()->put('base_lab_coverages', $labs->pluck('name_en')->toArray());

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

    public function forget(Request $request){
        if ($request->session()->has('base_lab_id')) {
            $request->session()->forget('base_lab_id');
            $request->session()->forget('base_lab_name');
            $request->session()->forget('base_lab');
            $request->session()->forget('base_lab');
            $request->session()->forget('base_lab_coverages');
            return redirect()->route('base');
        }
    }

    public function store(Request $request){
        $validator = \Validator::make($request->all(), [ 'lab_id' => 'required']);
        if ($validator->fails())
        {
            session()->flash('error', 'Invalid credentials');
            return redirect()->route('base');
        }
        $lab = Laboratory::query()->find($request->lab_id);
        $request->session()->put('base_lab_id', $request->lab_id);
        $request->session()->put('base_lab_name', $lab->name_en);
        $request->session()->put('base_lab', $lab->toArray());
        if (!$request->session()->has('base_lab_id')) {
            return redirect()->route('base');
        }
        return redirect('/dashboard');
    }
}
