<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcService;
use Modules\Vrc\Entities\VrcServiceCategory;
use Yajra\DataTables\Facades\DataTables;

class ServiceController extends VrcBaseController
{
    public function index()
    {
        $this->guard('vrc.service.view');

        if (request()->ajax()) {
            $services = VrcService::where('vrc_services.business_id', $this->businessId())
                ->leftJoin('vrc_service_categories as cat', 'cat.id', '=', 'vrc_services.category_id')
                ->select(['vrc_services.id', 'vrc_services.code', 'vrc_services.name', 'cat.name as category_name', 'vrc_services.default_labor_hours', 'vrc_services.default_price', 'vrc_services.is_active']);

            return DataTables::of($services)
                ->editColumn('code', fn ($s) => $s->code ?: '—')
                ->editColumn('category_name', fn ($s) => $s->category_name ?: '—')
                ->editColumn('is_active', fn ($s) => $s->is_active
                    ? '<span class="label label-success">' . __('vrc::lang.active') . '</span>'
                    : '<span class="label label-default">' . __('vrc::lang.inactive') . '</span>')
                ->addColumn('action', function ($s) {
                    if (! auth()->user()->can('vrc.service.manage')) {
                        return '';
                    }
                    return '<button data-href="' . route('vrc.services.edit', $s->id) . '" class="btn btn-xs btn-primary vrc-modal-btn"><i class="fa fa-edit"></i> ' . __('messages.edit') . '</button> '
                        . '<button data-href="' . route('vrc.services.destroy', $s->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::services.index');
    }

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

    public function store(Request $request)
    {
        $this->guard('vrc.service.manage');
        $data = $this->rules($request);
        try {
            $data['business_id'] = $this->businessId();
            $data['taxable'] = $request->boolean('taxable', true);
            $data['is_active'] = $request->boolean('is_active', true);
            VrcService::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.service.manage');
        $service = VrcService::where('business_id', $this->businessId())->findOrFail($id);
        return view('vrc::services.edit', array_merge($this->formData(), compact('service')));
    }

    public function update(Request $request, $id)
    {
        $this->guard('vrc.service.manage');
        $data = $this->rules($request);
        try {
            $service = VrcService::where('business_id', $this->businessId())->findOrFail($id);
            $data['taxable'] = $request->boolean('taxable', true);
            $data['is_active'] = $request->boolean('is_active', true);
            $service->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.service.manage');
        try {
            VrcService::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();
        }
    }

    protected function rules(Request $request): array
    {
        return $this->validate($request, [
            'category_id'         => 'nullable|integer',
            'code'                => 'nullable|string|max:60',
            'hsn_sac'             => 'nullable|string|max:40',
            'name'                => 'required|string|max:191',
            'name_ar'             => 'nullable|string|max:191',
            'description'         => 'nullable|string',
            'default_labor_hours' => 'nullable|numeric|min:0',
            'default_price'       => 'nullable|numeric|min:0',
            'tax_rate_id'         => 'nullable|integer',
            'taxable'             => 'nullable',
            'is_active'           => 'nullable',
        ]);
    }

    protected function formData(): array
    {
        $bid = $this->businessId();
        return [
            'categories' => VrcServiceCategory::where('business_id', $bid)->where('is_active', true)->orderBy('name')->pluck('name', 'id')->toArray(),
            'taxRates'   => \App\TaxRate::forBusinessDropdown($bid, true)['tax_rates'],
        ];
    }
}
