<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\CorporateVehicle;
use App\Models\VehicleLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

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

        return view('finance.corporate-vehicles');
    }

    public function list(Request $request): JsonResponse
    {
        $tenantId = session('tenant_id', 1);

        $query = CorporateVehicle::where('tenant_id', $tenantId);

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

        if ($request->filled('vehicle_type') && $request->vehicle_type !== 'all') {
            $query->where('vehicle_type', $request->vehicle_type);
        }

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('plate_number', 'like', "%{$search}%")
                    ->orWhere('model', 'like', "%{$search}%")
                    ->orWhere('driver', 'like', "%{$search}%");
            });
        }

        $vehicles = $query->orderBy('created_at', 'desc')->get();

        // 각 차량의 운행기록 주행거리 합계 조회
        $vehicleIds = $vehicles->pluck('id');
        $logDistances = VehicleLog::whereIn('vehicle_id', $vehicleIds)
            ->select('vehicle_id', DB::raw('SUM(distance_km) as total_log_distance'))
            ->groupBy('vehicle_id')
            ->pluck('total_log_distance', 'vehicle_id');

        // total_mileage = 초기 주행거리 + 운행기록 합계
        $vehicles->each(function ($vehicle) use ($logDistances) {
            $vehicle->log_distance = (int) ($logDistances[$vehicle->id] ?? 0);
            $vehicle->total_mileage = ($vehicle->mileage ?? 0) + $vehicle->log_distance;
        });

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

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'plate_number' => 'required|string|max:20',
            'model' => 'required|string|max:100',
            'vehicle_type' => 'required|string|max:20',
            'ownership_type' => 'required|in:corporate,rent,lease',
        ]);

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

        $vehicle = CorporateVehicle::create([
            'tenant_id' => $tenantId,
            'plate_number' => $request->plate_number,
            'model' => $request->model,
            'vehicle_type' => $request->vehicle_type,
            'ownership_type' => $request->ownership_type,
            'year' => $request->year,
            'driver' => $request->driver,
            'status' => $request->status ?? 'active',
            'mileage' => $request->mileage ?? 0,
            'memo' => $request->memo,
            // 법인차량 전용
            'purchase_date' => $request->purchase_date,
            'purchase_price' => $request->purchase_price ?? 0,
            // 렌트/리스 전용
            'contract_date' => $request->contract_date,
            'rent_company' => $request->rent_company,
            'rent_company_tel' => $request->rent_company_tel,
            'rent_period' => $request->rent_period,
            'agreed_mileage' => $request->agreed_mileage,
            'vehicle_price' => $request->vehicle_price ?? 0,
            'residual_value' => $request->residual_value ?? 0,
            'deposit' => $request->deposit ?? 0,
            'monthly_rent' => $request->monthly_rent ?? 0,
            'monthly_rent_tax' => $request->monthly_rent_tax ?? 0,
            'insurance_company' => $request->insurance_company,
            'insurance_company_tel' => $request->insurance_company_tel,
        ]);

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

    public function update(Request $request, int $id): JsonResponse
    {
        $tenantId = session('tenant_id', 1);

        $vehicle = CorporateVehicle::where('tenant_id', $tenantId)->findOrFail($id);

        $request->validate([
            'plate_number' => 'required|string|max:20',
            'model' => 'required|string|max:100',
            'vehicle_type' => 'required|string|max:20',
            'ownership_type' => 'required|in:corporate,rent,lease',
        ]);

        $vehicle->update([
            'plate_number' => $request->plate_number,
            'model' => $request->model,
            'vehicle_type' => $request->vehicle_type,
            'ownership_type' => $request->ownership_type,
            'year' => $request->year,
            'driver' => $request->driver,
            'status' => $request->status ?? 'active',
            'mileage' => $request->mileage ?? 0,
            'memo' => $request->memo,
            // 법인차량 전용
            'purchase_date' => $request->purchase_date,
            'purchase_price' => $request->purchase_price ?? 0,
            // 렌트/리스 전용
            'contract_date' => $request->contract_date,
            'rent_company' => $request->rent_company,
            'rent_company_tel' => $request->rent_company_tel,
            'rent_period' => $request->rent_period,
            'agreed_mileage' => $request->agreed_mileage,
            'vehicle_price' => $request->vehicle_price ?? 0,
            'residual_value' => $request->residual_value ?? 0,
            'deposit' => $request->deposit ?? 0,
            'monthly_rent' => $request->monthly_rent ?? 0,
            'monthly_rent_tax' => $request->monthly_rent_tax ?? 0,
            'insurance_company' => $request->insurance_company,
            'insurance_company_tel' => $request->insurance_company_tel,
        ]);

        return response()->json([
            'success' => true,
            'message' => '차량 정보가 수정되었습니다.',
            'data' => $vehicle,
        ]);
    }

    public function destroy(int $id): JsonResponse
    {
        $tenantId = session('tenant_id', 1);

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

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