<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Vrc\Entities\VrcInspectionTemplate;
use Modules\Vrc\Entities\VrcInspectionTemplateItem;
use Yajra\DataTables\Facades\DataTables;

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

        if (request()->ajax()) {
            $templates = VrcInspectionTemplate::where('business_id', $this->businessId())
                ->withCount('items')->select(['id', 'name', 'name_ar', 'vehicle_type', 'is_active']);

            return DataTables::of($templates)
                ->editColumn('vehicle_type', fn ($t) => $t->vehicle_type ?: '—')
                ->editColumn('is_active', fn ($t) => $t->is_active
                    ? '<span class="label label-success">' . __('vrc::lang.active') . '</span>'
                    : '<span class="label label-default">' . __('vrc::lang.inactive') . '</span>')
                ->addColumn('action', fn ($t) => '<a href="' . route('vrc.inspection-templates.edit', $t->id) . '" class="btn btn-xs btn-primary"><i class="fa fa-edit"></i> ' . __('messages.edit') . '</a> '
                    . '<button data-href="' . route('vrc.inspection-templates.destroy', $t->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::inspection_templates.index');
    }

    public function create()
    {
        $this->guard('vrc.inspection.manage');
        return view('vrc::inspection_templates.edit', ['template' => new VrcInspectionTemplate(['is_active' => true])]);
    }

    public function store(Request $request)
    {
        $this->guard('vrc.inspection.manage');
        $data = $this->rules($request);

        DB::beginTransaction();
        try {
            $template = VrcInspectionTemplate::create([
                'business_id'  => $this->businessId(),
                'name'         => $data['name'],
                'name_ar'      => $data['name_ar'] ?? null,
                'vehicle_type' => $data['vehicle_type'] ?? null,
                'is_active'    => $request->boolean('is_active', true),
            ]);
            $this->syncItems($template, $request);
            DB::commit();

            return redirect()->route('vrc.inspection-templates.index')
                ->with('status', ['success' => 1, 'msg' => __('vrc::lang.added_success')]);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency($e->getMessage());
            return back()->with('status', ['success' => 0, 'msg' => __('messages.something_went_wrong')]);
        }
    }

    public function edit($id)
    {
        $this->guard('vrc.inspection.manage');
        $template = VrcInspectionTemplate::with('items')->where('business_id', $this->businessId())->findOrFail($id);
        return view('vrc::inspection_templates.edit', compact('template'));
    }

    public function update(Request $request, $id)
    {
        $this->guard('vrc.inspection.manage');
        $data = $this->rules($request);

        DB::beginTransaction();
        try {
            $template = VrcInspectionTemplate::where('business_id', $this->businessId())->findOrFail($id);
            $template->update([
                'name'         => $data['name'],
                'name_ar'      => $data['name_ar'] ?? null,
                'vehicle_type' => $data['vehicle_type'] ?? null,
                'is_active'    => $request->boolean('is_active', true),
            ]);
            $template->items()->delete();
            $this->syncItems($template, $request);
            DB::commit();

            return redirect()->route('vrc.inspection-templates.index')
                ->with('status', ['success' => 1, 'msg' => __('vrc::lang.updated_success')]);
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::emergency($e->getMessage());
            return back()->with('status', ['success' => 0, 'msg' => __('messages.something_went_wrong')]);
        }
    }

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

    protected function syncItems(VrcInspectionTemplate $template, Request $request): void
    {
        foreach ((array) $request->input('item_label', []) as $i => $label) {
            if (trim((string) $label) === '') {
                continue;
            }
            VrcInspectionTemplateItem::create([
                'business_id' => $template->business_id,
                'template_id' => $template->id,
                'section'     => $request->input('item_section')[$i] ?? null,
                'label'       => $label,
                'label_ar'    => $request->input('item_label_ar')[$i] ?? null,
                'input_type'  => $request->input('item_input_type')[$i] ?? 'status',
                'sort_order'  => $i,
            ]);
        }
    }

    protected function rules(Request $request): array
    {
        return $this->validate($request, [
            'name'         => 'required|string|max:191',
            'name_ar'      => 'nullable|string|max:191',
            'vehicle_type' => 'nullable|string|max:40',
            'is_active'    => 'nullable',
        ]);
    }
}
