<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Location;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    public function index()
    {
        try {
            $query = Category::with(['parent']);

            // Check if is_active column exists
            if (Schema::hasColumn('categories', 'is_active')) {
                $query->where('is_active', 1);
            }

            $categories = $query->orderBy('sort_order', 'asc')->get();

            // Get location counts for each category
            $locationCounts = Location::selectRaw('category_id, COUNT(*) as count')
                ->whereNotNull('category_id')
                ->groupBy('category_id')
                ->pluck('count', 'category_id')
                ->toArray();

            // Group categories by parent
            $parentCategories = $categories->whereNull('parent_id');
            $childCategories = $categories->whereNotNull('parent_id');

            // دریافت داده‌های کشورها برای فیلتر جغرافیایی
            $countries = $this->getCountriesWithLocationCount();

            return view('categories.index', compact('parentCategories', 'childCategories', 'locationCounts', 'countries'));
        } catch (\Exception $e) {
            // Log the error
            \Log::error('Error in CategoryController@index: '.$e->getMessage());

            // Get all categories without any conditions as fallback
            $categories = Category::with(['parent'])->get();
            $parentCategories = $categories->whereNull('parent_id');
            $childCategories = $categories->whereNotNull('parent_id');
            $locationCounts = [];
            $countries = collect();

            return view('categories.index', compact('parentCategories', 'childCategories', 'locationCounts', 'countries'));
        }
    }

    public function show($categoryKey)
    {
        try {
            $category = Category::where('category_key', $categoryKey)->firstOrFail();

            // Get all locations in this category
            $locations = Location::where('category_id', $category->id)
                ->where('is_active', 1)
                ->orderBy('created_at', 'desc')
                ->paginate(12);

            // Get child categories if this is a parent category
            $childCategories = Category::where('parent_id', $category->id)
                ->where('is_active', 1)
                ->orderBy('sort_order', 'asc')
                ->get();

            // دریافت داده‌های کشورها برای فیلتر جغرافیایی
            $countries = $this->getCountriesWithLocationCount();

            return view('categories.show', compact('category', 'locations', 'childCategories', 'countries'));
        } catch (\Exception $e) {
            \Log::error('Error in CategoryController@show: '.$e->getMessage());
            abort(404);
        }
    }

    /**
     * دریافت لیست کشورها همراه با تعداد مکان‌ها
     */
    private function getCountriesWithLocationCount()
    {
        $countries = DB::table('state1_countries')
            ->select(
                'state1_countries.id',
                'state1_countries.name as name_fa',
                'state1_countries.name_en',
                'state1_countries.name_ar',
                'state1_countries.iso_code',
                DB::raw('(SELECT COUNT(*) FROM locations WHERE locations.country_id = state1_countries.id AND locations.is_active = 1) as location_count')
            )
            ->where('state1_countries.is_active', 1)
            ->orderByDesc('location_count')
            ->orderBy(DB::raw("COALESCE(state1_countries.name, state1_countries.name_en, state1_countries.name_ar)"))
            ->get();

        // افزودن نام پیش‌فرض برای هر زبان
        foreach ($countries as $country) {
            // نام پیش‌فرض برای نمایش
            $country->name = app()->getLocale() === 'en' ? ($country->name_en ?? $country->name_fa) : (app()->getLocale() === 'ar' ? ($country->name_ar ?? $country->name_fa) : $country->name_fa);
        }
        
        return $countries;
    }
}
