<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\Country;
use App\Models\Locale;
use App\Models\User;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class StoreController extends Controller
{
    /**
     * Display a listing of stores
     */
    public function index(Request $request)
    {
        $query = Store::with(['translations.locale', 'countries', 'countryStores.stats', 'media', 'user']);

        // 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 stores by country
            $query->whereHas('countries', function ($q) use ($currentCountry) {
                $q->where('countries.id', $currentCountry->id);
            });
        }

        // Locale 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}%");
                })->orWhereHas('user', function ($uq) use ($search) {
                    $uq->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%");
                });
            });
        }

        // Filter by status (via country_store pivot)
        if ($request->filled('status') && $currentCountry) {
            $query->whereHas('countryStores', function ($q) use ($request, $currentCountry) {
                $q->where('country_id', $currentCountry->id)
                  ->where('status', $request->status);
            });
        }

        // Filter by featured
        if ($request->filled('featured') && $currentCountry) {
            $query->whereHas('countryStores', function ($q) use ($request, $currentCountry) {
                $q->where('country_id', $currentCountry->id)
                  ->where('is_featured', $request->featured === '1');
            });
        }

        // Get paginated results
        $stores = $query->paginate(15)->withQueryString();

        // Get all countries and users for the form
        $countries = Country::active()->ordered()->get();
        $users = User::where('role', 'admin')->get(); // Only admins can own stores
        $categories = Category::active()->ordered()->get();

        return view('admin.stores.index', compact(
            'stores', 
            'countries', 
            'availableLocales', 
            'currentCountry',
            'users',
            'categories'
        ));
    }

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

        // 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_store_name_required')
            ])->withInput();
        }

        DB::beginTransaction();
        try {
            // Create store
            $store = Store::create([
                'user_id' => $request->user_id,
            ]);

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

            // Link to countries with pivot data
            foreach ($request->countries as $countryId) {
                $store->countryStores()->create([
                    'country_id' => $countryId,
                    'user_id' => $request->user_id,
                    'status' => $request->status,
                    'is_featured' => $request->boolean('is_featured'),
                    'order' => $request->order ?? 0,
                ]);
            }

            // Link categories to country-stores
            if ($request->filled('categories')) {
                foreach ($store->countryStores as $countryStore) {
                    $countryStore->categories()->sync($request->categories);
                }
            }

            // Handle logo upload
            if ($request->hasFile('logo')) {
                $store->addMediaFromRequest('logo')
                    ->toMediaCollection('logo');
            }

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

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

            // Get country store data for current filtered country
            $currentCountry = current_filtered_country();
            $countryStore = $currentCountry 
                ? $store->countryStores()->where('country_id', $currentCountry->id)->first()
                : $store->countryStores()->first();

            $data = [
                'id' => $store->id,
                'user_id' => $store->user_id,
                'user_name' => $store->user->name ?? 'N/A',
                'order' => $countryStore->order ?? 0,
                'status' => $countryStore->status ?? 'draft',
                'is_featured' => $countryStore->is_featured ?? false,
                'translations' => $store->translations->toArray(),
                'countries' => $store->countries->pluck('id')->toArray(),
                'categories' => $countryStore ? $countryStore->categories->pluck('id')->toArray() : [],
                'logo_url' => $store->getFirstMediaUrl('logo'),
                'stats' => $countryStore->stats ?? null,
            ];

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

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

        // 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_store_name_required')
            ])->withInput();
        }

        DB::beginTransaction();
        try {
            // Update store
            $store->update([
                'user_id' => $request->user_id,
            ]);

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

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

            // Update country-store relations
            // Delete old relations not in the new list
            $store->countryStores()->whereNotIn('country_id', $request->countries)->delete();

            // Update or create country-store relations
            foreach ($request->countries as $countryId) {
                $store->countryStores()->updateOrCreate(
                    ['country_id' => $countryId],
                    [
                        'user_id' => $request->user_id,
                        'status' => $request->status,
                        'is_featured' => $request->boolean('is_featured'),
                        'order' => $request->order ?? 0,
                    ]
                );
            }

            // Update categories for country-stores
            if ($request->filled('categories')) {
                foreach ($store->countryStores as $countryStore) {
                    $countryStore->categories()->sync($request->categories);
                }
            } else {
                foreach ($store->countryStores as $countryStore) {
                    $countryStore->categories()->detach();
                }
            }

            // Handle logo upload
            if ($request->hasFile('logo')) {
                $store->clearMediaCollection('logo');
                $store->addMediaFromRequest('logo')
                    ->toMediaCollection('logo');
            }

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

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

        try {
            $store->delete();
            flash_success(admin_trans('store_deleted_successfully'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_deleting_store'));
        }

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

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

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

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

    /**
     * Toggle store status
     */
    public function toggleStatus(Store $store)
    {
        try {
            $currentCountry = current_filtered_country();
            if (!$currentCountry) {
                flash_error(admin_trans('select_country_first'));
                return back();
            }

            $countryStore = $store->countryStores()
                ->where('country_id', $currentCountry->id)
                ->firstOrFail();

            $newStatus = $countryStore->status === 'active' ? 'draft' : 'active';
            $countryStore->update(['status' => $newStatus]);
            
            flash_success(admin_trans('store_status_updated'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_updating_status'));
        }

        return back();
    }

    /**
     * Toggle store featured status
     */
    public function toggleFeatured(Store $store)
    {
        try {
            $currentCountry = current_filtered_country();
            if (!$currentCountry) {
                flash_error(admin_trans('select_country_first'));
                return back();
            }

            $countryStore = $store->countryStores()
                ->where('country_id', $currentCountry->id)
                ->firstOrFail();

            $countryStore->update(['is_featured' => !$countryStore->is_featured]);

            $message = $countryStore->is_featured
                ? admin_trans('store_featured_successfully')
                : admin_trans('store_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:stores,id',
        ]);

        $stores = Store::whereIn('id', $request->selected);
        $count = count($request->selected);
        $currentCountry = current_filtered_country();

        if (!$currentCountry && in_array($request->action, ['activate', 'deactivate', 'feature', 'unfeature'])) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('select_country_for_bulk_action')
            ]);
        }

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

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

                    $stores->delete();
                    break;

                case 'activate':
                    DB::table('country_store')
                        ->whereIn('store_id', $request->selected)
                        ->where('country_id', $currentCountry->id)
                        ->update(['status' => 'active']);
                    break;

                case 'deactivate':
                    DB::table('country_store')
                        ->whereIn('store_id', $request->selected)
                        ->where('country_id', $currentCountry->id)
                        ->update(['status' => 'draft']);
                    break;

                case 'feature':
                    DB::table('country_store')
                        ->whereIn('store_id', $request->selected)
                        ->where('country_id', $currentCountry->id)
                        ->update(['is_featured' => true]);
                    break;

                case 'unfeature':
                    DB::table('country_store')
                        ->whereIn('store_id', $request->selected)
                        ->where('country_id', $currentCountry->id)
                        ->update(['is_featured' => false]);
                    break;
            }

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

    /**
     * Remove media from store
     */
    public function removeMedia(Store $store, $collection)
    {
        try {
            $store->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 ?? '',
                ];
            })
        ]);
    }

    /**
     * Get store statistics
     */
    public function getStats(Store $store)
    {
        $currentCountry = current_filtered_country();
        
        if (!$currentCountry) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('select_country_first')
            ]);
        }

        $countryStore = $store->countryStores()
            ->where('country_id', $currentCountry->id)
            ->with('stats')
            ->first();

        if (!$countryStore || !$countryStore->stats) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('no_stats_available')
            ]);
        }

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