<?php

namespace App\Http\Controllers;

use App\Services\PaymentManagementService;
use Illuminate\Http\Request;

class PaymentManagementController extends Controller
{
    public function __construct(private PaymentManagementService $service) {}

    public function index()
    {
        return view('admin.payment-management', $this->service->overview());
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'convenience_fee_type' => ['required', 'in:fixed,percentage'],
            'convenience_fee_value' => ['required', 'numeric', 'min:0', 'max:999999'],
            'platform_fee_percentage' => ['required', 'numeric', 'min:0', 'max:100'],
            'is_active' => ['required', 'boolean'],
        ]);

        if ($data['convenience_fee_type'] === 'percentage' && $data['convenience_fee_value'] > 100) {
            return back()->withInput()->withErrors(['convenience_fee_value' => 'The percentage convenience fee cannot exceed 100%.']);
        }

        $this->service->updateSetting($data);

        return back()->with('success', 'Payment fees updated. The new rates will apply to newly created checkouts.');
    }
}
