<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\VatGstRate;
use App\Support\ApiResponse;
use Illuminate\Http\Request;

class VatGstRateController extends Controller
{
    public function index(Request $request, int $businessId)
    {
        $items = VatGstRate::where('business_id', $businessId)->where('is_active', true)->orderBy('name')->get();
        return ApiResponse::success('VAT/GST rates', $items);
    }

    public function store(Request $request, ?int $businessId = null)
    {
        $businessId = $businessId ?: (int) ($request->input('businessId') ?? $request->input('business_id') ?? 0);
        if (!$businessId) return ApiResponse::error('businessId is required', null, 422);

        $data = $request->validate([
            'name' => 'required|string|max:255',
            'rate' => 'nullable|numeric',
            'percentage' => 'nullable|numeric',
            'type' => 'nullable|string|max:100',
            'id' => 'nullable|integer',
        ]);

        $payload = [
            'business_id' => $businessId,
            'name'        => $data['name'],
            'rate'        => $data['rate'] ?? $data['percentage'] ?? 0,
            'type'        => $data['type'] ?? null,
        ];

        if (!empty($data['id'])) {
            $item = VatGstRate::where('business_id', $businessId)->findOrFail($data['id']);
            $item->update($payload);
            return ApiResponse::success('Rate updated', $item);
        }
        $item = VatGstRate::create($payload);
        return ApiResponse::success('Rate created', $item);
    }

    public function update(Request $request, int $businessId, int $id)
    {
        $item = VatGstRate::where('business_id', $businessId)->findOrFail($id);
        $item->update($request->only(['name', 'rate', 'type', 'is_active']));
        return ApiResponse::success('Rate updated', $item);
    }

    public function destroy(Request $request, int $businessId, int $id)
    {
        $item = VatGstRate::where('business_id', $businessId)->findOrFail($id);
        $item->is_active = false;
        $item->save();
        return ApiResponse::success('Rate removed');
    }
}
