<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Offer;
use App\Models\Ad;
use App\Models\Restaurant;
use App\Models\GasOffice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OffersAndAdsController extends Controller
{
    /**
     * عرض صفحة إدارة العروض والإعلانات
     */
    public function index(Request $request)
    {
        $type = $request->get('type', 'offers'); // 'offers' or 'ads'
        
        if ($type === 'ads') {
            $ads = Ad::latest()->paginate(20);
            return view('admin.offers_ads.ads', compact('ads'));
        }
        
        $offers = Offer::latest()->paginate(20);
        return view('admin.offers_ads.offers', compact('offers'));
    }

    /**
     * عرض نموذج إضافة عرض جديد
     */
    public function createOffer()
    {
        $restaurants = Restaurant::where('is_active', true)->get();
        $gasOffices = GasOffice::where('is_active', true)->get();
        
        return view('admin.offers_ads.create_offer', compact('restaurants', 'gasOffices'));
    }

    /**
     * حفظ عرض جديد
     */
    public function storeOffer(Request $request)
    {
        try {
            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'title_ar' => 'nullable|string|max:255',
                'description' => 'nullable|string',
                'description_ar' => 'nullable|string',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                'link_type' => 'required|in:none,restaurant,gas_office,external',
                'link_id' => 'nullable',
                'external_link' => 'nullable|url',
                'discount_percentage' => 'nullable|numeric|min:0|max:100',
                'discount_amount' => 'nullable|numeric|min:0',
                'offer_type' => 'required|in:food,gas,taxi,general',
                'start_date' => 'required|date',
                'end_date' => 'required|date|after:start_date',
                'display_order' => 'nullable|integer|min:0',
                'is_active' => 'nullable',
            ], [
                'title.required' => 'العنوان مطلوب',
                'offer_type.required' => 'نوع العرض مطلوب',
                'link_type.required' => 'نوع الرابط مطلوب',
                'start_date.required' => 'تاريخ البداية مطلوب',
                'end_date.required' => 'تاريخ النهاية مطلوب',
                'end_date.after' => 'تاريخ النهاية يجب أن يكون بعد تاريخ البداية',
                'external_link.url' => 'الرابط الخارجي غير صحيح',
            ]);

            // التحقق من link_id و external_link حسب link_type
            if ($request->link_type === 'restaurant' || $request->link_type === 'gas_office') {
                $linkId = $request->input('link_id');
                // التحقق من وجود القيمة وصحتها
                if (empty($linkId) || $linkId === '' || $linkId === null || $linkId === '0' || $linkId === 0) {
                    Log::info('Validation failed for link_id', [
                        'link_type' => $request->link_type,
                        'link_id' => $linkId,
                        'all_inputs' => $request->all(),
                        'has_link_id' => $request->has('link_id'),
                        'link_id_raw' => $request->get('link_id')
                    ]);
                    return back()
                        ->withInput()
                        ->with('error', 'يجب اختيار ' . ($request->link_type === 'restaurant' ? 'مطعم' : 'مكتب غاز') . '. القيمة المستلمة: [' . var_export($linkId, true) . ']');
                }
            } elseif ($request->link_type === 'external') {
                if (empty($request->external_link) || trim($request->external_link) === '') {
                    return back()
                        ->withInput()
                        ->with('error', 'يجب إدخال رابط خارجي');
                }
            }

            DB::beginTransaction();

            $imagePath = null;
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('offers', 'public');
            }

            $linkId = null;
            if ($request->link_type === 'restaurant' || $request->link_type === 'gas_office') {
                $linkId = $request->input('link_id');
            }
            
            $externalLink = null;
            if ($request->link_type === 'external') {
                $externalLink = $request->input('external_link');
            }

            Offer::create([
                'title' => $request->title,
                'title_ar' => $request->title_ar,
                'description' => $request->description,
                'description_ar' => $request->description_ar,
                'image' => $imagePath,
                'link_type' => $request->link_type,
                'link_id' => $linkId,
                'external_link' => $externalLink,
                'discount_percentage' => $request->discount_percentage ?: null,
                'discount_amount' => $request->discount_amount ?: null,
                'offer_type' => $request->offer_type,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'display_order' => $request->display_order ?? 0,
                'is_active' => $request->has('is_active'),
            ]);

            DB::commit();

            return redirect()
                ->route('admin.offers-ads.index', ['type' => 'offers'])
                ->with('success', 'تم إضافة العرض بنجاح');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return back()
                ->withInput()
                ->withErrors($e->errors())
                ->with('error', 'يرجى التحقق من البيانات المدخلة');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('خطأ في إضافة العرض: ' . $e->getMessage());
            Log::error('Stack trace: ' . $e->getTraceAsString());
            return back()
                ->withInput()
                ->with('error', 'خطأ في إضافة العرض: ' . $e->getMessage());
        }
    }

    /**
     * عرض نموذج تعديل عرض
     */
    public function editOffer($id)
    {
        $offer = Offer::findOrFail($id);
        $restaurants = Restaurant::where('is_active', true)->get();
        $gasOffices = GasOffice::where('is_active', true)->get();
        
        return view('admin.offers_ads.edit_offer', compact('offer', 'restaurants', 'gasOffices'));
    }

    /**
     * تحديث عرض
     */
    public function updateOffer(Request $request, $id)
    {
        $offer = Offer::findOrFail($id);

        $request->validate([
            'title' => 'required|string|max:255',
            'title_ar' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'link_type' => 'required|in:none,restaurant,gas_office,external',
            'link_id' => 'nullable|required_if:link_type,restaurant,gas_office',
            'external_link' => 'nullable|required_if:link_type,external|url',
            'discount_percentage' => 'nullable|numeric|min:0|max:100',
            'discount_amount' => 'nullable|numeric|min:0',
            'offer_type' => 'required|in:food,gas,taxi,general',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'display_order' => 'nullable|integer|min:0',
            'is_active' => 'nullable',
        ]);

        DB::beginTransaction();

        try {
            $data = [
                'title' => $request->title,
                'title_ar' => $request->title_ar,
                'description' => $request->description,
                'description_ar' => $request->description_ar,
                'link_type' => $request->link_type,
                'link_id' => $request->link_id,
                'external_link' => $request->external_link,
                'discount_percentage' => $request->discount_percentage,
                'discount_amount' => $request->discount_amount,
                'offer_type' => $request->offer_type,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'display_order' => $request->display_order ?? 0,
                'is_active' => $request->has('is_active'),
            ];

            if ($request->hasFile('image')) {
                // حذف الصورة القديمة
                if ($offer->image) {
                    Storage::disk('public')->delete($offer->image);
                }
                $data['image'] = $request->file('image')->store('offers', 'public');
            }

            $offer->update($data);

            DB::commit();

            return redirect()
                ->route('admin.offers-ads.index', ['type' => 'offers'])
                ->with('success', 'تم تحديث العرض بنجاح');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()
                ->withInput()
                ->with('error', 'خطأ في تحديث العرض: ' . $e->getMessage());
        }
    }

    /**
     * حذف عرض
     */
    public function destroyOffer($id)
    {
        try {
            $offer = Offer::findOrFail($id);
            
            // حذف الصورة
            if ($offer->image) {
                Storage::disk('public')->delete($offer->image);
            }
            
            $offer->delete();

            return redirect()
                ->route('admin.offers-ads.index', ['type' => 'offers'])
                ->with('success', 'تم حذف العرض بنجاح');
        } catch (\Exception $e) {
            return back()
                ->with('error', 'خطأ في حذف العرض: ' . $e->getMessage());
        }
    }

    /**
     * عرض نموذج إضافة إعلان جديد
     */
    public function createAd()
    {
        $restaurants = Restaurant::where('is_active', true)->get();
        $gasOffices = GasOffice::where('is_active', true)->get();
        
        return view('admin.offers_ads.create_ad', compact('restaurants', 'gasOffices'));
    }

    /**
     * حفظ إعلان جديد
     */
    public function storeAd(Request $request)
    {
        try {
            $validated = $request->validate([
                'title' => 'required|string|max:255',
                'title_ar' => 'nullable|string|max:255',
                'description' => 'nullable|string',
                'description_ar' => 'nullable|string',
                'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
                'video_url' => 'nullable|url',
                'link_type' => 'required|in:none,restaurant,gas_office,external',
                'link_id' => 'nullable',
                'external_link' => 'nullable|url',
                'ad_type' => 'required|in:banner,slider,popup',
                'start_date' => 'required|date',
                'end_date' => 'required|date|after:start_date',
                'display_order' => 'nullable|integer|min:0',
                'is_active' => 'nullable',
                'cost_per_view' => 'nullable|numeric|min:0',
                'cost_per_click' => 'nullable|numeric|min:0',
                'total_cost' => 'nullable|numeric|min:0',
            ], [
                'title.required' => 'العنوان مطلوب',
                'ad_type.required' => 'نوع الإعلان مطلوب',
                'link_type.required' => 'نوع الرابط مطلوب',
                'start_date.required' => 'تاريخ البداية مطلوب',
                'end_date.required' => 'تاريخ النهاية مطلوب',
                'end_date.after' => 'تاريخ النهاية يجب أن يكون بعد تاريخ البداية',
                'external_link.url' => 'الرابط الخارجي غير صحيح',
                'video_url.url' => 'رابط الفيديو غير صحيح',
            ]);

            // التحقق من link_id و external_link حسب link_type
            if ($request->link_type === 'restaurant' || $request->link_type === 'gas_office') {
                $linkId = $request->input('link_id');
                // التحقق من وجود القيمة وصحتها
                if (empty($linkId) || $linkId === '' || $linkId === null || $linkId === '0' || $linkId === 0) {
                    Log::info('Validation failed for link_id (Ad)', [
                        'link_type' => $request->link_type,
                        'link_id' => $linkId,
                        'all_inputs' => $request->all(),
                        'has_link_id' => $request->has('link_id'),
                        'link_id_raw' => $request->get('link_id')
                    ]);
                    return back()
                        ->withInput()
                        ->with('error', 'يجب اختيار ' . ($request->link_type === 'restaurant' ? 'مطعم' : 'مكتب غاز') . '. القيمة المستلمة: [' . var_export($linkId, true) . ']');
                }
            } elseif ($request->link_type === 'external') {
                if (empty($request->external_link) || trim($request->external_link) === '') {
                    return back()
                        ->withInput()
                        ->with('error', 'يجب إدخال رابط خارجي');
                }
            }

            DB::beginTransaction();

            $imagePath = null;
            if ($request->hasFile('image')) {
                $imagePath = $request->file('image')->store('ads', 'public');
            }

            Ad::create([
                'title' => $request->title,
                'title_ar' => $request->title_ar,
                'description' => $request->description,
                'description_ar' => $request->description_ar,
                'image' => $imagePath,
                'video_url' => $request->video_url,
                'link_type' => $request->link_type,
                'link_id' => $request->link_type !== 'none' && $request->link_type !== 'external' ? $request->link_id : null,
                'external_link' => $request->link_type === 'external' ? $request->external_link : null,
                'ad_type' => $request->ad_type,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'display_order' => $request->display_order ?? 0,
                'is_active' => $request->has('is_active'),
                'cost_per_view' => $request->cost_per_view ?? 0,
                'cost_per_click' => $request->cost_per_click ?? 0,
                'total_cost' => $request->total_cost ?? 0,
            ]);

            DB::commit();

            return redirect()
                ->route('admin.offers-ads.index', ['type' => 'ads'])
                ->with('success', 'تم إضافة الإعلان بنجاح');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return back()
                ->withInput()
                ->withErrors($e->errors())
                ->with('error', 'يرجى التحقق من البيانات المدخلة');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('خطأ في إضافة الإعلان: ' . $e->getMessage());
            Log::error('Stack trace: ' . $e->getTraceAsString());
            return back()
                ->withInput()
                ->with('error', 'خطأ في إضافة الإعلان: ' . $e->getMessage());
        }
    }

    /**
     * عرض نموذج تعديل إعلان
     */
    public function editAd($id)
    {
        $ad = Ad::findOrFail($id);
        $restaurants = Restaurant::where('is_active', true)->get();
        $gasOffices = GasOffice::where('is_active', true)->get();
        
        return view('admin.offers_ads.edit_ad', compact('ad', 'restaurants', 'gasOffices'));
    }

    /**
     * تحديث إعلان
     */
    public function updateAd(Request $request, $id)
    {
        $ad = Ad::findOrFail($id);

        $request->validate([
            'title' => 'required|string|max:255',
            'title_ar' => 'nullable|string|max:255',
            'description' => 'nullable|string',
            'description_ar' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
            'video_url' => 'nullable|url',
            'link_type' => 'required|in:none,restaurant,gas_office,external',
            'link_id' => 'nullable|required_if:link_type,restaurant,gas_office',
            'external_link' => 'nullable|required_if:link_type,external|url',
            'ad_type' => 'required|in:banner,slider,popup',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after:start_date',
            'display_order' => 'nullable|integer|min:0',
            'is_active' => 'nullable',
            'cost_per_view' => 'nullable|numeric|min:0',
            'cost_per_click' => 'nullable|numeric|min:0',
            'total_cost' => 'nullable|numeric|min:0',
        ]);

        DB::beginTransaction();

        try {
            $data = [
                'title' => $request->title,
                'title_ar' => $request->title_ar,
                'description' => $request->description,
                'description_ar' => $request->description_ar,
                'video_url' => $request->video_url,
                'link_type' => $request->link_type,
                'link_id' => $request->link_id,
                'external_link' => $request->external_link,
                'ad_type' => $request->ad_type,
                'start_date' => $request->start_date,
                'end_date' => $request->end_date,
                'display_order' => $request->display_order ?? 0,
                'is_active' => $request->has('is_active'),
                'cost_per_view' => $request->cost_per_view ?? 0,
                'cost_per_click' => $request->cost_per_click ?? 0,
                'total_cost' => $request->total_cost ?? 0,
            ];

            if ($request->hasFile('image')) {
                // حذف الصورة القديمة
                if ($ad->image) {
                    Storage::disk('public')->delete($ad->image);
                }
                $data['image'] = $request->file('image')->store('ads', 'public');
            }

            $ad->update($data);

            DB::commit();

            return redirect()
                ->route('admin.offers-ads.index', ['type' => 'ads'])
                ->with('success', 'تم تحديث الإعلان بنجاح');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()
                ->withInput()
                ->with('error', 'خطأ في تحديث الإعلان: ' . $e->getMessage());
        }
    }

    /**
     * حذف إعلان
     */
    public function destroyAd($id)
    {
        try {
            $ad = Ad::findOrFail($id);
            
            // حذف الصورة
            if ($ad->image) {
                Storage::disk('public')->delete($ad->image);
            }
            
            $ad->delete();

            return redirect()
                ->route('admin.offers-ads.index', ['type' => 'ads'])
                ->with('success', 'تم حذف الإعلان بنجاح');
        } catch (\Exception $e) {
            return back()
                ->with('error', 'خطأ في حذف الإعلان: ' . $e->getMessage());
        }
    }
}
