<?php

namespace App\Http\Controllers;

use App\Models\Package;
use App\Models\Subscription;
use App\Services\ActionNotificationService;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    /**
     * Display user's subscriptions.
     */
    public function index()
    {
        $user = auth()->user();
        $activeSubscription = $user->getActiveSubscription();

        $subscriptions = $user->subscriptions()
            ->with('package', 'payments')
            ->latest()
            ->paginate(10);

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

    /**
     * Show available packages for selection.
     */
    public function selectPackage()
    {
        $user = auth()->user();
        $activeSubscription = $user->getActiveSubscription();
        $packages = Package::where('is_active', true)
            ->orderBy('driver_limit')
            ->get();

        return view('subscriptions.select-package', compact('packages', 'activeSubscription'));
    }

    /**
     * Create a new subscription for a package.
     */
    public function store(Request $request, ActionNotificationService $notifications)
    {
        $validated = $request->validate([
            'package_id' => 'required|exists:packages,id',
            'trial' => 'sometimes|boolean',
        ]);

        $user = auth()->user();
        $package = Package::findOrFail($validated['package_id']);

        // Check if user already has an active subscription
        $activeSubscription = $user->getActiveSubscription();
        if ($activeSubscription && $activeSubscription->package_id === $package->id) {
            return redirect()->back()
                ->with('info', 'You already have an active subscription for this package');
        }

        $subscriptionData = [
            'package_id' => $package->id,
            'started_at' => now(),
            'last_driver_count' => $user->company?->drivers()->count() ?? 0,
        ];

        if (!empty($validated['trial'])) {
            $subscriptionData = array_merge($subscriptionData, [
                'status' => 'active',
                'payment_status' => 'pending',
                'trial_days' => 7,
                'trial_ends_at' => now()->addDays(7),
                'next_billing_date' => now()->addDays(7),
            ]);
        } else {
            $subscriptionData = array_merge($subscriptionData, [
                'status' => 'pending',
                'payment_status' => 'pending',
            ]);
        }

        $subscription = $user->subscriptions()->create($subscriptionData);

        $notifications->notifyAction(
            'Subscription Created',
            $user,
            [
                'channel' => 'web',
                'package' => $package->name,
                'subscription_id' => $subscription->id,
            ]
        );

        return redirect()->route('payments.checkout', ['subscription' => $subscription->id]);
    }

    /**
     * Show subscription details.
     */
    public function show(Subscription $subscription)
    {
        $this->authorize('view', $subscription);

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

    /**
     * Cancel subscription.
     */
    public function cancel(Subscription $subscription, ActionNotificationService $notifications)
    {
        $this->authorize('update', $subscription);

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

        $notifications->notifyAction(
            'Subscription Cancelled',
            auth()->user(),
            [
                'channel' => 'web',
                'subscription_id' => $subscription->id,
                'package' => $subscription->package?->name,
            ]
        );

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

    /**
     * Renew subscription.
     */
    public function renew(Subscription $subscription, ActionNotificationService $notifications)
    {
        $this->authorize('update', $subscription);

        if ($subscription->status !== 'expired') {
            return redirect()->back()
                ->with('error', 'Only expired subscriptions can be renewed');
        }

        $newSubscription = auth()->user()->subscriptions()->create([
            'package_id' => $subscription->package_id,
            'status' => 'pending',
            'payment_status' => 'pending',
            'started_at' => now(),
        ]);

        $notifications->notifyAction(
            'Subscription Renewed',
            auth()->user(),
            [
                'channel' => 'web',
                'previous_subscription_id' => $subscription->id,
                'new_subscription_id' => $newSubscription->id,
                'package' => $subscription->package?->name,
            ]
        );

        return redirect()->route('payments.checkout', ['subscription' => $newSubscription->id]);
    }

    /**
     * Download subscription invoice.
     */
    public function invoice(Subscription $subscription)
    {
        $this->authorize('view', $subscription);

        // Generate and return PDF invoice
        // This will be implemented with a PDF library like DOMPDF or TCPDF
        return response()->download('subscription-invoice-' . $subscription->id . '.pdf');
    }
}
