<?php

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

use App\Http\Controllers\Controller;
use App\Models\MarketingCampaign;
use App\Models\MarketingPackage;
use Illuminate\Http\Request;

class MarketingController extends Controller
{
    /**
     * Get active marketing banners (for mobile app)
     */
    public function activeBanners()
    {
        $banners = MarketingCampaign::with(['business', 'venue', 'offer'])
            ->where('type', 'banner')
            ->where('status', 'active')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        // Track impressions
        foreach ($banners as $banner) {
            $banner->incrementImpressions();
        }

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

    /**
     * Get active popup campaigns
     */
    public function activePopups()
    {
        $popup = MarketingCampaign::with(['business', 'venue', 'offer'])
            ->where('type', 'popup')
            ->where('status', 'active')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->orderBy('created_at', 'desc')
            ->first();

        if ($popup) {
            $popup->incrementImpressions();
        }

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

    /**
     * Get featured venues
     */
    public function featuredVenues()
    {
        $campaigns = MarketingCampaign::with(['venue.category'])
            ->where('type', 'featured_venue')
            ->where('status', 'active')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->whereNotNull('venue_id')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        $venues = $campaigns->map(function ($campaign) {
            $campaign->incrementImpressions();
            return [
                'campaign_id' => $campaign->id,
                'venue' => $campaign->venue,
                'featured_until' => $campaign->end_date,
            ];
        });

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

    /**
     * Get featured offers
     */
    public function featuredOffers()
    {
        $campaigns = MarketingCampaign::with(['offer.venue'])
            ->where('type', 'featured_offer')
            ->where('status', 'active')
            ->where('start_date', '<=', now())
            ->where('end_date', '>=', now())
            ->whereNotNull('offer_id')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        $offers = $campaigns->map(function ($campaign) {
            $campaign->incrementImpressions();
            return [
                'campaign_id' => $campaign->id,
                'offer' => $campaign->offer,
                'featured_until' => $campaign->end_date,
            ];
        });

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

    /**
     * Track campaign click
     */
    public function trackClick($id)
    {
        $campaign = MarketingCampaign::findOrFail($id);

        if (!$campaign->isActive()) {
            return response()->json([
                'success' => false,
                'message' => 'Campaign is not active',
            ], 400);
        }

        $campaign->incrementClicks();

        return response()->json([
            'success' => true,
            'message' => 'Click tracked',
            'data' => [
                'cta_link' => $campaign->cta_link,
                'venue_id' => $campaign->venue_id,
                'offer_id' => $campaign->offer_id,
            ],
        ]);
    }

    /**
     * Track conversion (e.g., offer redeemed from campaign)
     */
    public function trackConversion($id)
    {
        $campaign = MarketingCampaign::findOrFail($id);

        if (!$campaign->isActive()) {
            return response()->json([
                'success' => false,
                'message' => 'Campaign is not active',
            ], 400);
        }

        // Update today's analytics
        \App\Models\MarketingCampaignAnalytic::updateOrCreate(
            [
                'campaign_id' => $campaign->id,
                'date' => now()->toDateString(),
            ],
            [
                'conversions' => \DB::raw('conversions + 1'),
            ]
        );

        return response()->json([
            'success' => true,
            'message' => 'Conversion tracked',
        ]);
    }

    /**
     * Get available packages (for business)
     */
    public function getPackages()
    {
        $packages = MarketingPackage::where('is_active', true)
            ->orderBy('sort_order')
            ->get()
            ->groupBy('type');

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

    /**
     * Create campaign (business API)
     */
    public function createCampaign(Request $request)
    {
        $user = auth()->user();
        $business = $user->businesses()->first();

        if (!$business) {
            return response()->json([
                'success' => false,
                'message' => 'No business associated with this account',
            ], 403);
        }

        $validated = $request->validate([
            'package_id' => 'required|exists:marketing_packages,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'venue_id' => 'nullable|exists:venues,id',
            'offer_id' => 'nullable|exists:offers,id',
            'media' => 'nullable|array',
            'media.*' => 'nullable|url',
            'cta_text' => 'nullable|string|max:100',
            'cta_link' => 'nullable|url',
            'start_date' => 'required|date|after_or_equal:today',
        ]);

        $package = MarketingPackage::findOrFail($validated['package_id']);

        $startDate = \Carbon\Carbon::parse($validated['start_date']);
        $endDate = $startDate->copy()->addDays($package->duration_days);

        $campaign = MarketingCampaign::create([
            'business_id' => $business->id,
            'package_id' => $package->id,
            'venue_id' => $validated['venue_id'] ?? null,
            'offer_id' => $validated['offer_id'] ?? null,
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'type' => $package->type,
            'media' => $validated['media'] ?? null,
            'cta_text' => $validated['cta_text'] ?? 'Learn More',
            'cta_link' => $validated['cta_link'] ?? null,
            'start_date' => $startDate,
            'end_date' => $endDate,
            'status' => 'pending',
            'amount_paid' => $package->price,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Campaign created successfully. Awaiting approval.',
            'data' => $campaign,
        ], 201);
    }

    /**
     * Get business campaigns
     */
    public function myCampaigns(Request $request)
    {
        $user = auth()->user();
        $business = $user->businesses()->first();

        if (!$business) {
            return response()->json([
                'success' => false,
                'message' => 'No business associated with this account',
            ], 403);
        }

        $query = MarketingCampaign::where('business_id', $business->id)
            ->with(['package', 'venue', 'offer']);

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

        $campaigns = $query->orderBy('created_at', 'desc')->get();

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

    /**
     * Get campaign analytics (business API)
     */
    public function getCampaignAnalytics($id, Request $request)
    {
        $user = auth()->user();
        $business = $user->businesses()->first();

        if (!$business) {
            return response()->json([
                'success' => false,
                'message' => 'No business associated with this account',
            ], 403);
        }

        $campaign = MarketingCampaign::where('business_id', $business->id)
            ->findOrFail($id);

        $startDate = $request->start_date ?? $campaign->start_date;
        $endDate = $request->end_date ?? ($campaign->end_date->isPast() ? $campaign->end_date : now());

        $analytics = \App\Models\MarketingCampaignAnalytic::getForDateRange($campaign->id, $startDate, $endDate);
        $aggregatedStats = \App\Models\MarketingCampaignAnalytic::getAggregatedStats($campaign->id);

        return response()->json([
            'success' => true,
            'data' => [
                'campaign' => $campaign,
                'daily_analytics' => $analytics,
                'aggregated_stats' => $aggregatedStats,
            ],
        ]);
    }
}
