<?php

namespace Modules\Bms\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Bms\Entities\BmsOfficeVisit;
use Yajra\DataTables\Facades\DataTables;

class OfficeVisitController extends BmsBaseController
{
    public function index()
    {
        $this->guard('bms.bookings.view');

        if (request()->ajax()) {
            $rows = BmsOfficeVisit::where('bms_office_visits.business_id', $this->businessId())
                ->leftJoin('contacts', 'contacts.id', '=', 'bms_office_visits.contact_id')
                ->select([
                    'bms_office_visits.id', 'bms_office_visits.visit_date', 'bms_office_visits.visit_time',
                    'bms_office_visits.status', 'contacts.name as contact_name', 'contacts.mobile as contact_mobile',
                ]);

            return DataTables::of($rows)
                ->editColumn('contact_name', fn ($v) => $v->contact_name ?: '—')
                ->editColumn('visit_date', fn ($v) => $v->visit_date ? \Carbon\Carbon::parse($v->visit_date)->format('Y-m-d') : '—')
                ->editColumn('status', fn ($v) => '<span class="label '.$this->statusClass($v->status).'">'.$this->statusLabel($v->status).'</span>')
                ->addColumn('action', fn ($v) => '<a href="'.route('bms.visits.show', $v->id).'" class="tw-dw-btn tw-dw-btn-xs tw-dw-btn-outline tw-dw-btn-primary"><i class="fa fas fa-eye"></i> '.__('messages.view').'</a>')
                ->rawColumns(['status', 'action'])
                ->make(true);
        }

        return view('bms::visits.index');
    }

    public function show($id)
    {
        $this->guard('bms.bookings.view');
        $visit = BmsOfficeVisit::with(['contact:id,name,mobile,email'])
            ->where('business_id', $this->businessId())->findOrFail($id);

        return view('bms::visits.show', [
            'visit'     => $visit,
            'statuses'  => $this->visitStatuses(),
            'locations' => $this->locations(),
            'canManage' => auth()->user()->can('bms.bookings.manage'),
        ]);
    }

    public function update(Request $request, $id)
    {
        $this->guard('bms.bookings.manage');
        $data = $this->validate($request, [
            'status'      => 'required|in:requested,confirmed,done,cancelled',
            'visit_date'  => 'nullable|date',
            'visit_time'  => 'nullable',
            'location_id' => 'nullable|integer',
            'notes'       => 'nullable|string',
        ]);

        try {
            $visit = BmsOfficeVisit::where('business_id', $this->businessId())->findOrFail($id);
            $visit->fill($data)->save();

            return redirect()->route('bms.visits.show', $visit->id)
                ->with('status', __('bms::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return back()->withInput()->with('error', __('messages.something_went_wrong'));
        }
    }

    protected function visitStatuses(): array
    {
        return collect(['requested', 'confirmed', 'done', 'cancelled'])
            ->mapWithKeys(fn ($s) => [$s => $this->statusLabel($s)])->toArray();
    }

    protected function statusLabel(string $s): string
    {
        $key = 'bms::lang.vst_'.$s;
        $label = __($key);
        return $label === $key ? ucfirst($s) : $label;
    }

    protected function statusClass(string $s): string
    {
        return [
            'requested' => 'label-warning', 'confirmed' => 'label-primary',
            'done' => 'label-success', 'cancelled' => 'label-default',
        ][$s] ?? 'label-default';
    }
}
