<?php

namespace App\Http\Controllers\Api\PublicApi;

use App\Http\Controllers\Controller;
use App\Http\Resources\Category as CategoryResource;
use App\Http\Resources\ListingResource;
use App\Models\Category;
use App\Models\Faq;
use App\Models\Listing;
use Illuminate\Http\Request;

class HomePageController extends Controller
{
    public function index(Request $request)
    {
        $featuredCategories = Category::query()
            ->featured()
            ->active()
            ->orderBy('sort_order')
            ->limit(4)
            ->get();

        $featuredListings = Listing::query()
            ->featured()
            ->published()
            ->with(['category', 'consultantProfile', 'coverImage', 'featureValues.feature'])
            ->latest()
            ->limit(8)
            ->get();


        // Soru/cevap {tr, en} objesi olarak gider; aktif dile çözümleme frontend'de.
        $faqs = Faq::query()
            ->where('status', Faq::STATUS_PUBLISHED)
            ->orderBy('order')
            ->orderBy('id')
            ->get()
            ->map(fn (Faq $faq) => [
                'id' => $faq->id,
                'question' => $faq->getTranslations('question'),
                'answer' => $faq->getTranslations('answer'),
                'order' => $faq->order,
            ])
            ->values();


        $categoryPreviews = [];
        foreach ($featuredCategories as $category) {
            $categoryPreviews[$category->slug] = Listing::query()
                ->where('category_id', $category->id)
                ->published()
                ->with('coverImage')
                ->latest()
                ->limit(3)
                ->get()
                ->map(fn(Listing $listing) => $this->previewArray($listing))
                ->values();
        }

        $cityRows = Listing::query()
            ->published()
            ->whereNotNull('city')
            ->where('city', '!=', '')
            ->selectRaw('city, COUNT(*) as total')
            ->groupBy('city')
            ->orderByDesc('total')
            ->limit(6)
            ->get();

        $popularCities = $cityRows->map(function ($row) {
            $listings = Listing::query()
                ->published()
                ->where('city', $row->city)
                ->with('coverImage')
                ->latest()
                ->limit(4)
                ->get();

            return [
                'city' => $row->city,
                'count' => (int) $row->total,
                'image' => $listings->first()?->coverImage?->file_url
                    ?? $listings->first()?->coverImage?->file_path,
                'previews' => $listings->map(fn(Listing $listing) => $this->previewArray($listing))->values(),
            ];
        });

        return response()->json([
            'data' => [

                'featured_categories' => CategoryResource::collection($featuredCategories),
                'featured_listings' => ListingResource::collection($featuredListings),
                'category_previews' => $categoryPreviews,
                'popular_cities' => $popularCities,
                'faqs' => $faqs
            ],
        ]);
    }


    private function previewArray(Listing $listing): array
    {
        return [
            'id' => $listing->id,
            'slug' => $listing->slug,
            'title' => $listing->title,
            'price' => $listing->price,
            'currency' => $listing->currency,
            'image' => $listing->coverImage?->file_url ?? $listing->coverImage?->file_path,
            'location' => trim(($listing->city ?? '') . ', ' . ($listing->country ?? ''), ', '),
        ];
    }
}
