<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\CorporateVehicle;
use App\Models\VehicleMaintenance;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class VehicleMaintenanceController extends Controller
{
    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('finance.vehicle-maintenance'));
        }

        return view('finance.vehicle-maintenance');
    }

    /**
     * 차량 목록 조회
     */
    public function vehicles(Request $request): JsonResponse
    {
        $tenantId = session('tenant_id', 1);

        $vehicles = CorporateVehicle::where('tenant_id', $tenantId)
            ->orderBy('plate_number')
            ->get();

        return response()->json([
            'success' => true,
            'data' => $vehicles,
        ]);
    }

    /**
     * 정비 이력 목록 조회
     */
    public function list(Request $request): JsonResponse
    {
        $tenantId = session('tenant_id', 1);

        $query = VehicleMaintenance::with('vehicle')
            ->where('tenant_id', $tenantId);

        // 차량 필터
        if ($request->filled('vehicle_id') && $request->vehicle_id !== 'all') {
            $query->where('vehicle_id', $request->vehicle_id);
        }

        // 카테고리 필터
        if ($request->filled('category') && $request->category !== 'all') {
            $query->where('category', $request->category);
        }

        // 날짜 범위 필터
        if ($request->filled('start_date')) {
            $query->whereDate('date', '>=', $request->start_date);
        }
        if ($request->filled('end_date')) {
            $query->whereDate('date', '<=', $request->end_date);
        }

        // 검색어
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                    ->orWhere('vendor', 'like', "%{$search}%")
                    ->orWhere('memo', 'like', "%{$search}%");
            });
        }

        $maintenances = $query->orderBy('date', 'desc')->get();

        // 응답 포맷팅
        $data = $maintenances->map(function ($m) {
            return [
                'id' => $m->id,
                'date' => $m->date->format('Y-m-d'),
                'vehicleId' => $m->vehicle_id,
                'plateNumber' => $m->vehicle?->plate_number,
                'model' => $m->vehicle?->model,
                'category' => $m->category,
                'description' => $m->description,
                'amount' => $m->amount,
                'mileage' => $m->mileage,
                'vendor' => $m->vendor,
                'memo' => $m->memo,
            ];
        });

        return response()->json([
            'success' => true,
            'data' => $data,
        ]);
    }

    /**
     * 정비 이력 등록
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'vehicle_id' => 'required|exists:corporate_vehicles,id',
            'date' => 'required|date',
            'category' => 'required|string|max:20',
            'amount' => 'required|numeric|min:0',
        ]);

        $tenantId = session('tenant_id', 1);

        $maintenance = VehicleMaintenance::create([
            'tenant_id' => $tenantId,
            'vehicle_id' => $request->vehicle_id,
            'date' => $request->date,
            'category' => $request->category,
            'description' => $request->description,
            'amount' => $request->amount ?? 0,
            'mileage' => $request->mileage,
            'vendor' => $request->vendor,
            'memo' => $request->memo,
        ]);

        // 차량 주행거리 업데이트
        if ($request->filled('mileage')) {
            CorporateVehicle::where('id', $request->vehicle_id)
                ->where('tenant_id', $tenantId)
                ->update(['mileage' => $request->mileage]);
        }

        return response()->json([
            'success' => true,
            'message' => '정비 이력이 등록되었습니다.',
            'data' => $maintenance,
        ]);
    }

    /**
     * 정비 이력 수정
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $tenantId = session('tenant_id', 1);

        $maintenance = VehicleMaintenance::where('tenant_id', $tenantId)->findOrFail($id);

        $request->validate([
            'vehicle_id' => 'required|exists:corporate_vehicles,id',
            'date' => 'required|date',
            'category' => 'required|string|max:20',
            'amount' => 'required|numeric|min:0',
        ]);

        $maintenance->update([
            'vehicle_id' => $request->vehicle_id,
            'date' => $request->date,
            'category' => $request->category,
            'description' => $request->description,
            'amount' => $request->amount ?? 0,
            'mileage' => $request->mileage,
            'vendor' => $request->vendor,
            'memo' => $request->memo,
        ]);

        // 차량 주행거리 업데이트
        if ($request->filled('mileage')) {
            CorporateVehicle::where('id', $request->vehicle_id)
                ->where('tenant_id', $tenantId)
                ->update(['mileage' => $request->mileage]);
        }

        return response()->json([
            'success' => true,
            'message' => '정비 이력이 수정되었습니다.',
            'data' => $maintenance,
        ]);
    }

    /**
     * 정비 이력 삭제
     */
    public function destroy(int $id): JsonResponse
    {
        $tenantId = session('tenant_id', 1);

        $maintenance = VehicleMaintenance::where('tenant_id', $tenantId)->findOrFail($id);
        $maintenance->delete();

        return response()->json([
            'success' => true,
            'message' => '정비 이력이 삭제되었습니다.',
        ]);
    }
}
