<?php

namespace App\Http\Controllers\Admin;

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

class LocaleController extends Controller
{
    /**
     * Display a listing of locales
     */
    public function index(Request $request)
    {
        $query = Locale::with(['language', 'country']);

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                  ->orWhere('name', 'like', "%{$search}%")
                  ->orWhereHas('language', function($lq) use ($search) {
                      $lq->where('name', 'like', "%{$search}%")
                        ->orWhere('native_name', 'like', "%{$search}%");
                  })
                  ->orWhereHas('country', function($cq) use ($search) {
                      $cq->where('name', 'like', "%{$search}%")
                        ->orWhere('code', 'like', "%{$search}%");
                  });
            });
        }

        // Get paginated results with ordering
        $locales = $query->ordered()->paginate(10)->withQueryString();
        
        // Get available languages and countries for the create form
        $languages = Language::active()->ordered()->get();
        $countries = Country::active()->ordered()->get();
        
        return view('admin.locales.index', compact('locales', 'languages', 'countries'));
    }

    /**
     * Store a newly created locale
     */
    public function store(Request $request)
    {
        $request->validate([
            'language_id' => 'required|exists:languages,id',
            'country_id' => 'required|exists:countries,id',
            'name' => 'nullable|string|max:255',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_default' => 'nullable|boolean',
        ]);

        DB::beginTransaction();
        try {
            // Check if combination already exists
            $exists = Locale::where('language_id', $request->language_id)
                           ->where('country_id', $request->country_id)
                           ->exists();
            
            if ($exists) {
                flash_error(admin_trans('locale_combination_already_exists'));
                return back()->withInput();
            }

            // If this is set as default, remove default from others
            if ($request->boolean('is_default')) {
                Locale::where('is_default', true)->update(['is_default' => false]);
            }

            // Get language and country for auto-generating code and name
            $language = Language::find($request->language_id);
            $country = Country::find($request->country_id);

            $data = [
                'language_id' => $request->language_id,
                'country_id' => $request->country_id,
                'code' => $language->code . '-' . $country->code, // en-US, ar-EG
                'name' => $request->name ?: $language->name . ' (' . ($country->name ?? $country->code) . ')',
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_default' => $request->boolean('is_default'),
            ];

            Locale::create($data);

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

    /**
     * Update the specified locale
     */
    public function update(Request $request, Locale $locale)
    {
        $request->validate([
            'language_id' => 'required|exists:languages,id',
            'country_id' => 'required|exists:countries,id',
            'name' => 'nullable|string|max:255',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_default' => 'nullable|boolean',
        ]);

        DB::beginTransaction();
        try {
            // Check if combination already exists (excluding current locale)
            $exists = Locale::where('language_id', $request->language_id)
                           ->where('country_id', $request->country_id)
                           ->where('id', '!=', $locale->id)
                           ->exists();
            
            if ($exists) {
                flash_error(admin_trans('locale_combination_already_exists'));
                return back()->withInput();
            }

            // If this is set as default, remove default from others
            if ($request->boolean('is_default')) {
                Locale::where('id', '!=', $locale->id)
                      ->where('is_default', true)
                      ->update(['is_default' => false]);
            }

            // Get language and country for auto-updating code and name
            $language = Language::find($request->language_id);
            $country = Country::find($request->country_id);

            $data = [
                'language_id' => $request->language_id,
                'country_id' => $request->country_id,
                'code' => $language->code . '-' . $country->code,
                'name' => $request->name ?: $language->name . ' (' . ($country->name ?? $country->code) . ')',
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_default' => $request->boolean('is_default'),
            ];

            $locale->update($data);

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

    /**
     * Remove the specified locale
     */
    public function destroy(Locale $locale)
    {
        // Prevent deleting default locale
        if ($locale->is_default) {
            flash_error(admin_trans('cannot_delete_default_locale'));
            return back();
        }

        // Check if locale has related records
        if ($locale->offerTranslations()->count() > 0 || 
            $locale->storeTranslations()->count() > 0 || 
            $locale->pageTranslations()->count() > 0) {
            flash_error(admin_trans('cannot_delete_locale_with_relations'));
            return back();
        }

        try {
            $locale->delete();
            flash_success(admin_trans('locale_deleted_successfully'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_deleting_locale'));
        }

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

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

        DB::beginTransaction();
        try {
            foreach ($request->orders as $order => $id) {
                Locale::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 locale status
     */
    public function toggleStatus(Locale $locale)
    {
        try {
            $newStatus = $locale->status === 'active' ? 'draft' : 'active';
            $locale->update(['status' => $newStatus]);
            
            flash_success(admin_trans('locale_status_updated'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_updating_status'));
        }

        return back();
    }

    /**
     * Set locale as default
     */
    public function setDefault(Locale $locale)
    {
        DB::beginTransaction();
        try {
            // Remove default from all
            Locale::where('is_default', true)->update(['is_default' => false]);

            // Set this as default
            $locale->update(['is_default' => true]);

            DB::commit();
            flash_success(admin_trans('default_locale_updated'));
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_setting_default'));
        }

        return back();
    }

    /**
     * Auto-create locales from all active countries and languages
     */
    public function autoCreate()
    {
        DB::beginTransaction();
        try {
            // Get all active countries and languages
            $countries = Country::active()->get();
            $languages = Language::active()->get();

            if ($countries->isEmpty() || $languages->isEmpty()) {
                flash_error(admin_trans('no_active_countries_or_languages'));
                return back();
            }

            $created = 0;
            $skipped = 0;

            // Loop through all combinations
            foreach ($languages as $language) {
                foreach ($countries as $country) {
                    // Check if combination already exists
                    $exists = Locale::where('language_id', $language->id)
                                   ->where('country_id', $country->id)
                                   ->exists();

                    if ($exists) {
                        $skipped++;
                        continue;
                    }

                    // Create new locale
                    Locale::create([
                        'language_id' => $language->id,
                        'country_id' => $country->id,
                        'code' => $language->code . '-' . $country->code,
                        'name' => $language->name . ' (' . ($country->name ?? $country->code) . ')',
                        'order' => 0,
                        'status' => 'active',
                        'is_default' => false,
                    ]);

                    $created++;
                }
            }

            DB::commit();

            if ($created > 0) {
                $message = admin_trans('auto_create_success');
                $message = str_replace([':created', ':skipped'], [$created, $skipped], $message);
                flash_success($message);
            } else {
                flash_info(admin_trans('all_locales_already_exist'));
            }
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_auto_creating_locales'));
        }

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