<?php

namespace App\Http\Controllers\Api\PublicApi;

use App\Http\Controllers\Controller;
use App\Http\Resources\ListingDetailResource;
use App\Http\Resources\ListingResource;
use App\Models\Listing;
use App\Models\ListingCategory;
use App\Services\ListingFilterService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ListingController extends Controller
{
    public function __construct(private ListingFilterService $filters)
    {
    }

    public function index(Request $request)
    {
        $perPage = (int) $request->query('per_page', 12);
        $perPage = max(1, min($perPage, 50));

        $query = Listing::query()
            ->published()
            ->with([
                'category',
                'consultantProfile',
                'coverImage',
                'featureValues.feature',
                'consultantProfile.company'
            ])
            // Kartlarda "video" rozeti için sayaç (ilişki yüklenmez, tek alt sorgu).
            ->withCount('videos');

        $this->filters->apply($query, $request);
        $this->filters->applySort($query, $request->query('sort'));

        return ListingResource::collection($query->paginate($perPage)->withQueryString());
    }

    public function show(string $slug)
    {
        $listing = Listing::query()
            ->published()
            ->with([
                'category',
                'consultantProfile.user',
                'consultantProfile.company',
                'media',
                'videos',
                'featureValues.feature',
            ])
            ->where('slug', $slug)
            ->firstOrFail();

        $listing->increment('view_count');

        return new ListingDetailResource($listing);
    }

    /**
     * Dinamik filtre şeması. Kategori verilirse o kategorinin filtrelenebilir
     * feature'larına göre; verilmezse tüm filtrelenebilir feature'lara göre döner.
     * Admin panelden eklenen herhangi bir feature burada otomatik görünür.
     */
    public function filters(Request $request)
    {
        $category = $request->filled('category')
            ? ListingCategory::where('slug', $request->query('category'))->first()
            : null;

        // Sınır hesapları published ilanlar (ve varsa kategori) üzerinden.
        $base = Listing::query()->published();
        if ($category) {
            $base->where('category_id', $category->id);
        }

        $priceBounds = (clone $base)->selectRaw('MIN(price) as min, MAX(price) as max')->first();
        $areaBounds = (clone $base)->selectRaw('MIN(gross_area) as min, MAX(gross_area) as max')->first();

        $cities = (clone $base)->whereNotNull('city')->distinct()->orderBy('city')->pluck('city');
        $countries = (clone $base)->whereNotNull('country')->distinct()->orderBy('country')->pluck('country');

        // Filtrelenebilir feature'lar (kategoriye bağlıysa pivot üzerinden).
        if ($category) {
            $features = $category->features()
                ->where('listing_features.is_active', true)
                ->where('listing_features.is_filterable', true)
                ->get();
        } else {
            $features = \App\Models\ListingFeature::query()
                ->where('is_active', true)
                ->where('is_filterable', true)
                ->orderBy('sort_order')
                ->get();
        }

        $featureSchema = $features->map(function ($feature) use ($category) {
            $item = [
                'key' => $feature->key,
                'name' => $feature->name,
                'input_type' => $feature->input_type,
                'unit' => $feature->unit,
                'options' => $feature->options,
                // Kanonik değer → aktif dil etiketi (filtre panelinde gösterim için).
                'option_labels' => $feature->localizedOptionLabels() ?: null,
            ];

            // number feature'lar için mevcut min/max aralığı.
            if ($feature->input_type === 'number') {
                $range = DB::table('listing_feature_values as fv')
                    ->join('listings as l', 'l.id', '=', 'fv.listing_id')
                    ->where('l.status', 'published')
                    ->when($category, fn ($q) => $q->where('l.category_id', $category->id))
                    ->where('fv.feature_id', $feature->id)
                    ->selectRaw('MIN(fv.value_number) as min, MAX(fv.value_number) as max')
                    ->first();

                $item['range'] = [
                    'min' => $range->min !== null ? (float) $range->min : null,
                    'max' => $range->max !== null ? (float) $range->max : null,
                ];
            }

            return $item;
        })->values();

        return response()->json([
            'data' => [
                'category' => $category ? ['id' => $category->id, 'name' => $category->name, 'slug' => $category->slug] : null,
                'price' => [
                    'min' => $priceBounds->min !== null ? (float) $priceBounds->min : null,
                    'max' => $priceBounds->max !== null ? (float) $priceBounds->max : null,
                ],
                'area' => [
                    'min' => $areaBounds->min !== null ? (float) $areaBounds->min : null,
                    'max' => $areaBounds->max !== null ? (float) $areaBounds->max : null,
                ],
                'cities' => $cities,
                'countries' => $countries,
                'sorts' => [
                    ['key' => 'newest', 'label' => 'En yeni'],
                    ['key' => 'price_asc', 'label' => 'Fiyat (artan)'],
                    ['key' => 'price_desc', 'label' => 'Fiyat (azalan)'],
                    ['key' => 'area_desc', 'label' => 'Alan (büyükten)'],
                    ['key' => 'popular', 'label' => 'En çok görüntülenen'],
                ],
                'features' => $featureSchema,
            ],
        ]);
    }
}
