<?php

namespace App\Http\Controllers;
use App\Enums\RecordStatusEnum;
use App\Http\Controllers\Helper\GlobalController;
use App\Models\BaseModel;
use App\Models\Department;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class DepartmentController extends Controller
{
    protected $model;
    protected $baseLabId;
    protected $labs;

    public function __construct(Department $department){
        $this->model = $department;
        $this->baseLabId = Session::get('base_lab_id');
        $this->base = Session::get('base_lab');
    }

    public function index(Request $request){
        if(!GlobalController::user_can(Auth::user()->role_id, ['view_department'])) return redirect(url('my-profile'));
        $standardDepartments = $this->model::query()->where([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE, 'is_standard' => 1])->get(['id','name_en'])->unique('name_en');
        $recordStatusCondition = Auth::id()==1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $departments = $this->model::query()->with(['samples'])->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->where('lab_id', $this->baseLabId)
            ->when(!empty($request->kword), function ($departments) use($request){
                $departments->whereRaw("replace(name_en, ' ','') like '%".str_replace(" ","",$request->kword)."%'");
            })->orderBy('weight','asc')->paginate(config('labis.pagination.perpage', 10));
        return view('department', ['departments' => $departments, 'labs' => $this->labs, 'standardDepartments' => $standardDepartments]);
    }

    public function save(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['create_department'])) return false;
            $validator = \Validator::make($request->all(), ['name_en' => 'required']);
            if ($validator->fails()){
                return response()->json(['success' => false, 'message' => __('department.create_fail'), 'errors' => $validator->errors()->all()]);
            }

            $new  = $this->model::query()->firstOrNew(['name_en' => $request->name_en, 'lab_id' => $this->baseLabId]);
            $new->name_en = $request->name_en;
            $new->weight = $request->weight;
            $new->lab_id = $this->baseLabId;
            $new->created_at = date('Y-m-d H:i:s');
            $new->created_by = Auth::user()->id;
            $new->record_status_id = RecordStatusEnum::ACTIVE;
            $new->save();

            return response()->json(['success' => true, 'message' => __('department.create_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('department.create_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['update_department'])) return false;
            $validator = \Validator::make($request->all(), [
                'name_en' => 'required',
                'weight' => 'nullable'
            ]);
            if ($validator->fails()) return response()->json(['success' => false, 'message' => __('department.update_fail'), 'errors' => $validator->errors()->all()]);
            $data = array(
                'name_en' => $request->name_en,
                'updated_at' => date('Y-m-d H:i:s'),
                'updated_by' => Auth::id()
            );
            $this->model::query()->where('id', $request->uid)->update($data);
            return response()->json(['success' => true, 'message' => __('department.update_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('department.update_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request){
        try{
            $department = $this->model::query()->find($request->uid);
            return response()->json(['success' => true, 'message' => __('department.get_success'), 'data' => $department]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('department.get_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function delete(Request $request){
        try{
            if(!GlobalController::user_can(Auth::user()->role_id, ['delete_department'])) return false;
            $this->model::query()->where('id', $request->uid)->update(array('record_status_id'=> RecordStatusEnum::DELETE));
            return response()->json(['success' => true, 'message' => __('department.delete_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('department.delete_fail'), 'errors' => $e->getMessage()]);
        }
    }

    public function restore(Request $request){
        try{
            $this->model::query()->where('id', $request->uid)->update(array('record_status_id'=> RecordStatusEnum::ACTIVE));
            return response()->json(['success' => true, 'message' => __('department.restore_success')]);
        } catch (\Exception $e){
            return response()->json(['success' => false, 'message' => __('department.restore_fail'), 'errors' => $e->getMessage()]);
        }
    }


}
