<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\PaymentMethod;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class PaymentMethodController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('permission:fees.view', only: ['index']),
            new Middleware('permission:fees.update', only: ['create', 'store', 'edit', 'update', 'toggle', 'destroy']),
        ];
    }

    public function index(): View
    {
        $methods = PaymentMethod::with('account')->orderBy('sort_order')->orderBy('name')->get();

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

    public function create(): View
    {
        return view('fees.payment-methods.create', [
            'method' => new PaymentMethod(['is_active' => true]),
            'accounts' => $this->cashBankAccounts(),
        ]);
    }

    public function store(Request $request, BranchContext $ctx): RedirectResponse
    {
        $data = $this->validated($request);
        $data['branch_id'] = $ctx->currentId() ?? auth()->user()?->branch_id ?? \App\Models\Branch::min('id');

        PaymentMethod::create($data);

        return redirect()->route('payment-methods.index')->with('success', 'Payment method added.');
    }

    public function edit(PaymentMethod $paymentMethod): View
    {
        return view('fees.payment-methods.edit', [
            'method' => $paymentMethod,
            'accounts' => $this->cashBankAccounts(),
        ]);
    }

    public function update(Request $request, PaymentMethod $paymentMethod): RedirectResponse
    {
        $paymentMethod->update($this->validated($request));

        return redirect()->route('payment-methods.index')->with('success', 'Payment method updated.');
    }

    /** Enable / disable — keeps history but removes it from new-payment options. */
    public function toggle(PaymentMethod $paymentMethod): RedirectResponse
    {
        $paymentMethod->update(['is_active' => ! $paymentMethod->is_active]);

        return back()->with('success', 'Payment method '.($paymentMethod->is_active ? 'enabled' : 'disabled').'.');
    }

    public function destroy(PaymentMethod $paymentMethod): RedirectResponse
    {
        if ($paymentMethod->payments()->exists()) {
            return back()->with('error', 'This method has payments and cannot be deleted. Disable it instead.');
        }
        $paymentMethod->delete();

        return back()->with('success', 'Payment method removed.');
    }

    private function validated(Request $request): array
    {
        return $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'channel' => ['required', 'in:'.implode(',', array_keys(PaymentMethod::CHANNELS))],
            'account_number' => ['nullable', 'string', 'max:60'],
            'account_title' => ['nullable', 'string', 'max:120'],
            'account_id' => ['nullable', 'exists:accounts,id'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);
    }

    private function cashBankAccounts()
    {
        return Account::whereIn('cash_bank', ['cash', 'bank'])->orderBy('code')->get(['id', 'code', 'name', 'cash_bank']);
    }
}
