<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Device;
use App\Models\UserSubscription;
use App\Services\FirebasePushService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class SubscriptionsController extends Controller
{
    private const PERIOD_DAYS = [
        'monthly'   => 31,
        'quarterly' => 92,
        'biannual'  => 183,
        'yearly'    => 366,
        'lifetime'  => null, // no expiry
    ];

    public function index(Request $request): View
    {
        $subscriptions = UserSubscription::with('user:id,name,email')
            ->when($request->plan, fn($q) => $q->where('plan', $request->plan))
            ->when($request->source, fn($q) => $q->where('source', $request->source))
            ->when($request->q, fn($q) => $q->whereHas('user', fn($u) =>
                $u->where('email', 'like', "%{$request->q}%")->orWhere('name', 'like', "%{$request->q}%")
            ))
            ->latest()
            ->paginate(25)
            ->withQueryString();

        $stats = [
            'total'          => UserSubscription::count(),
            'active'         => UserSubscription::where('is_active', true)->where(fn($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))->count(),
            'expired'        => UserSubscription::where('expires_at', '<', now())->count(),
            'revenue'        => UserSubscription::whereNotNull('amount_paid')->sum('amount_paid'),
            'crypto_pending' => UserSubscription::where('source', 'crypto')->where('payment_status', 'pending')->count(),
        ];

        return view('admin.subscriptions.index', compact('subscriptions', 'stats'));
    }

    public function approveCrypto(UserSubscription $subscription): RedirectResponse
    {
        if ($subscription->source !== 'crypto' || $subscription->payment_status !== 'pending') {
            return back()->with('error', 'This subscription is not awaiting crypto approval.');
        }

        $days      = self::PERIOD_DAYS[$subscription->period] ?? null;
        $expiresAt = ($days === null) ? null : now()->addDays($days);

        $subscription->update([
            'is_active'      => true,
            'payment_status' => 'approved',
            'starts_at'      => now(),
            'expires_at'     => $expiresAt,
        ]);

        $user = $subscription->user;
        if ($user) {
            $user->update([
                'plan'            => $subscription->plan,
                'plan_expires_at' => $expiresAt,
                'plan_source'     => 'crypto',
            ]);

            app(FirebasePushService::class)->sendFromTemplate('subscription_activated', $user);
        }

        return back()->with('success', 'Crypto payment approved and plan activated.');
    }

    public function rejectCrypto(UserSubscription $subscription): RedirectResponse
    {
        if ($subscription->source !== 'crypto' || $subscription->payment_status !== 'pending') {
            return back()->with('error', 'This subscription is not awaiting crypto approval.');
        }

        $subscription->update([
            'is_active'      => false,
            'payment_status' => 'rejected',
        ]);

        $user = $subscription->user;
        if ($user) {
            $this->notifyUser(
                $user->id,
                'Crypto Payment Not Verified',
                'Your crypto payment could not be verified. Please contact support.',
                ['type' => 'subscription_rejected']
            );
        }

        return back()->with('error', 'Crypto payment rejected.');
    }

    public function cancelSubscription(UserSubscription $subscription): RedirectResponse
    {
        if (!$subscription->is_active) {
            return back()->with('error', 'This subscription is already inactive.');
        }

        $subscription->update([
            'is_active'      => false,
            'payment_status' => 'cancelled',
        ]);

        $user = $subscription->user;
        if ($user && $user->plan === $subscription->plan) {
            $otherActive = UserSubscription::where('user_id', $user->id)
                ->where('id', '!=', $subscription->id)
                ->where('is_active', true)
                ->where(fn($q) => $q->whereNull('expires_at')->orWhere('expires_at', '>', now()))
                ->first();

            if (!$otherActive) {
                $user->update(['plan' => 'free', 'plan_expires_at' => null]);
            }
        }

        return back()->with('success', 'Subscription cancelled.');
    }

    private function notifyUser(int|string $userId, string $title, string $body, array $data = []): void
    {
        $tokens = Device::where('user_id', $userId)
            ->whereNotNull('fcm_token')
            ->where('fcm_token', '!=', '')
            ->where('is_revoked', false)
            ->pluck('fcm_token');

        if ($tokens->isEmpty()) {
            return;
        }

        $push = app(FirebasePushService::class);
        foreach ($tokens as $token) {
            $push->sendToToken($token, $title, $body, $data);
        }
    }
}
