<?php

namespace App\Http\Controllers;

use App\Enums\RecordStatusEnum;
use App\Models\BaseModel;
use App\Models\Equipment;
use App\Models\Rack;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class RackController extends Controller
{
    protected $model;
    protected $equipmentModel;
    protected $baseOrganizationId;
    protected $base;

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

    public function index(Request $request)
    {
        $recordStatusCondition = Auth::id() == 1 ? [RecordStatusEnum::DELETE, RecordStatusEnum::ACTIVE] : [RecordStatusEnum::ACTIVE];
        $equipments = $this->equipmentModel::with(['room.building'])
            ->where(BaseModel::RECORD_STATUS_FIELD, RecordStatusEnum::ACTIVE)
            ->where('organization_id', $this->baseOrganizationId)
            ->get();

        $racks = $this->model::with(['equipment.room.building'])
            ->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->whereIn('equipment_id', $equipments->pluck('id')->toArray())
            ->when(!empty($request->kword), function ($query) use ($request) {
                $keyword = str_replace(' ', '', $request->kword);
                $query->where(function ($query) use ($keyword) {
                    $query->whereRaw("replace(name, ' ','') like ?", ['%' . $keyword . '%'])
                        ->orWhereRaw("replace(code, ' ','') like ?", ['%' . $keyword . '%']);
                });
            })
            ->when(!empty(trim($request->equipment_id)), function ($query) use ($request) {
                $query->where('equipment_id', $request->equipment_id);
            })
            ->orderBy(BaseModel::CREATED_AT_FIELD, 'desc')
            ->paginate(config('nrml.pagination.perpage', 10));

        return view('rack', ['racks' => $racks, 'equipments' => $equipments]);
    }

    public function save(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'equipment_id' => 'required',
                'code' => 'required',
                'name' => 'required',
            ]);

            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => 'Unable to create rack.', 'errors' => $validator->errors()->all()]);
            }

            $this->model::query()->insert([
                'equipment_id' => $request->equipment_id,
                'code' => $request->code,
                'name' => $request->name,
                'description' => $request->description,
                BaseModel::CREATED_AT_FIELD => date('Y-m-d H:i:s'),
                BaseModel::CREATED_BY_FIELD => Auth::id(),
            ]);

            return response()->json(['success' => true, 'message' => 'Rack has been created.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Unable to create rack.', 'errors' => $e->getMessage()]);
        }
    }

    public function update(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'rack_id' => 'required',
                'equipment_id' => 'required',
                'code' => 'required',
                'name' => 'required',
            ]);

            if ($validator->fails()) {
                return response()->json(['success' => false, 'message' => 'Unable to update rack.', 'errors' => $validator->errors()->all()]);
            }

            $this->model::query()->where('id', $request->rack_id)->update([
                'equipment_id' => $request->equipment_id,
                'code' => $request->code,
                'name' => $request->name,
                'description' => $request->description,
                BaseModel::UPDATED_AT_FIELD => date('Y-m-d H:i:s'),
                BaseModel::UPDATED_BY_FIELD => Auth::id(),
            ]);

            return response()->json(['success' => true, 'message' => 'Rack has been updated.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Unable to update rack.', 'errors' => $e->getMessage()]);
        }
    }

    public function get(Request $request)
    {
        try {
            $rack = $this->model::query()->where('id', $request->rack_id)->first();
            return response()->json(['success' => true, 'message' => 'Rack has been retrieved.', 'data' => $rack]);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Unable to retrieve rack.', 'errors' => $e->getMessage()]);
        }
    }

    public function delete(Request $request)
    {
        try {
            $this->model::query()->where('id', $request->rack_id)->update([
                BaseModel::DELETED_AT_FIELD => date('Y-m-d H:i:s'),
                BaseModel::DELETED_BY_FIELD => Auth::id(),
                BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::DELETE,
            ]);

            return response()->json(['success' => true, 'message' => 'Rack has been deleted.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Unable to delete rack.', 'errors' => $e->getMessage()]);
        }
    }

    public function restore(Request $request)
    {
        try {
            $this->model::query()->where('id', $request->rack_id)->update([BaseModel::RECORD_STATUS_FIELD => RecordStatusEnum::ACTIVE]);
            return response()->json(['success' => true, 'message' => 'Rack has been restored.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Unable to restore rack.', 'errors' => $e->getMessage()]);
        }
    }
}
