<?php

namespace App\Http\Controllers;

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

class BoxController extends Controller
{
    protected $model;
    protected $rackModel;
    protected $baseOrganizationId;
    protected $base;

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

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

        $boxes = $this->model::with(['rack.equipment.room.building'])
            ->whereIn(BaseModel::RECORD_STATUS_FIELD, $recordStatusCondition)
            ->whereIn('rack_id', $racks->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->rack_id)), function ($query) use ($request) {
                $query->where('rack_id', $request->rack_id);
            })
            ->orderBy(BaseModel::CREATED_AT_FIELD, 'desc')
            ->paginate(config('nrml.pagination.perpage', 10));

        return view('box', ['boxes' => $boxes, 'racks' => $racks]);
    }

    public function save(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'rack_id' => 'required',
                'code' => 'required',
                'name' => 'required',
                'rows' => 'required|integer|min:1',
                'columns' => 'required|integer|min:1',
            ]);

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

            $this->model::query()->insert([
                'rack_id' => $request->rack_id,
                'code' => $request->code,
                'name' => $request->name,
                'rows' => $request->rows,
                'columns' => $request->columns,
                'capacity' => $request->capacity ?: ((int) $request->rows * (int) $request->columns),
                BaseModel::CREATED_AT_FIELD => date('Y-m-d H:i:s'),
                BaseModel::CREATED_BY_FIELD => Auth::id(),
            ]);

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

    public function update(Request $request)
    {
        try {
            $validator = \Validator::make($request->all(), [
                'box_id' => 'required',
                'rack_id' => 'required',
                'code' => 'required',
                'name' => 'required',
                'rows' => 'required|integer|min:1',
                'columns' => 'required|integer|min:1',
            ]);

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

            $this->model::query()->where('id', $request->box_id)->update([
                'rack_id' => $request->rack_id,
                'code' => $request->code,
                'name' => $request->name,
                'rows' => $request->rows,
                'columns' => $request->columns,
                'capacity' => $request->capacity ?: ((int) $request->rows * (int) $request->columns),
                BaseModel::UPDATED_AT_FIELD => date('Y-m-d H:i:s'),
                BaseModel::UPDATED_BY_FIELD => Auth::id(),
            ]);

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

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

    public function delete(Request $request)
    {
        try {
            $this->model::query()->where('id', $request->box_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' => 'Box has been deleted.']);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => 'Unable to delete box.', 'errors' => $e->getMessage()]);
        }
    }

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