<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Subscription;
use App\Models\SubscriptionPlan;
use App\Models\Payment;
use Illuminate\Http\Request;

class UserSubscriptionController extends Controller
{
    /**
     * Display user subscriptions listing
     */
    public function index(Request $request)
    {
        $status = $request->get('status', 'all');

        $query = Subscription::whereHas('plan', function($q) {
            $q->where('type', 'user');
        })->with(['plan', 'user']);

        if ($status !== 'all') {
            $query->where('status', $status);
        }

        $subscriptions = $query->orderBy('created_at', 'desc')->paginate(20);

        $stats = [
            'total' => Subscription::whereHas('plan', function($q) {
                $q->where('type', 'user');
            })->count(),
            'active' => Subscription::whereHas('plan', function($q) {
                $q->where('type', 'user');
            })->where('status', 'active')->count(),
            'expired' => Subscription::whereHas('plan', function($q) {
                $q->where('type', 'user');
            })->where('status', 'expired')->count(),
            'cancelled' => Subscription::whereHas('plan', function($q) {
                $q->where('type', 'user');
            })->where('status', 'cancelled')->count(),
            'monthly_revenue' => Payment::where('status', 'completed')
                ->where('type', 'subscription')
                ->whereHas('subscription.plan', function($q) {
                    $q->where('type', 'user');
                })
                ->whereMonth('created_at', now()->month)
                ->sum('amount'),
        ];

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

    /**
     * Show subscription details
     */
    public function show($id)
    {
        $subscription = Subscription::whereHas('plan', function($q) {
            $q->where('type', 'user');
        })
            ->with(['plan', 'user', 'payments'])
            ->findOrFail($id);

        return view('admin.user-subscriptions.show', compact('subscription'));
    }

    /**
     * Cancel subscription
     */
    public function cancel($id)
    {
        $subscription = Subscription::whereHas('plan', function($q) {
            $q->where('type', 'user');
        })->findOrFail($id);

        $subscription->update([
            'status' => 'cancelled',
            'cancelled_at' => now(),
        ]);

        // Create notification
        \App\Models\Notification::create([
            'notifiable_type' => 'App\\Models\\User',
            'notifiable_id' => $subscription->user_id,
            'type' => 'subscription_cancelled',
            'data' => json_encode([
                'title' => 'Subscription Cancelled',
                'message' => 'Your subscription has been cancelled by administrator.',
                'subscription_id' => $subscription->id
            ])
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Subscription cancelled successfully'
        ]);
    }

    /**
     * Activate subscription
     */
    public function activate($id)
    {
        $subscription = Subscription::whereHas('plan', function($q) {
            $q->where('type', 'user');
        })->findOrFail($id);

        $subscription->update([
            'status' => 'active',
            'cancelled_at' => null,
        ]);

        // Create notification
        \App\Models\Notification::create([
            'notifiable_type' => 'App\\Models\\User',
            'notifiable_id' => $subscription->user_id,
            'type' => 'subscription_activated',
            'data' => json_encode([
                'title' => 'Subscription Activated',
                'message' => 'Your subscription has been activated.',
                'subscription_id' => $subscription->id
            ])
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Subscription activated successfully'
        ]);
    }

    /**
     * Get subscription stats for analytics
     */
    public function analytics()
    {
        $userPlans = SubscriptionPlan::where('type', 'user')
            ->where('is_active', true)
            ->withCount(['subscriptions', 'activeSubscriptions'])
            ->get();

        $monthlyStats = [];
        for ($i = 11; $i >= 0; $i--) {
            $date = now()->subMonths($i);
            $monthlyStats[] = [
                'month' => $date->format('M Y'),
                'subscriptions' => Subscription::whereHas('plan', function($q) {
                    $q->where('type', 'user');
                })
                    ->whereYear('created_at', $date->year)
                    ->whereMonth('created_at', $date->month)
                    ->count(),
                'revenue' => Payment::where('status', 'completed')
                    ->where('type', 'subscription')
                    ->whereHas('subscription.plan', function($q) {
                        $q->where('type', 'user');
                    })
                    ->whereYear('created_at', $date->year)
                    ->whereMonth('created_at', $date->month)
                    ->sum('amount'),
            ];
        }

        return view('admin.user-subscriptions.analytics', compact('userPlans', 'monthlyStats'));
    }
}
