<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Business;
use App\Models\BusinessSubscription;
use App\Models\SubscriptionPlan;
use Illuminate\Http\Request;

class AdminSubscriptionController extends Controller
{
    /**
     * Display all business subscriptions
     */
    public function index(Request $request)
    {
        $query = BusinessSubscription::with(['business', 'plan']);

        // Filter by search
        if ($request->search) {
            $query->whereHas('business', function ($q) {
                $q->where('business_name', 'like', '%' . request('search') . '%')
                  ->orWhere('email', 'like', '%' . request('search') . '%');
            });
        }

        // Filter by status
        if ($request->status) {
            $query->where('status', $request->status);
        }

        // Filter by tier
        if ($request->tier) {
            $query->whereHas('plan', function ($q) {
                $q->where('tier', request('tier'));
            });
        }

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

        $stats = [
            'active' => BusinessSubscription::where('status', 'active')->where('end_date', '>', now())->count(),
            'expiring_soon' => BusinessSubscription::where('status', 'active')
                ->whereBetween('end_date', [now(), now()->addDays(7)])
                ->count(),
            'trial' => BusinessSubscription::where('status', 'trial')->count(),
            'monthly_revenue' => BusinessSubscription::where('status', 'active')
                ->where('end_date', '>', now())
                ->with('plan')
                ->get()
                ->sum(function ($sub) {
                    return $sub->plan->price;
                }),
        ];

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

    /**
     * Get subscription usage
     */
    public function getUsage($businessId)
    {
        $business = Business::findOrFail($businessId);
        $usage = $business->getSubscriptionUsage();

        return response()->json([
            'success' => true,
            'usage' => $usage,
        ]);
    }

    /**
     * Cancel subscription
     */
    public function cancel($subscriptionId, Request $request)
    {
        $subscription = BusinessSubscription::findOrFail($subscriptionId);

        $subscription->update([
            'status' => 'cancelled',
            'cancelled_at' => now(),
            'cancellation_reason' => $request->reason ?? null,
        ]);

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

    /**
     * Edit subscription
     */
    public function edit($subscriptionId)
    {
        $subscription = BusinessSubscription::with(['business', 'plan'])->findOrFail($subscriptionId);
        $plans = SubscriptionPlan::where('type', 'business')->where('is_active', true)->get();

        return view('admin.subscriptions.edit', compact('subscription', 'plans'));
    }

    /**
     * Update subscription
     */
    public function update($subscriptionId, Request $request)
    {
        $subscription = BusinessSubscription::findOrFail($subscriptionId);

        $validated = $request->validate([
            'subscription_plan_id' => 'required|exists:subscription_plans,id',
            'status' => 'required|in:trial,active,paused,cancelled',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'auto_renew' => 'boolean',
        ]);

        $subscription->update($validated);

        return redirect()->route('admin.subscriptions.index')
                       ->with('success', 'Subscription updated successfully');
    }

    /**
     * Renew subscription
     */
    public function renew($subscriptionId)
    {
        $subscription = BusinessSubscription::findOrFail($subscriptionId);

        $endDate = $subscription->end_date->addDays($subscription->plan->duration_days ?? 30);

        $subscription->update([
            'end_date' => $endDate,
            'next_billing_date' => $endDate,
            'status' => 'active',
        ]);

        return redirect()->back()->with('success', 'Subscription renewed successfully');
    }
}

