<?php

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

use App\Http\Controllers\Controller;
use App\Models\Offer;
use App\Models\Favorite;
use App\Models\Redemption;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OfferController extends Controller
{
    public function index(Request $request)
    {
        $query = Offer::with(['business', 'venue', 'category'])
            ->where('status', 'active')
            ->where('approval_status', 'approved')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now());

        // SUBSCRIPTION-BASED ACCESS CONTROL
        $user = auth('sanctum')->user();
        $userSubscription = null;
        $subscriptionPlanName = null;

        if ($user) {
            $userSubscription = $user->subscriptions()
                ->where('status', 'active')
                ->whereNull('business_id')
                ->with('plan')
                ->first();

            $subscriptionPlanName = $userSubscription ? $userSubscription->plan->name : null;
        }

        // Filter offers based on user subscription level
        if (!$user || !$userSubscription) {
            // No subscription - show only regular offers
            $query->where('offer_type', 'regular');
        } elseif (in_array($subscriptionPlanName, ['Premium', 'Premium Annual'])) {
            // Premium users - show regular + special offers
            $query->whereIn('offer_type', ['regular', 'special']);
        } elseif (in_array($subscriptionPlanName, ['VIP', 'VIP Annual'])) {
            // VIP users - show all offers (regular, special, exclusive)
            // No filter needed - they see everything
        } else {
            // Free tier or unknown - show only regular offers
            $query->where('offer_type', 'regular');
        }

        // Search
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('title_ar', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

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

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

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

        // Filter by offer type (respect subscription limits)
        if ($request->has('offer_type')) {
            $requestedType = $request->offer_type;

            // Check if user has access to requested offer type
            if ($requestedType === 'exclusive' && !in_array($subscriptionPlanName, ['VIP', 'VIP Annual'])) {
                // User doesn't have VIP, can't filter by exclusive
                return response()->json([
                    'success' => false,
                    'message' => 'VIP subscription required to access exclusive offers',
                    'subscription_required' => 'VIP'
                ], 403);
            } elseif ($requestedType === 'special' && !in_array($subscriptionPlanName, ['Premium', 'Premium Annual', 'VIP', 'VIP Annual'])) {
                // User doesn't have Premium or VIP
                return response()->json([
                    'success' => false,
                    'message' => 'Premium subscription required to access special offers',
                    'subscription_required' => 'Premium'
                ], 403);
            }

            $query->where('offer_type', $requestedType);
        }

        // Featured/Boosted offers
        if ($request->has('featured') && $request->featured) {
            $query->where('is_featured', true);
        }

        if ($request->has('boosted') && $request->boosted) {
            $query->where('is_boosted', true)
                ->where('boost_end_date', '>=', now());
        }

        // Sorting
        $sortBy = $request->sort_by ?? 'created_at';
        $sortOrder = $request->sort_order ?? 'desc';

        if (in_array($sortBy, ['redemption_count', 'view_count', 'created_at', 'end_date'])) {
            $query->orderBy($sortBy, $sortOrder);
        }

        $perPage = $request->per_page ?? 15;
        $offers = $query->paginate($perPage);

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

    public function show($id)
    {
        $offer = Offer::with([
            'business',
            'venue',
            'category',
        ])->findOrFail($id);

        // Check if offer is active
        if (!$offer->isActive()) {
            return response()->json([
                'success' => false,
                'message' => 'This offer is not currently active'
            ], 400);
        }

        // CHECK SUBSCRIPTION ACCESS
        $user = auth('sanctum')->user();
        if ($user) {
            $userSubscription = $user->subscriptions()
                ->where('status', 'active')
                ->whereNull('business_id')
                ->with('plan')
                ->first();

            $subscriptionPlanName = $userSubscription ? $userSubscription->plan->name : null;

            // Check if user has access to this offer type
            if ($offer->offer_type === 'exclusive' && !in_array($subscriptionPlanName, ['VIP', 'VIP Annual'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'VIP subscription required to access this exclusive offer',
                    'subscription_required' => 'VIP',
                    'offer_type' => 'exclusive'
                ], 403);
            }

            if ($offer->offer_type === 'special' && !in_array($subscriptionPlanName, ['Premium', 'Premium Annual', 'VIP', 'VIP Annual'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'Premium subscription required to access this special offer',
                    'subscription_required' => 'Premium',
                    'offer_type' => 'special'
                ], 403);
            }
        } elseif ($offer->offer_type !== 'regular') {
            // Not authenticated and trying to access non-regular offer
            return response()->json([
                'success' => false,
                'message' => 'Please login to access this offer',
                'requires_auth' => true
            ], 401);
        }

        // Increment view count
        $offer->increment('view_count');

        // Check if user has favorited
        $isFavorited = false;
        $userRedemptionCount = 0;
        $canRedeem = false;

        if (auth('sanctum')->check()) {
            $isFavorited = Favorite::where('user_id', auth()->id())
                ->where('favorable_type', Offer::class)
                ->where('favorable_id', $offer->id)
                ->exists();

            $userRedemptionCount = Redemption::where('offer_id', $offer->id)
                ->where('user_id', auth()->id())
                ->whereIn('status', ['pending', 'redeemed'])
                ->count();

            $canRedeem = $offer->canBeRedeemed()
                && $userRedemptionCount < $offer->redemption_per_user;
        }

        return response()->json([
            'success' => true,
            'data' => [
                'offer' => $offer,
                'is_favorited' => $isFavorited,
                'user_redemption_count' => $userRedemptionCount,
                'can_redeem' => $canRedeem,
                'remaining_redemptions' => $offer->redemption_limit
                    ? ($offer->redemption_limit - $offer->redemption_count)
                    : null,
            ]
        ]);
    }

    public function toggleFavorite($id)
    {
        $offer = Offer::findOrFail($id);

        $favorite = Favorite::where('user_id', auth()->id())
            ->where('favorable_type', Offer::class)
            ->where('favorable_id', $offer->id)
            ->first();

        if ($favorite) {
            $favorite->delete();
            $message = 'Offer removed from favorites';
            $isFavorited = false;
        } else {
            Favorite::create([
                'user_id' => auth()->id(),
                'favorable_type' => Offer::class,
                'favorable_id' => $offer->id,
            ]);
            $message = 'Offer added to favorites';
            $isFavorited = true;
        }

        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => [
                'is_favorited' => $isFavorited
            ]
        ]);
    }

    public function exclusive(Request $request)
    {
        // Check if user has VIP subscription
        $user = auth('sanctum')->user();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Please login to access exclusive offers',
                'requires_auth' => true
            ], 401);
        }

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

        $subscriptionPlanName = $userSubscription ? $userSubscription->plan->name : null;

        if (!in_array($subscriptionPlanName, ['VIP', 'VIP Annual'])) {
            return response()->json([
                'success' => false,
                'message' => 'VIP subscription required to access exclusive offers',
                'subscription_required' => 'VIP',
                'current_subscription' => $subscriptionPlanName ?? 'None'
            ], 403);
        }

        $offers = Offer::with(['business', 'venue', 'category'])
            ->where('status', 'active')
            ->where('approval_status', 'approved')
            ->where('offer_type', 'exclusive')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->orderBy('created_at', 'desc')
            ->paginate($request->per_page ?? 15);

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

    public function special(Request $request)
    {
        // Check if user has Premium or VIP subscription
        $user = auth('sanctum')->user();

        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Please login to access special offers',
                'requires_auth' => true
            ], 401);
        }

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

        $subscriptionPlanName = $userSubscription ? $userSubscription->plan->name : null;

        if (!in_array($subscriptionPlanName, ['Premium', 'Premium Annual', 'VIP', 'VIP Annual'])) {
            return response()->json([
                'success' => false,
                'message' => 'Premium subscription required to access special offers',
                'subscription_required' => 'Premium',
                'current_subscription' => $subscriptionPlanName ?? 'None'
            ], 403);
        }

        $offers = Offer::with(['business', 'venue', 'category'])
            ->where('status', 'active')
            ->where('approval_status', 'approved')
            ->where('offer_type', 'special')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->orderBy('created_at', 'desc')
            ->paginate($request->per_page ?? 15);

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

    public function trending(Request $request)
    {
        $offers = Offer::with(['business', 'venue', 'category'])
            ->where('status', 'active')
            ->where('approval_status', 'approved')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->orderBy('redemption_count', 'desc')
            ->orderBy('view_count', 'desc')
            ->paginate($request->per_page ?? 15);

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

    public function expiringSoon(Request $request)
    {
        $offers = Offer::with(['business', 'venue', 'category'])
            ->where('status', 'active')
            ->where('approval_status', 'approved')
            ->where('start_date', '<=', now())
            ->whereBetween('end_date', [now(), now()->addDays(7)])
            ->orderBy('end_date', 'asc')
            ->paginate($request->per_page ?? 15);

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