<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Services\Care\CarePermissions;
use App\Services\Care\CarePricingService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SettingsGpPricingController extends Controller
{
    use ScopesToAccount;

    public function edit(Request $request, CarePricingService $pricing): View
    {
        $this->authorizeAbility($request, 'settings.view');
        $organization = $this->organization($request);
        $canManage = app(CarePermissions::class)->can($this->member($request), 'settings.manage');

        return view('care.settings.gp-pricing', [
            'organization' => $organization,
            'services' => $pricing->gpServices($organization),
            'canManage' => $canManage,
            'currency' => strtoupper((string) config('care.billing.currency', 'GHS')),
        ]);
    }

    public function update(Request $request, CarePricingService $pricing): RedirectResponse
    {
        $this->authorizeAbility($request, 'settings.manage');
        $organization = $this->organization($request);

        $validated = $request->validate([
            'services' => ['required', 'array'],
            'services.*.code' => ['required', 'string', 'max:64'],
            'services.*.amount' => ['required', 'numeric', 'min:0', 'max:999999'],
        ]);

        $pricing->updateGpServices($organization, $validated['services']);

        return redirect()
            ->route('care.settings.gp-pricing')
            ->with('success', 'GP service prices saved.');
    }
}
