<?php

namespace App\Http\Controllers\Api;

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

class PaymentMethodController extends Controller
{
    public function index(Request $request, int $businessId)
    {
        $items = PaymentMethod::where('business_id', $businessId)->where('is_active', true)->orderBy('name')->get();
        return ApiResponse::success('Payment methods', $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' => 'nullable|string|max:255',
            'displayName' => 'nullable|string|max:255',
            'type' => 'nullable|string|max:100',
            'paymentType' => 'nullable|string|max:100',
            'accountNumber' => 'nullable|string|max:100',
            'bankName' => 'nullable|string|max:255',
            'id' => 'nullable|integer',
        ]);

        $name = $data['name'] ?? $data['displayName'] ?? null;
        if (!$name) return ApiResponse::error('name is required', null, 422);

        $payload = [
            'business_id'    => $businessId,
            'name'           => $name,
            'type'           => $data['type'] ?? $data['paymentType'] ?? null,
            'account_number' => $data['accountNumber'] ?? null,
            'bank_name'      => $data['bankName'] ?? null,
        ];

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

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

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