<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Subscription;
use App\Models\SubscriptionPlan;
// use Illuminate\Http\RedirectResponse;
// use Illuminate\Support\Facades\Crypt;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SubscriptionController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();

        $plans = SubscriptionPlan::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('price')
            ->get();

        $activeSubscription = Subscription::with('plan')
            ->where('user_id', $user->id)
            ->where('status', 'active')
            ->where(function ($query) {
                $query->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            })
            ->latest()
            ->first();

        $pendingSubscription = Subscription::with('plan')
            ->where('user_id', $user->id)
            ->where('status', 'pending')
            ->latest()
            ->first();

        return view('user.subscriptions.index', compact(
            'plans',
            'activeSubscription',
            'pendingSubscription'
        ));
    }

    public function show(Request $request, SubscriptionPlan $plan): View
    {
        abort_unless($plan->is_active, 404);

        $activeSubscription = Subscription::with('plan')
            ->where('user_id', $request->user()->id)
            ->where('status', 'active')
            ->where(function ($query) {
                $query->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            })
            ->latest()
            ->first();

        return view('user.subscriptions.show', compact('plan', 'activeSubscription'));
    }

    public function subscribe(Request $request, SubscriptionPlan $plan)
    {
        abort_unless($plan->is_active, 404);

        $user = $request->user();

        $activeSubscription = Subscription::with('plan')
            ->where('user_id', $user->id)
            ->where('status', 'active')
            ->where(function ($query) {
                $query->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            })
            ->latest()
            ->first();

        if ($activeSubscription) {
            $currentPrice = (float) $activeSubscription->plan?->price;
            $newPrice = (float) $plan->price;

            if ($newPrice <= $currentPrice) {
                return $request->expectsJson()
                    ? response()->json([
                        'status' => false,
                        'message' => $newPrice === $currentPrice
                            ? 'You are already on this plan.'
                            : 'You cannot downgrade while your current subscription is active.',
                    ], 422)
                    : redirect()->route('user.subscriptions.index')
                        ->with('error', $newPrice === $currentPrice
                            ? 'You are already on this plan.'
                            : 'You cannot downgrade while your current subscription is active.');
            }

            // Allow upgrade to higher plan
        }

        $pendingSubscription = Subscription::with('plan')
            ->where('user_id', $user->id)
            ->where('status', 'pending')
            ->latest()
            ->first();

        if ($pendingSubscription) {
            $encryptedId = encrypt($pendingSubscription->id);

            $message = $pendingSubscription->plan_id === $plan->id
                ? 'You already have a pending subscription for this plan. Complete payment to continue.'
                : 'You already have a pending subscription. Please complete or cancel it before choosing another plan.';

            return $request->expectsJson()
                ? response()->json([
                    'status' => true,
                    'message' => $message,
                    'redirect' => route('user.payments.show', $encryptedId),
                ])
                : redirect()->route('user.payments.show', $encryptedId)
                    ->with('info', $message);
        }

        $subscription = Subscription::create([
            'user_id' => $user->id,
            'plan_id' => $plan->id,
            'payment_id' => null,
            'starts_at' => null,
            'expires_at' => null,
            'status' => 'pending',
            'amount' => $plan->price,
            'currency' => $plan->currency,
        ]);

        $encryptedId = encrypt($subscription->id);

        $redirectUrl = route('user.payments.show', $encryptedId);

        return $request->expectsJson()
            ? response()->json([
                'status' => true,
                'message' => 'Redirecting to payment...',
                'redirect' => $redirectUrl,
            ])
            : redirect($redirectUrl);
    }

    public function history(Request $request): View
    {
        $subscriptions = Subscription::with(['plan', 'payment'])
            ->where('user_id', $request->user()->id)
            ->latest()
            ->paginate(15);

        return view('user.subscriptions.history', compact('subscriptions'));
    }
}