<?php

namespace App\Http\Controllers\Api;

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

class ChartOfAccountController extends Controller
{
    public function index(Request $request, int $businessId)
    {
        $items = ChartOfAccount::where('business_id', $businessId)->where('is_active', true)->orderBy('code')->get();
        return ApiResponse::success('Chart of accounts', $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([
            'code' => 'nullable|string|max:50',
            'name' => 'nullable|string|max:255',
            'category' => 'nullable|string|max:255',
            'type' => 'nullable|string|max:100',
            'taxType' => 'nullable|string|max:100',
            'description' => 'nullable|string',
            'id' => 'nullable|integer',
        ]);

        $payload = [
            'business_id' => $businessId,
            'code'        => $data['code'] ?? null,
            'name'        => $data['name'] ?? $data['category'] ?? null,
            'type'        => $data['type'] ?? null,
            'tax_type'    => $data['taxType'] ?? null,
            'description' => $data['description'] ?? null,
        ];

        if (empty($payload['name'])) return ApiResponse::error('name is required', null, 422);

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

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

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