<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Offer;
use App\Models\Ad;
use App\Models\OfferInteraction;
use App\Models\AdInteraction;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class OffersAndAdsController extends Controller
{
    /**
     * الحصول على جميع العروض النشطة
     */
    public function getOffers(Request $request): JsonResponse
    {
        try {
            $offers = Offer::active()
                ->ordered()
                ->get()
                ->map(function ($offer) {
                    return [
                        'id' => $offer->id,
                        'title' => $offer->title_ar ?? $offer->title,
                        'description' => $offer->description_ar ?? $offer->description,
                        'image_url' => $offer->image ? asset('storage/' . $offer->image) : null,
                        'image' => $offer->image ? url('storage/' . $offer->image) : null,
                        'link_type' => $offer->link_type,
                        'link_id' => $offer->link_id,
                        'external_link' => $offer->external_link,
                        'link' => $offer->link,
                        'discount_percentage' => $offer->discount_percentage,
                        'discount_amount' => $offer->discount_amount,
                        'offer_type' => $offer->offer_type,
                        'start_date' => $offer->start_date->toISOString(),
                        'end_date' => $offer->end_date->toISOString(),
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => $offers,
                'message' => 'تم جلب العروض بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في جلب العروض: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * الحصول على جميع الإعلانات النشطة (للسلايدر)
     */
    public function getAds(Request $request): JsonResponse
    {
        try {
            $adType = $request->get('type', 'slider'); // 'slider', 'banner', 'popup'

            $ads = Ad::active()
                ->where('ad_type', $adType)
                ->ordered()
                ->get()
                ->map(function ($ad) {
                    return [
                        'id' => $ad->id,
                        'title' => $ad->title_ar ?? $ad->title,
                        'description' => $ad->description_ar ?? $ad->description,
                        'image_url' => $ad->image ? asset('storage/' . $ad->image) : null,
                        'image' => $ad->image ? url('storage/' . $ad->image) : null,
                        'video_url' => $ad->video_url,
                        'link_type' => $ad->link_type,
                        'link_id' => $ad->link_id,
                        'external_link' => $ad->external_link,
                        'link' => $ad->link,
                        'ad_type' => $ad->ad_type,
                        'start_date' => $ad->start_date->toISOString(),
                        'end_date' => $ad->end_date->toISOString(),
                    ];
                });

            return response()->json([
                'success' => true,
                'data' => $ads,
                'message' => 'تم جلب الإعلانات بنجاح'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في جلب الإعلانات: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * الحصول على إعلانات البنر النشطة (عرض مكان "عرض خاص") - مسار عام بدون مصادقة.
     * يعيد الإعلانات حيث ad_type = banner و is_active = 1، مع مراعاة تاريخ البدء والانتهاء إن وُجد.
     */
    public function getBannerItems(Request $request): JsonResponse
    {
        try {
            $today = now()->format('Y-m-d');
            $ads = Ad::where('is_active', true)
                ->where('ad_type', 'banner')
                ->whereDate('start_date', '<=', $today)
                ->whereDate('end_date', '>=', $today)
                ->orderBy('display_order', 'asc')
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($ad) {
                return [
                    'id' => $ad->id,
                    'title' => $ad->title_ar ?? $ad->title,
                    'description' => $ad->description_ar ?? $ad->description,
                    'image_url' => $ad->image ? asset('storage/' . $ad->image) : null,
                    'image' => $ad->image ? url('storage/' . $ad->image) : null,
                    'video_url' => $ad->video_url,
                    'link_type' => $ad->link_type,
                    'link_id' => $ad->link_id,
                    'external_link' => $ad->external_link,
                    'link' => $ad->link,
                    'ad_type' => $ad->ad_type,
                    'start_date' => $ad->start_date->toISOString(),
                    'end_date' => $ad->end_date->toISOString(),
                ];
            });

            // إن لم يُعثر على بنر ضمن الفترة، نُرجع أي بنر نشط (لتجنب عدم الظهور بسبب التواريخ فقط)
            if ($ads->isEmpty()) {
                $ads = Ad::where('is_active', true)
                    ->where('ad_type', 'banner')
                    ->orderBy('display_order', 'asc')
                    ->orderBy('created_at', 'desc')
                    ->get()
                    ->map(function ($ad) {
                        return [
                            'id' => $ad->id,
                            'title' => $ad->title_ar ?? $ad->title,
                            'description' => $ad->description_ar ?? $ad->description,
                            'image_url' => $ad->image ? asset('storage/' . $ad->image) : null,
                            'image' => $ad->image ? url('storage/' . $ad->image) : null,
                            'video_url' => $ad->video_url,
                            'link_type' => $ad->link_type,
                            'link_id' => $ad->link_id,
                            'external_link' => $ad->external_link,
                            'link' => $ad->link,
                            'ad_type' => $ad->ad_type,
                            'start_date' => $ad->start_date->toISOString(),
                            'end_date' => $ad->end_date->toISOString(),
                        ];
                    });
            }

            return response()->json([
                'success' => true,
                'data' => $ads->values()->all(),
                'message' => 'تم جلب إعلانات البنر بنجاح',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => [],
                'message' => 'خطأ: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * الحصول على العروض والإعلانات للسلايدر في الشاشة الرئيسية
     */
    public function getSliderItems(Request $request): JsonResponse
    {
        try {
            // الحصول على جميع العروض (للتشخيص)
            $allOffersCount = Offer::count();
            $activeOffersCount = Offer::where('is_active', true)->count();
            $today = now()->format('Y-m-d');
            $validDateOffersCount = Offer::where('is_active', true)
                ->whereDate('start_date', '<=', $today)
                ->whereDate('end_date', '>=', $today)
                ->count();

            // الحصول على العروض النشطة
            $offers = Offer::where('is_active', true)
                ->whereDate('start_date', '<=', $today)
                ->whereDate('end_date', '>=', $today)
                ->orderBy('display_order', 'asc')
                ->orderBy('created_at', 'desc')
                ->take(10)
                ->get()
                ->map(function ($offer) {
                    return [
                        'type' => 'offer',
                        'id' => $offer->id,
                        'title' => $offer->title_ar ?? $offer->title,
                        'description' => $offer->description_ar ?? $offer->description,
                        'image_url' => $offer->image ? asset('storage/' . $offer->image) : null,
                        'image' => $offer->image ? url('storage/' . $offer->image) : null,
                        'link_type' => $offer->link_type,
                        'link_id' => $offer->link_id,
                        'external_link' => $offer->external_link,
                        'link' => $offer->link,
                        'discount_percentage' => $offer->discount_percentage,
                        'discount_amount' => $offer->discount_amount,
                        'offer_type' => $offer->offer_type,
                        'display_order' => $offer->display_order ?? 999,
                    ];
                });

            // الحصول على جميع الإعلانات (للتشخيص)
            $allAdsCount = Ad::count();
            $activeAdsCount = Ad::where('is_active', true)->count();
            $sliderAdsCount = Ad::where('is_active', true)
                ->where('ad_type', 'slider')
                ->count();
            $today = now()->format('Y-m-d');
            $validDateSliderAdsCount = Ad::where('is_active', true)
                ->where('ad_type', 'slider')
                ->whereDate('start_date', '<=', $today)
                ->whereDate('end_date', '>=', $today)
                ->count();

            // الحصول على الإعلانات النشطة من نوع slider
            $ads = Ad::where('is_active', true)
                ->where('ad_type', 'slider')
                ->whereDate('start_date', '<=', $today)
                ->whereDate('end_date', '>=', $today)
                ->orderBy('display_order', 'asc')
                ->orderBy('created_at', 'desc')
                ->take(10)
                ->get()
                ->map(function ($ad) {
                    return [
                        'type' => 'ad',
                        'id' => $ad->id,
                        'title' => $ad->title_ar ?? $ad->title,
                        'description' => $ad->description_ar ?? $ad->description,
                        'image_url' => $ad->image ? asset('storage/' . $ad->image) : null,
                        'image' => $ad->image ? url('storage/' . $ad->image) : null,
                        'video_url' => $ad->video_url,
                        'link_type' => $ad->link_type,
                        'link_id' => $ad->link_id,
                        'external_link' => $ad->external_link,
                        'link' => $ad->link,
                        'ad_type' => $ad->ad_type,
                        'display_order' => $ad->display_order ?? 999,
                    ];
                });

            // دمج العروض والإعلانات وترتيبها حسب display_order
            $sliderItems = $offers->concat($ads)->sortBy('display_order')->values();

            // تسجيل المشاهدة
            $user = Auth::user();
            foreach ($sliderItems as $item) {
                if ($item['type'] === 'offer') {
                    $offer = Offer::find($item['id']);
                    if ($offer) {
                        $offer->incrementViews();
                        
                        // تسجيل التفاعل
                        OfferInteraction::create([
                            'offer_id' => $offer->id,
                            'user_id' => $user?->id,
                            'interaction_type' => 'view',
                            'ip_address' => $request->ip(),
                            'device_info' => $request->userAgent(),
                        ]);
                    }
                } elseif ($item['type'] === 'ad') {
                    $ad = Ad::find($item['id']);
                    if ($ad) {
                        $ad->incrementViews();
                        
                        // تسجيل التفاعل
                        AdInteraction::create([
                            'ad_id' => $ad->id,
                            'user_id' => $user?->id,
                            'interaction_type' => 'view',
                            'ip_address' => $request->ip(),
                            'device_info' => $request->userAgent(),
                        ]);
                    }
                }
            }

            // إحصائيات للتشخيص
            $allOffersCount = Offer::count();
            $activeOffersCount = Offer::where('is_active', true)->count();
            $validDateOffersCount = Offer::where('is_active', true)
                ->where('start_date', '<=', now())
                ->where('end_date', '>=', now())
                ->count();

            $allAdsCount = Ad::count();
            $activeAdsCount = Ad::where('is_active', true)->count();
            $sliderAdsCount = Ad::where('is_active', true)
                ->where('ad_type', 'slider')
                ->count();
            $validDateSliderAdsCount = Ad::where('is_active', true)
                ->where('ad_type', 'slider')
                ->where('start_date', '<=', now())
                ->where('end_date', '>=', now())
                ->count();

            return response()->json([
                'success' => true,
                'data' => $sliderItems,
                'message' => 'تم جلب عناصر السلايدر بنجاح',
                'debug' => [
                    'offers' => [
                        'total' => $allOffersCount,
                        'active' => $activeOffersCount,
                        'valid_dates' => $validDateOffersCount,
                        'returned' => $offers->count(),
                    ],
                    'ads' => [
                        'total' => $allAdsCount,
                        'active' => $activeAdsCount,
                        'slider_type' => $sliderAdsCount,
                        'valid_dates' => $validDateSliderAdsCount,
                        'returned' => $ads->count(),
                    ],
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في جلب عناصر السلايدر: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * تسجيل النقرة على عرض أو إعلان
     */
    public function recordClick(Request $request, $type, $id): JsonResponse
    {
        try {
            $user = Auth::user();

            if ($type === 'offer') {
                $offer = Offer::findOrFail($id);
                $offer->incrementClicks();
                
                OfferInteraction::create([
                    'offer_id' => $offer->id,
                    'user_id' => $user?->id,
                    'interaction_type' => 'click',
                    'ip_address' => $request->ip(),
                    'device_info' => $request->userAgent(),
                ]);

                return response()->json([
                    'success' => true,
                    'data' => ['link' => $offer->link],
                    'message' => 'تم تسجيل النقرة بنجاح'
                ]);
            } elseif ($type === 'ad') {
                $ad = Ad::findOrFail($id);
                $ad->incrementClicks();
                
                AdInteraction::create([
                    'ad_id' => $ad->id,
                    'user_id' => $user?->id,
                    'interaction_type' => 'click',
                    'ip_address' => $request->ip(),
                    'device_info' => $request->userAgent(),
                ]);

                return response()->json([
                    'success' => true,
                    'data' => ['link' => $ad->link],
                    'message' => 'تم تسجيل النقرة بنجاح'
                ]);
            }

            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'نوع غير صحيح'
            ], 400);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'data' => null,
                'message' => 'خطأ في تسجيل النقرة: ' . $e->getMessage()
            ], 500);
        }
    }
}
