<?php

namespace App\Http\Controllers\Owner;

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

class PaymentMethodController extends Controller
{
    public function index(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        $canManage = $organizationId > 0;

        $methods = $canManage
            ? PaymentMethod::query()
                ->where('organization_id', $organizationId)
                ->orderBy('sort_order')
                ->orderBy('name')
                ->get()
            : collect();

        return view('content.owner.settings.payments.index', [
            'canManagePayments' => $canManage,
            'methods' => $methods,
            'stats' => [
                'total' => $methods->count(),
                'active' => $methods->where('is_active', true)->count(),
                'default' => $methods->where('is_default', true)->count(),
            ],
        ]);
    }

    public function store(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if ($organizationId <= 0) {
            return redirect()->route('owner.settings.payments')->withErrors([
                'name' => 'Primero debes tener una organización asignada.',
            ]);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'account_holder' => ['nullable', 'string', 'max:120'],
            'account_reference' => ['nullable', 'string', 'max:160'],
            'payment_details' => ['nullable', 'string', 'max:1200'],
            'is_active' => ['required', 'boolean'],
            'is_default' => ['required', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        if ((bool) $validated['is_default']) {
            PaymentMethod::query()
                ->where('organization_id', $organizationId)
                ->update(['is_default' => false]);
        }

        PaymentMethod::create([
            'organization_id' => $organizationId,
            'name' => $validated['name'],
            'account_holder' => trim((string) ($validated['account_holder'] ?? '')) ?: null,
            'account_reference' => trim((string) ($validated['account_reference'] ?? '')) ?: null,
            'payment_details' => trim((string) ($validated['payment_details'] ?? '')) ?: null,
            'is_active' => (bool) $validated['is_active'],
            'is_default' => (bool) $validated['is_default'],
            'sort_order' => (int) ($validated['sort_order'] ?? 100),
        ]);

        return redirect()->route('owner.settings.payments')->with('status', 'Método de pago creado correctamente.');
    }

    public function update(Request $request, PaymentMethod $paymentMethod)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if ($organizationId <= 0 || $paymentMethod->organization_id !== $organizationId) {
            abort(404);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'account_holder' => ['nullable', 'string', 'max:120'],
            'account_reference' => ['nullable', 'string', 'max:160'],
            'payment_details' => ['nullable', 'string', 'max:1200'],
            'is_active' => ['required', 'boolean'],
            'is_default' => ['required', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        if ((bool) $validated['is_default']) {
            PaymentMethod::query()
                ->where('organization_id', $organizationId)
                ->where('id', '!=', $paymentMethod->id)
                ->update(['is_default' => false]);
        }

        $paymentMethod->update([
            'name' => $validated['name'],
            'account_holder' => trim((string) ($validated['account_holder'] ?? '')) ?: null,
            'account_reference' => trim((string) ($validated['account_reference'] ?? '')) ?: null,
            'payment_details' => trim((string) ($validated['payment_details'] ?? '')) ?: null,
            'is_active' => (bool) $validated['is_active'],
            'is_default' => (bool) $validated['is_default'],
            'sort_order' => (int) ($validated['sort_order'] ?? $paymentMethod->sort_order),
        ]);

        return redirect()->route('owner.settings.payments')->with('status', 'Método de pago actualizado correctamente.');
    }

    public function destroy(Request $request, PaymentMethod $paymentMethod)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if ($organizationId <= 0 || $paymentMethod->organization_id !== $organizationId) {
            abort(404);
        }

        $paymentMethod->delete();

        return redirect()->route('owner.settings.payments')->with('status', 'Método de pago eliminado correctamente.');
    }
}
