<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Occasion;
use App\Models\Country;
use App\Models\Locale;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OccasionController extends Controller
{
    /**
     * Display a listing of occasions
     */
    public function index(Request $request)
    {
        $query = Occasion::with(['translations.locale', 'countries', 'media']);

        // Get current country filter from session
        $currentCountry = current_filtered_country();
        $availableLocales = collect();
        
        if ($currentCountry) {
            // Get locales for the selected country
            $availableLocales = Locale::where('country_id', $currentCountry->id)
                                    ->active()
                                    ->ordered()
                                    ->get();
            
            // Filter occasions by country
            $query->whereHas('countries', function ($q) use ($currentCountry) {
                $q->where('countries.id', $currentCountry->id);
            });
        }

        // Language filter (for translations)
        if ($request->filled('locale_id')) {
            $query->whereHas('translations', function ($q) use ($request) {
                $q->where('locale_id', $request->locale_id);
            });
        }

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->whereHas('translations', function ($tq) use ($search) {
                    $tq->where('name', 'like', "%{$search}%")
                        ->orWhere('description', 'like', "%{$search}%");
                });
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by featured
        if ($request->filled('featured')) {
            $query->where('is_featured', $request->featured === '1');
        }

        // Get paginated results with ordering
        $occasions = $query->ordered()->paginate(15)->withQueryString();

        // Get all countries for the form
        $countries = Country::active()->ordered()->get();

        return view('admin.occasions.index', compact('occasions', 'countries', 'availableLocales', 'currentCountry'));
    }

    /**
     * Store a newly created occasion
     */
    public function store(Request $request)
    {
        $request->validate([
            'translations' => 'required|array',
            'countries' => 'required|array',
            'countries.*' => 'exists:countries,id',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_featured' => 'nullable|boolean',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:2048',
            'banner' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        // Check if at least one translation exists
        $hasTranslation = false;
        foreach ($request->translations as $translation) {
            if (!empty($translation['name'])) {
                $hasTranslation = true;
                break;
            }
        }

        if (!$hasTranslation) {
            return back()->withErrors([
                'translations' => admin_trans('at_least_one_occasion_name_required')
            ])->withInput();
        }

        DB::beginTransaction();
        try {
            $occasion = Occasion::create([
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_featured' => $request->boolean('is_featured'),
            ]);

            // Store translations
            foreach ($request->translations as $localeId => $translation) {
                if (!empty($translation['name'])) {
                    $occasion->translations()->create([
                        'locale_id' => $localeId,
                        'name' => $translation['name'],
                        'description' => $translation['description'] ?? null,
                    ]);
                }
            }

            // Link to countries
            $occasion->countries()->sync($request->countries);

            // Handle media uploads
            if ($request->hasFile('icon')) {
                $occasion->addMediaFromRequest('icon')
                    ->toMediaCollection('icon');
            }

            if ($request->hasFile('banner')) {
                $occasion->addMediaFromRequest('banner')
                    ->toMediaCollection('banner');
            }

            DB::commit();
            flash_success(admin_trans('occasion_created_successfully'));
            return redirect()->route('admin.occasions.index');
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_creating_occasion'));
            return back()->withInput();
        }
    }

    /**
     * Show the form for editing the specified occasion (API endpoint)
     */
    public function edit(Occasion $occasion)
    {
        try {
            $occasion->load(['translations.locale', 'countries', 'media']);

            $data = [
                'id' => $occasion->id,
                'order' => $occasion->order,
                'status' => $occasion->status,
                'is_featured' => $occasion->is_featured,
                'translations' => $occasion->translations->toArray(),
                'countries' => $occasion->countries->pluck('id')->toArray(),
                'icon_url' => $occasion->getFirstMediaUrl('icon'),
                'banner_url' => $occasion->getFirstMediaUrl('banner'),
            ];

            return response()->json([
                'success' => true,
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('error_loading_occasion')
            ], 500);
        }
    }

    /**
     * Update the specified occasion
     */
    public function update(Request $request, Occasion $occasion)
    {
        $request->validate([
            'translations' => 'required|array',
            'countries' => 'required|array',
            'countries.*' => 'exists:countries,id',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_featured' => 'nullable|boolean',
            'icon' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:2048',
            'banner' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:5120',
        ]);

        // Check if at least one translation exists
        $hasTranslation = false;
        foreach ($request->translations as $translation) {
            if (!empty($translation['name'])) {
                $hasTranslation = true;
                break;
            }
        }

        if (!$hasTranslation) {
            return back()->withErrors([
                'translations' => admin_trans('at_least_one_occasion_name_required')
            ])->withInput();
        }

        DB::beginTransaction();
        try {
            $occasion->update([
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_featured' => $request->boolean('is_featured'),
            ]);

            // Clear existing translations
            $occasion->translations()->delete();

            // Store translations
            foreach ($request->translations as $localeId => $translation) {
                if (!empty($translation['name'])) {
                    $occasion->translations()->create([
                        'locale_id' => $localeId,
                        'name' => $translation['name'],
                        'description' => $translation['description'] ?? null,
                    ]);
                }
            }

            // Update countries
            $occasion->countries()->sync($request->countries);

            // Handle media uploads
            if ($request->hasFile('icon')) {
                $occasion->clearMediaCollection('icon');
                $occasion->addMediaFromRequest('icon')
                    ->toMediaCollection('icon');
            }

            if ($request->hasFile('banner')) {
                $occasion->clearMediaCollection('banner');
                $occasion->addMediaFromRequest('banner')
                    ->toMediaCollection('banner');
            }

            DB::commit();
            flash_success(admin_trans('occasion_updated_successfully'));
            return redirect()->route('admin.occasions.index');
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_updating_occasion'));
            return back()->withInput();
        }
    }

    /**
     * Remove the specified occasion
     */
    public function destroy(Occasion $occasion)
    {
        // Check if occasion has related records
        if ($occasion->offers()->count() > 0) {
            flash_error(admin_trans('cannot_delete_occasion_with_relations'));
            return back();
        }

        try {
            $occasion->delete();
            flash_success(admin_trans('occasion_deleted_successfully'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_deleting_occasion'));
        }

        return redirect()->route('admin.occasions.index');
    }

    /**
     * Update occasions order
     */
    public function updateOrder(Request $request)
    {
        $request->validate([
            'orders' => 'required|array',
            'orders.*' => 'required|integer|exists:occasions,id',
        ]);

        DB::beginTransaction();
        try {
            foreach ($request->orders as $order => $id) {
                Occasion::where('id', $id)->update(['order' => $order]);
            }

            DB::commit();
            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false], 500);
        }
    }

    /**
     * Toggle occasion status
     */
    public function toggleStatus(Occasion $occasion)
    {
        try {
            $newStatus = $occasion->status === 'active' ? 'draft' : 'active';
            $occasion->update(['status' => $newStatus]);

            flash_success(admin_trans('occasion_status_updated'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_updating_status'));
        }

        return back();
    }

    /**
     * Toggle occasion featured status
     */
    public function toggleFeatured(Occasion $occasion)
    {
        try {
            $occasion->update(['is_featured' => !$occasion->is_featured]);

            $message = $occasion->is_featured
                ? admin_trans('occasion_featured_successfully')
                : admin_trans('occasion_unfeatured_successfully');

            flash_success($message);
        } catch (\Exception $e) {
            flash_error(admin_trans('error_updating_featured'));
        }

        return back();
    }

    /**
     * Bulk actions
     */
    public function bulkAction(Request $request)
    {
        $request->validate([
            'action' => 'required|in:delete,activate,deactivate,feature,unfeature',
            'selected' => 'required|array',
            'selected.*' => 'exists:occasions,id',
        ]);

        $occasions = Occasion::whereIn('id', $request->selected);
        $count = count($request->selected);

        try {
            switch ($request->action) {
                case 'delete':
                    $occasionsWithRelations = Occasion::whereIn('id', $request->selected)
                        ->whereHas('offers')
                        ->count();

                    if ($occasionsWithRelations > 0) {
                        return response()->json([
                            'success' => false,
                            'message' => admin_trans('some_occasions_have_relations')
                        ]);
                    }

                    $occasions->delete();
                    break;

                case 'activate':
                    $occasions->update(['status' => 'active']);
                    break;

                case 'deactivate':
                    $occasions->update(['status' => 'draft']);
                    break;

                case 'feature':
                    $occasions->update(['is_featured' => true]);
                    break;

                case 'unfeature':
                    $occasions->update(['is_featured' => false]);
                    break;
            }

            return response()->json([
                'success' => true,
                'message' => "$count " . admin_trans('occasions') . " {$request->action}d " . admin_trans('successfully')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('error_bulk_action')
            ]);
        }
    }

    /**
     * Remove media from occasion
     */
    public function removeMedia(Occasion $occasion, $collection)
    {
        try {
            $occasion->clearMediaCollection($collection);

            return response()->json([
                'success' => true,
                'message' => admin_trans('media_removed_successfully')
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('error_removing_media')
            ], 500);
        }
    }

    /**
     * Get locales for country (AJAX)
     */
    public function getLocalesForCountry(Country $country)
    {
        $locales = Locale::where('country_id', $country->id)
                        ->active()
                        ->ordered()
                        ->with('language')
                        ->get();

        return response()->json([
            'success' => true,
            'locales' => $locales->map(function($locale) {
                return [
                    'id' => $locale->id,
                    'name' => $locale->name,
                    'code' => $locale->code,
                    'language_name' => $locale->language->name ?? '',
                ];
            })
        ]);
    }
}