<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Banner;
use App\Models\BannerImpression;
use App\Models\BannerClick;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class BannerPlacementController extends Controller
{
    /**
     * Get active banners for a specific screen/placement
     * 
     * This API allows the UniversalBannerWidget to fetch banners
     * that are configured to display on specific screens
     */
    public function getBannersForPlacement(Request $request, $screenName)
    {
        try {
            // Get location filters if provided
            $country = $request->query('country');
            $state = $request->query('state');
            $city = $request->query('city');

            // Query active banners
            $bannersQuery = Banner::where('status', 'active')
                ->where(function ($query) use ($screenName) {
                    // Check if banner has placement_screens column and includes this screen
                    // OR if no specific screens are set (show everywhere)
                    $query->whereJsonContains('placement_screens', $screenName)
                          ->orWhereNull('placement_screens')
                          ->orWhere('placement_screens', '[]');
                })
                ->where(function($query) {
                    $query->whereNull('start_date')
                          ->orWhere('start_date', '<=', now());
                })
                ->where(function($query) {
                    $query->whereNull('end_date')
                          ->orWhere('end_date', '>=', now());
                });

            // Apply location filters if banner supports targeting
            // Apply location filters using the model scope which handles target_location_type correctly
            // We pass null for state/city if not provided, scope handles it
            if ($country || $state || $city) {
                 $bannersQuery->forLocation($country, $state, $city);
            }

            $banners = $bannersQuery
                ->orderBy('priority', 'desc')
                ->orderBy('total_impressions', 'asc') // Show banners with fewer impressions first
                ->limit(3) // Max 3 banners per placement
                ->get();


            // Transform to API response format
            $bannersData = $banners->map(function ($banner) {
                return [
                    'id' => $banner->id,
                    'title' => $banner->title,
                    'description' => $banner->description,
                    'image_url' => $banner->image_url ? url($banner->image_url) : null,
                    'redirect_type' => $banner->redirect_type,
                    'redirect_value' => $banner->redirect_value,
                    'impressions' => $banner->impressions ?? 0,
                    'clicks' => $banner->clicks ?? 0,
                ];
            });

            return response()->json([
                'success' => true,
                'data' => $bannersData,
                'screen' => $screenName,
                'count' => $bannersData->count(),
            ]);

        } catch (\Exception $e) {
            Log::error('Error fetching banners for placement: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch banners',
                'error' => config('app.debug') ? $e->getMessage() : null,
            ], 500);
        }
    }

    /**
     * Get configuration for all banner placements (for admin dashboard)
     */
    public function getPlacementSettings()
    {
        $placements = [
            'home' => [
                'name' => 'Home Screen',
                'is_active' => true,
                'position' => 'top',
                'max_banners' => 3,
            ],
            'packages' => [
                'name' => 'Packages & Orders',
                'is_active' => true,
                'position' => 'bottom',
                'max_banners' => 1,
            ],
            'premium_plans' => [
                'name' => 'Premium Plans',
                'is_active' => true,
                'position' => 'bottom',
                'max_banners' => 1,
            ],
            'blogs' => [
                'name' => 'Blogs',
                'is_active' => true,
                'position' => 'inline',
                'max_banners' => 2,
            ],
            'my_ads' => [
                'name' => 'My Ads',
                'is_active' => true,
                'position' => 'inline',
                'max_banners' => 1,
            ],
            'help_support' => [
                'name' => 'Help & Support',
                'is_active' => true,
                'position' => 'bottom',
                'max_banners' => 1,
            ],
            'trust_score' => [
                'name' => 'Trust Score',
                'is_active' => true,
                'position' => 'bottom',
                'max_banners' => 1,
            ],
            'my_reviews' => [
                'name' => 'My Reviews',
                'is_active' => true,
                'position' => 'bottom',
                'max_banners' => 1,
            ],
        ];

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

    /**
     * Get analytics for banner placements
     */
    public function getPlacementAnalytics()
    {
        $screens = ['home', 'packages', 'premium_plans', 'blogs', 'my_ads', 'help_support'];
        
        $analytics = [];
        
        foreach ($screens as $screen) {
            // Get total impressions and clicks for this screen
            $impressions = BannerImpression::whereHas('banner', function($query) use ($screen) {
                $query->whereJsonContains('placement_screens', $screen);
            })->count();
            
            $clicks = BannerClick::whereHas('banner', function($query) use ($screen) {
                $query->whereJsonContains('placement_screens', $screen);
            })->count();
            
            $ctr = $impressions > 0 ? ($clicks / $impressions) * 100 : 0;
            
            $activeBanners = Banner::where('status', 'active')
                ->whereJsonContains('placement_screens', $screen)
                ->count();
            
            $analytics[$screen] = [
                'screen_name' => $screen,
                'active_banners' => $activeBanners,
                'total_impressions' => $impressions,
                'total_clicks' => $clicks,
                'ctr' => round($ctr, 2),
            ];
        }
        
        return response()->json([
            'success' => true,
            'analytics' => $analytics,
        ]);
    }
}
