<?php

namespace App\Http\Controllers\Page;

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

class AgenciesController extends Controller
{
    public function index(Request $request)
    {
        $query = Agency::with(['tours' => function ($q) {
            $q->active()->public();
        }])
            ->active()
            ->approved()
            ->withCount(['tours' => function ($q) {
                $q->active()->public();
            }]);

        // İsme göre arama
        if ($request->filled('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        // Şehir filtresi
        if ($request->filled('city')) {
            $query->where('city', $request->city);
        }

        // İş tipi filtresi
        if ($request->filled('business_type')) {
            $query->where('business_type', $request->business_type);
        }

        // Minimum tur sayısı
        if ($request->filled('min_tours')) {
            $query->having('tours_count', '>=', $request->min_tours);
        }

        // Sıralama
        $sortBy = $request->get('sort', 'newest');
        switch ($sortBy) {
            case 'name_asc':
                $query->orderBy('name', 'asc');
                break;
            case 'name_desc':
                $query->orderBy('name', 'desc');
                break;
            case 'tours_most':
                $query->orderBy('tours_count', 'desc');
                break;
            case 'tours_least':
                $query->orderBy('tours_count', 'asc');
                break;
            case 'oldest':
                $query->orderBy('created_at', 'asc');
                break;
            case 'newest':
            default:
                $query->orderBy('created_at', 'desc');
                break;
        }

        // AJAX için JSON response
        if ($request->ajax()) {
            $agencies = $query->paginate(12);
            return response()->json([
                'agencies' => view('page.partials.agency-cards', compact('agencies'))->render(),
                'hasMore' => $agencies->hasMorePages(),
                'nextPage' => $agencies->currentPage() + 1
            ]);
        }

        $agencies = $query->paginate(12);

        // Şehir listesi
        $cities = [];

        return view('page.agencies', compact('agencies', 'cities'));
    }
}
