<?php

namespace App\Http\Controllers\API\V1\Subscription;

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

class SubscriptionController extends Controller
{
    /**
     * Get available subscription plans for users
     */
    public function plans()
    {
        $plans = SubscriptionPlan::where('is_active', true)
            ->where('type','user')
            ->orderBy('sort_order')
            ->orderBy('price')
            ->get();

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

    /**
     * Subscribe to a plan
     */
    public function subscribe(Request $request)
    {
        $request->validate([
            'plan_id' => 'required|exists:subscription_plans,id',
            'payment_method' => 'required|in:stripe,paypal,card'
        ]);

        $user = auth()->user();
        $plan = SubscriptionPlan::findOrFail($request->plan_id);

        // Check if user already has active subscription
        $activeSubscription = $user->subscriptions()
            ->where('status', 'active')
            ->first();

        if ($activeSubscription) {
            return response()->json([
                'success' => false,
                'message' => 'You already have an active subscription'
            ], 400);
        }

        // Create subscription
        $subscription = Subscription::create([
            'user_id' => $user->id,
            'subscription_plan_id' => $plan->id,
            'status' => 'trial',
            'start_date' => now(),
            'end_date' => now()->addDays($plan->duration_days),
            'trial_end_date' => now()->addDays(7), // 7-day trial
            'auto_renew' => true
        ]);

        // Create payment record
        $payment = Payment::create([
            'user_id' => $user->id,
            'subscription_id' => $subscription->id,
            'amount' => $plan->price,
            'currency' => 'AED',
            'payment_method' => $request->payment_method,
            'status' => 'pending',
            'type' => 'subscription'
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Subscription created successfully',
            'subscription' => $subscription,
            'payment' => $payment
        ], 201);
    }

    /**
     * Get current subscription
     */
    public function current()
    {
        $user = auth()->user();

        $subscription = $user->subscriptions()
            ->with('plan')
            ->where('status', 'active')
            ->orWhere('status', 'trial')
            ->first();

        if (!$subscription) {
            return response()->json([
                'success' => true,
                'subscription' => null,
                'message' => 'No active subscription'
            ]);
        }

        // Calculate usage
        $usage = [
            'days_remaining' => now()->diffInDays($subscription->end_date),
            'is_trial' => $subscription->status === 'trial',
            'trial_days_remaining' => $subscription->trial_end_date ? now()->diffInDays($subscription->trial_end_date) : 0,
        ];

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

    /**
     * Cancel subscription
     */
    public function cancel(Request $request)
    {
        $request->validate([
            'reason' => 'nullable|string|max:500'
        ]);

        $user = auth()->user();

        $subscription = $user->subscriptions()
            ->where('status', 'active')
            ->orWhere('status', 'trial')
            ->firstOrFail();

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

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

    /**
     * Get subscription benefits
     */
    public function benefits()
    {
        $user = auth()->user();

        $subscription = $user->subscriptions()
            ->with('plan')
            ->where('status', 'active')
            ->first();

        if (!$subscription) {
            return response()->json([
                'success' => true,
                'has_subscription' => false,
                'benefits' => []
            ]);
        }

        $plan = $subscription->plan;
        $features = json_decode($plan->features, true);

        $benefits = [
            'has_subscription' => true,
            'plan_name' => $plan->name,
            'features' => $features,
            'analytics_access' => $plan->analytics_access,
            'priority_support' => $plan->priority_support,
            'featured_listing' => $plan->featured_listing,
            'custom_branding' => $plan->custom_branding,
            'api_access' => $plan->api_access,
        ];

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

    /**
     * Get subscription history
     */
    public function history()
    {
        $user = auth()->user();

        $subscriptions = $user->subscriptions()
            ->with('plan')
            ->orderBy('created_at', 'desc')
            ->get();

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

    /**
     * Reactivate subscription
     */
    public function reactivate()
    {
        $user = auth()->user();

        $subscription = $user->subscriptions()
            ->where('status', 'cancelled')
            ->where('end_date', '>', now())
            ->firstOrFail();

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

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

    /**
     * Update auto-renew setting
     */
    public function updateAutoRenew(Request $request)
    {
        $request->validate([
            'auto_renew' => 'required|boolean'
        ]);

        $user = auth()->user();

        $subscription = $user->subscriptions()
            ->where('status', 'active')
            ->firstOrFail();

        $subscription->update([
            'auto_renew' => $request->auto_renew
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Auto-renew setting updated',
            'auto_renew' => $subscription->auto_renew
        ]);
    }
}
