<?php


namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Country;
use Illuminate\Http\Request;

class CountryFilterController extends Controller
{
    /**
     * Set country filter
     */
    public function setFilter(Request $request)
    {
        $request->validate([
            'country_id' => 'required|exists:countries,id'
        ]);

        $country = Country::findOrFail($request->country_id);
        
        // Set in session
        set_country_filter($country->id);
        
        return response()->json([
            'success' => true,
            'country' => [
                'id' => $country->id,
                'name' => $country->getName(admin_locale() === 'ar' ? 1 : 2), // Adjust language IDs
                'code' => $country->code,
                'flag_emoji' => $country->flag_emoji,
            ],
            'message' => admin_trans('country_filter_updated')
        ]);
    }

    /**
     * Clear country filter
     */
    public function clearFilter()
    {
        clear_country_filter();
        
        return response()->json([
            'success' => true,
            'message' => admin_trans('country_filter_cleared')
        ]);
    }

    /**
     * Get current filter status
     */
    public function getFilter()
    {
        $country = current_filtered_country();
        
        return response()->json([
            'success' => true,
            'country' => $country ? [
                'id' => $country->id,
                'name' => $country->getName(admin_locale() === 'ar' ? 1 : 2),
                'code' => $country->code,
                'flag_emoji' => $country->flag_emoji,
            ] : null,
            'available_countries' => get_available_countries_for_filter()->map(function($c) {
                return [
                    'id' => $c->id,
                    'name' => $c->getName(admin_locale() === 'ar' ? 1 : 2),
                    'code' => $c->code,
                    'flag_emoji' => $c->flag_emoji,
                ];
            })
        ]);
    }
}