<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcAppointment;
use Modules\Vrc\Entities\VrcBay;
use Yajra\DataTables\Facades\DataTables;

class BayController extends VrcBaseController
{
    public function index()
    {
        $this->guard('vrc.bay.manage');

        if (request()->ajax()) {
            $locations = $this->locations();
            $bays = VrcBay::where('business_id', $this->businessId())
                ->select(['id', 'name', 'type', 'location_id', 'is_active']);

            return DataTables::of($bays)
                ->editColumn('type', fn ($b) => VrcBay::types()[$b->type] ?? $b->type)
                ->editColumn('location_id', fn ($b) => $locations[$b->location_id] ?? '—')
                ->editColumn('is_active', fn ($b) => $b->is_active
                    ? '<span class="label label-success">' . __('vrc::lang.active') . '</span>'
                    : '<span class="label label-default">' . __('vrc::lang.inactive') . '</span>')
                ->addColumn('action', fn ($b) => '<button data-href="' . route('vrc.bays.edit', $b->id) . '" class="btn btn-xs btn-primary vrc-modal-btn"><i class="fa fa-edit"></i> ' . __('messages.edit') . '</button> '
                    . '<button data-href="' . route('vrc.bays.destroy', $b->id) . '" class="btn btn-xs btn-danger vrc-delete"><i class="fa fa-trash"></i></button>')
                ->rawColumns(['is_active', 'action'])
                ->make(true);
        }

        return view('vrc::bays.index');
    }

    public function create()
    {
        $this->guard('vrc.bay.manage');
        return view('vrc::bays.create', $this->formData());
    }

    public function store(Request $request)
    {
        $this->guard('vrc.bay.manage');
        $data = $this->rules($request);
        try {
            $data['business_id'] = $this->businessId();
            $data['is_active'] = $request->boolean('is_active', true);
            VrcBay::create($data);
            return $this->ok(__('vrc::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function edit($id)
    {
        $this->guard('vrc.bay.manage');
        $bay = VrcBay::where('business_id', $this->businessId())->findOrFail($id);
        return view('vrc::bays.edit', array_merge($this->formData(), compact('bay')));
    }

    public function update(Request $request, $id)
    {
        $this->guard('vrc.bay.manage');
        $data = $this->rules($request);
        try {
            $bay = VrcBay::where('business_id', $this->businessId())->findOrFail($id);
            $data['is_active'] = $request->boolean('is_active', true);
            $bay->update($data);
            return $this->ok(__('vrc::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function destroy($id)
    {
        $this->guard('vrc.bay.manage');
        try {
            VrcBay::where('business_id', $this->businessId())->findOrFail($id)->delete();
            return $this->ok(__('vrc::lang.deleted_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    /** Bay utilisation in a window (busy slot count per bay). Expanded in Phase 8. */
    public function utilization(Request $request)
    {
        $this->guard('vrc.bay.manage');
        $from = $request->get('from', now()->startOfDay()->toDateTimeString());
        $to = $request->get('to', now()->endOfDay()->toDateTimeString());

        $rows = VrcBay::where('business_id', $this->businessId())->where('is_active', true)->get()
            ->map(function ($bay) use ($from, $to) {
                $busy = VrcAppointment::where('business_id', $bay->business_id)
                    ->where('bay_id', $bay->id)->active()
                    ->where('scheduled_start', '<', $to)
                    ->where(fn ($w) => $w->whereNull('scheduled_end')->orWhere('scheduled_end', '>', $from))
                    ->count();
                return ['bay' => $bay->name, 'busy' => $busy, 'occupied' => $busy > 0];
            });

        return response()->json($rows);
    }

    protected function rules(Request $request): array
    {
        return $this->validate($request, [
            'name'        => 'required|string|max:191',
            'type'        => 'required|in:lift,bay,wash,diagnostic',
            'location_id' => 'nullable|integer',
            'is_active'   => 'nullable',
        ]);
    }

    protected function formData(): array
    {
        return ['locations' => $this->locations(), 'types' => VrcBay::types()];
    }
}
