<?php

namespace Modules\Vrc\Http\Controllers;

use Illuminate\Http\Request;
use Modules\Vrc\Entities\VrcVehicle;
use Modules\Vrc\Entities\VrcVehicleMake;
use Modules\Vrc\Entities\VrcVehicleModel;
use Modules\Vrc\Services\Contracts\ContactServiceContract;
use Yajra\DataTables\Facades\DataTables;

class VehicleController extends VrcBaseController
{
    public function __construct(protected ContactServiceContract $contacts)
    {
    }

    public function index()
    {
        $this->guard('vrc.vehicle.view');

        if (request()->ajax()) {
            $vehicles = VrcVehicle::where('vrc_vehicles.business_id', $this->businessId())
                ->leftJoin('vrc_vehicle_makes as mk', 'mk.id', '=', 'vrc_vehicles.make_id')
                ->leftJoin('vrc_vehicle_models as md', 'md.id', '=', 'vrc_vehicles.model_id')
                ->leftJoin('contacts as c', 'c.id', '=', 'vrc_vehicles.erp_customer_id')
                ->search(request('search_term'))
                ->select([
                    'vrc_vehicles.id',
                    'vrc_vehicles.plate_number',
                    'vrc_vehicles.vin',
                    'vrc_vehicles.year',
                    'mk.name as make_name',
                    'md.name as model_name',
                    'c.name as customer_name',
                    'vrc_vehicles.is_active',
                ]);

            return DataTables::of($vehicles)
                ->editColumn('plate_number', fn ($v) => $v->plate_number ?: '—')
                ->editColumn('vin', fn ($v) => $v->vin ?: '—')
                ->addColumn('make_model', fn ($v) => trim(($v->make_name ?? '') . ' ' . ($v->model_name ?? '')) ?: '—')
                ->editColumn('customer_name', fn ($v) => $v->customer_name ?: '—')
                ->editColumn('is_active', fn ($v) => $v->is_active
                    ? '<span class="label label-success">' . __('vrc::lang.active') . '</span>'
                    : '<span class="label label-default">' . __('vrc::lang.inactive') . '</span>')
                ->addColumn('action', function ($v) {
                    $btns = '<a href="' . route('vrc.vehicles.show', $v->id) . '" class="btn btn-xs btn-info"><i class="fa fa-eye"></i> ' . __('messages.view') . '</a> ';
                    if (auth()->user()->can('vrc.vehicle.manage')) {
                        $btns .= '<button data-href="' . route('vrc.vehicles.edit', $v->id) . '" class="btn btn-xs btn-primary vrc-modal-btn"><i class="fa fa-edit"></i> ' . __('messages.edit') . '</button> ';
                        $btns .= '<button data-href="' . route('vrc.vehicles.destroy', $v->id) . '" class="btn btn-xs btn-danger vrc-delete"><i class="fa fa-trash"></i></button>';
                    }
                    return $btns;
                })
                ->rawColumns(['is_active', 'action'])
                ->make(true);
        }

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

    public function create()
    {
        $this->guard('vrc.vehicle.manage');

        return view('vrc::vehicles.create', $this->formData());
    }

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

        try {
            $data['business_id'] = $this->businessId();
            $data['is_active'] = $request->boolean('is_active', true);
            VrcVehicle::create($data);

            return $this->ok(__('vrc::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    public function show($id)
    {
        $this->guard('vrc.vehicle.view');
        $vehicle = VrcVehicle::with(['make', 'model'])
            ->where('business_id', $this->businessId())->findOrFail($id);
        $customer = $this->contacts->find($this->businessId(), (int) $vehicle->erp_customer_id);

        return view('vrc::vehicles.show', compact('vehicle', 'customer'));
    }

    public function edit($id)
    {
        $this->guard('vrc.vehicle.manage');
        $vehicle = VrcVehicle::where('business_id', $this->businessId())->findOrFail($id);

        return view('vrc::vehicles.edit', array_merge($this->formData($vehicle), compact('vehicle')));
    }

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

        try {
            $vehicle = VrcVehicle::where('business_id', $this->businessId())->findOrFail($id);
            $data['is_active'] = $request->boolean('is_active', true);
            $vehicle->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.vehicle.manage');
        try {
            VrcVehicle::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();
        }
    }

    /** Service history: repair orders for this vehicle, newest first (Phase 4 fills this). */
    public function history($id)
    {
        $this->guard('vrc.vehicle.view');
        $vehicle = VrcVehicle::with(['make', 'model'])
            ->where('business_id', $this->businessId())->findOrFail($id);

        // Repair orders are introduced in Phase 4; until then history is empty.
        $orders = class_exists(\Modules\Vrc\Entities\VrcRepairOrder::class)
            ? \Modules\Vrc\Entities\VrcRepairOrder::where('business_id', $this->businessId())
                ->where('vehicle_id', $vehicle->id)
                ->orderByDesc('created_at')->get()
            : collect();

        return view('vrc::vehicles.history', compact('vehicle', 'orders'));
    }

    /** Active + historical warranties for a vehicle (spec §6.11). */
    public function warranties($id)
    {
        $this->guard('vrc.vehicle.view');
        $vehicle = VrcVehicle::with(['make', 'model'])->where('business_id', $this->businessId())->findOrFail($id);
        $warranties = \Modules\Vrc\Entities\VrcWarranty::where('business_id', $this->businessId())
            ->where('vehicle_id', $vehicle->id)->orderByDesc('end_date')->get();

        return view('vrc::vehicles.warranties', compact('vehicle', 'warranties'));
    }

    /** Vehicles owned by an ERP customer (JSON) — for dependent dropdowns. */
    public function customerVehicles($erpCustomerId)
    {
        $this->guard('vrc.vehicle.view');
        $vehicles = VrcVehicle::with(['make', 'model'])
            ->where('business_id', $this->businessId())
            ->where('erp_customer_id', (int) $erpCustomerId)
            ->get()
            ->mapWithKeys(fn ($v) => [$v->id => $v->label]);

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

    /** Dependent dropdown: models for a make (JSON). */
    public function models(Request $request)
    {
        $this->guard('vrc.vehicle.view');
        $models = VrcVehicleModel::where('business_id', $this->businessId())
            ->where('make_id', (int) $request->get('make_id'))
            ->where('is_active', true)
            ->orderBy('name')
            ->pluck('name', 'id');

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

    /** Ownership transfer to another ERP customer (history is preserved). */
    public function transfer(Request $request, $id)
    {
        $this->guard('vrc.vehicle.manage');
        $request->validate(['erp_customer_id' => 'required|integer']);

        try {
            $vehicle = VrcVehicle::where('business_id', $this->businessId())->findOrFail($id);
            $customer = $this->contacts->find($this->businessId(), (int) $request->erp_customer_id);
            if (! $customer) {
                return $this->fail(__('vrc::lang.customer_not_found'));
            }
            // History lives on the repair orders (which keep their own customer
            // snapshot), so re-pointing ownership preserves it.
            $vehicle->update(['erp_customer_id' => $customer->id]);

            return $this->ok(__('vrc::lang.vehicle_transferred'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());
            return $this->fail();
        }
    }

    protected function validateData(Request $request): array
    {
        return $this->validate($request, [
            'erp_customer_id'     => 'required|integer',
            'make_id'             => 'nullable|integer',
            'model_id'            => 'nullable|integer',
            'year'                => 'nullable|integer|min:1900|max:2100',
            'plate_number'        => 'nullable|string|max:30',
            'vin'                 => 'nullable|string|max:40',
            'engine_number'       => 'nullable|string|max:60',
            'color'               => 'nullable|string|max:40',
            'transmission'        => 'nullable|string|max:20',
            'fuel_type'           => 'nullable|string|max:20',
            'odometer'            => 'nullable|integer|min:0',
            'odometer_unit'       => 'nullable|in:km,mi',
            'vehicle_type'        => 'nullable|string|max:40',
            'registration_expiry' => 'nullable|date',
            'insurance_policy_no' => 'nullable|string|max:80',
            'insurance_expiry'    => 'nullable|date',
            'notes'               => 'nullable|string',
        ]);
    }

    protected function formData(?VrcVehicle $vehicle = null): array
    {
        $bid = $this->businessId();

        return [
            'customers' => $this->contacts->customersDropdown($bid),
            'makes'     => VrcVehicleMake::where('business_id', $bid)->where('is_active', true)->orderBy('name')->pluck('name', 'id')->toArray(),
            'models'    => $vehicle && $vehicle->make_id
                ? VrcVehicleModel::where('business_id', $bid)->where('make_id', $vehicle->make_id)->pluck('name', 'id')->toArray()
                : [],
            'transmissions' => ['manual' => __('vrc::lang.manual'), 'automatic' => __('vrc::lang.automatic'), 'cvt' => 'CVT'],
            'fuel_types'    => ['petrol' => __('vrc::lang.petrol'), 'diesel' => __('vrc::lang.diesel'), 'hybrid' => __('vrc::lang.hybrid'), 'electric' => __('vrc::lang.electric')],
        ];
    }
}
