<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ManualPaymentMethod;
use App\Services\AuditLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ManualPaymentMethodController extends Controller
{
    public function __construct(private AuditLogger $auditLogger) {}

    public function index(): View
    {
        $methods = ManualPaymentMethod::orderBy('sort_order')->orderBy('name')->paginate(20);

        return view('admin.payment-methods.index', compact('methods'));
    }

    public function create(): View
    {
        return view('admin.payment-methods.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $this->validateMethod($request);
        $method = ManualPaymentMethod::create($validated);
        $this->auditLogger->log('payment_method.created', $method, null, $method->toArray());

        return redirect()
            ->route('admin.payment-methods.index')
            ->with('success', __('admin.actions.save'));
    }

    public function edit(ManualPaymentMethod $paymentMethod): View
    {
        return view('admin.payment-methods.edit', ['method' => $paymentMethod]);
    }

    public function update(Request $request, ManualPaymentMethod $paymentMethod): RedirectResponse
    {
        $validated = $this->validateMethod($request);
        $old = $paymentMethod->toArray();
        $paymentMethod->update($validated);
        $this->auditLogger->log('payment_method.updated', $paymentMethod, $old, $paymentMethod->fresh()->toArray());

        return back()->with('success', __('admin.actions.update'));
    }

    public function destroy(ManualPaymentMethod $paymentMethod): RedirectResponse
    {
        $old = $paymentMethod->toArray();
        $paymentMethod->delete();
        $this->auditLogger->log('payment_method.deleted', null, $old, null);

        return redirect()
            ->route('admin.payment-methods.index')
            ->with('success', __('admin.actions.delete'));
    }

    private function validateMethod(Request $request): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'type' => ['required', 'string', 'max:100'],
            'instructions' => ['nullable', 'string'],
            'account_name' => ['nullable', 'string', 'max:255'],
            'account_identifier' => ['nullable', 'string', 'max:255'],
            'is_active' => ['sometimes', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);
    }
}
