<?php

namespace App\Http\Controllers\Admin;

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

class CountryController extends Controller
{
    /**
     * Display a listing of countries
     */
    public function index(Request $request)
    {
        $query = Country::with('translations');

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

        // Get paginated results with ordering
        $countries = $query->ordered()->paginate(10)->withQueryString();
        
        return view('admin.countries.index', compact('countries'));
    }

    /**
     * Store a newly created country
     */
    public function store(Request $request)
    {
        // Log the incoming request data
        \Log::info('Country store request data:', $request->all());
        
        try {
            $validator = \Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'code' => 'required|string|max:2|unique:countries,code',
                'iso_code' => 'nullable|string|max:3',
                'iso2' => 'nullable|string|max:2',
                'dial_code' => 'nullable|string|max:10',
                'currency' => 'nullable|string|max:3',
                'currency_code' => 'nullable|string|max:3',
                'currency_symbol' => 'nullable|string|max:8',
                'flag_url' => 'nullable|url|max:500',
                'order' => 'nullable|integer|min:0',
                'status' => 'required|in:draft,active',
                'is_default' => 'nullable|boolean',
                'fetch_from_api' => 'nullable|in:0,1,true,false', // Accept multiple formats
            ]);

            if ($validator->fails()) {
                \Log::error('Validation failed for country store:', $validator->errors()->toArray());
                return back()->withErrors($validator)->withInput();
            }

        } catch (\Exception $e) {
            \Log::error('Exception in country store validation:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            flash_error('Validation error: ' . $e->getMessage());
            return back()->withInput();
        }

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

            $data = $request->only([
                'name', 'code', 'iso_code', 'iso2', 'dial_code', 
                'currency', 'currency_code', 'currency_symbol', 
                'flag_url', 'order', 'status', 'is_default'
            ]);

            \Log::info('Processed data for country creation:', $data);

            // Create country with API data if requested
            if ($request->boolean('fetch_from_api') && !empty($data['iso_code'])) {
                $country = Country::createWithApiData($data);
            } else {
                $country = Country::create($data);
            }

            \Log::info('Country created successfully:', ['id' => $country->id]);

            DB::commit();
            flash_success(admin_trans('country_created_successfully'));
            return redirect()->route('admin.countries.index');
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Exception in country store creation:', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);
            flash_error('Creation error: ' . $e->getMessage());
            return back()->withInput();
        }
    }

    /**
     * Update the specified country
     */
    public function update(Request $request, Country $country)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:2|unique:countries,code,' . $country->id,
            'iso_code' => 'nullable|string|max:3',
            'iso2' => 'nullable|string|max:2',
            'dial_code' => 'nullable|string|max:10',
            'currency' => 'nullable|string|max:3',
            'currency_code' => 'nullable|string|max:3',
            'currency_symbol' => 'nullable|string|max:8',
            'flag_url' => 'nullable|url|max:500',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_default' => 'nullable|boolean',
            'fetch_from_api' => 'nullable|boolean',
        ]);

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

            $data = $request->only([
                'name', 'code', 'iso_code', 'iso2', 'dial_code', 
                'currency', 'currency_code', 'currency_symbol', 
                'flag_url', 'order', 'status', 'is_default'
            ]);

            // Fetch from API if requested
            if ($request->boolean('fetch_from_api') && !empty($data['iso_code'])) {
                $apiData = Country::fetchCountryData($data['iso_code']);
                if ($apiData) {
                    // Merge API data with form data (form data takes priority)
                    $data = array_merge($apiData, $data);
                }
            }

            $country->update($data);

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

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

        // Check if country has related records
        if ($country->users()->count() > 0 || $country->countryStores()->count() > 0) {
            flash_error(admin_trans('cannot_delete_country_with_relations'));
            return back();
        }

        try {
            $country->delete();
            flash_success(admin_trans('country_deleted_successfully'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_deleting_country'));
        }

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

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

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

        return back();
    }

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

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

        return back();
    }

    /**
     * Fetch country data from API
     */
    public function fetchFromApi(Request $request)
    {
        $request->validate([
            'iso_code' => 'required|string|max:3',
        ]);

        try {
            $countryData = Country::fetchCountryData($request->iso_code);
            
            if ($countryData) {
                return response()->json([
                    'success' => true,
                    'data' => $countryData
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => admin_trans('country_not_found_in_api')
                ], 404);
            }
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => admin_trans('error_fetching_from_api')
            ], 500);
        }
    }

    /**
     * Update flag URL from API
     */
    public function updateFlag(Country $country)
    {
        try {
            if ($country->updateFlagFromApi()) {
                flash_success(admin_trans('flag_updated_successfully'));
            } else {
                flash_error(admin_trans('error_updating_flag'));
            }
        } catch (\Exception $e) {
            flash_error(admin_trans('error_updating_flag'));
        }

        return back();
    }

    /**
     * Manage country translations
     */
    public function translations(Country $country)
    {
        $languages = Language::active()->ordered()->get();
        $translations = $country->translations()->with('language')->get()->keyBy('language_id');
        
        return view('admin.countries.translations', compact('country', 'languages', 'translations'));
    }

    /**
     * Store/Update country translation
     */
    public function storeTranslation(Request $request, Country $country)
    {
        $request->validate([
            'language_id' => 'required|exists:languages,id',
            'name' => 'required|string|max:255',
        ]);

        try {
            $country->translations()->updateOrCreate(
                ['language_id' => $request->language_id],
                ['name' => $request->name]
            );

            flash_success(admin_trans('translation_saved_successfully'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_saving_translation'));
        }

        return back();
    }
}