<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\CryptoPaymentTransaction;
use App\Models\SubscriptionPlan;
use App\Models\UserSubscription;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class AdvancedPaymentController extends Controller
{
    public function index(): View
    {
        return view('admin.advanced-payments', [
            'cryptoTransactions' => CryptoPaymentTransaction::query()->latest('id')->paginate(20, ['*'], 'crypto_page'),
            'plans' => SubscriptionPlan::query()->orderBy('name')->get(),
            'subscriptions' => UserSubscription::query()->latest('id')->paginate(20, ['*'], 'sub_page'),
        ]);
    }

    public function storeSubscriptionPlan(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:191'],
            'code' => ['required', 'string', 'max:60'],
            'amount' => ['required', 'numeric', 'min:0'],
            'currency' => ['required', 'string', 'max:10'],
            'interval_days' => ['required', 'integer', 'min:1'],
        ]);

        SubscriptionPlan::query()->updateOrCreate(
            ['code' => strtoupper($validated['code'])],
            [
                'name' => $validated['name'],
                'amount' => (float) $validated['amount'],
                'currency' => strtoupper($validated['currency']),
                'interval_days' => (int) $validated['interval_days'],
                'is_active' => true,
            ]
        );

        return back()->with('status', 'Subscription plan saved.');
    }

    public function toggleSubscriptionPlan(int $planId): RedirectResponse
    {
        $plan = SubscriptionPlan::query()->findOrFail($planId);
        $plan->is_active = ! $plan->is_active;
        $plan->save();

        return back()->with('status', 'Subscription plan status updated.');
    }

    public function updateCryptoStatus(Request $request, int $transactionId): RedirectResponse
    {
        $validated = $request->validate([
            'status' => ['required', 'in:initiated,pending,confirmed,failed,refunded'],
        ]);

        $txn = CryptoPaymentTransaction::query()->findOrFail($transactionId);
        $txn->status = $validated['status'];
        if ($validated['status'] === 'confirmed') {
            $txn->confirmed_at = now();
        }
        $txn->save();

        return back()->with('status', 'Crypto payment status updated.');
    }
}
