<?php

namespace App\Http\Controllers;

use App\Enums\AssetStatusEnum;
use App\Models\Asset;
use App\Models\AssetCategory;
use App\Models\Opd;
use Illuminate\Http\Request;

class PublicController extends Controller
{
    public function home()
    {
        $categories = AssetCategory::withCount(['assets' => fn ($q) => $q->published()])
            ->orderBy('name')
            ->get();

        $featuredAssets = Asset::with(['category', 'opd', 'primaryContact'])
            ->published()
            ->featured()
            ->latest('published_at')
            ->take(6)
            ->get();

        $latestAssets = Asset::with(['category', 'opd'])
            ->published()
            ->latest('published_at')
            ->take(8)
            ->get();

        $stats = [
            'total_assets' => Asset::published()->count(),
            'available_assets' => Asset::published()->available()->count(),
            'total_categories' => AssetCategory::count(),
            'total_opds' => Opd::count(),
        ];

        return view('public.home', compact('categories', 'featuredAssets', 'latestAssets', 'stats'));
    }

    public function assets(Request $request)
    {
        $categories = AssetCategory::orderBy('name')->get();
        $opds = Opd::orderBy('name')->get();

        $query = Asset::with(['category', 'opd'])
            ->published();

        if ($search = $request->input('q')) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('description', 'like', "%{$search}%")
                    ->orWhere('address', 'like', "%{$search}%");
            });
        }

        if ($categorySlug = $request->input('kategori')) {
            $query->whereHas('category', fn ($q) => $q->where('slug', $categorySlug));
        }

        if ($opdId = $request->input('opd')) {
            $query->where('opd_id', $opdId);
        }

        $sort = $request->input('sort', 'latest');
        match ($sort) {
            'price_asc' => $query->orderBy('rental_price', 'asc'),
            'price_desc' => $query->orderBy('rental_price', 'desc'),
            'name' => $query->orderBy('name', 'asc'),
            default => $query->latest('published_at'),
        };

        $assets = $query->paginate(12)->withQueryString();

        return view('public.assets.index', compact('assets', 'categories', 'opds'));
    }

    public function assetDetail(Asset $asset)
    {
        abort_if(! $asset->published_at || $asset->status === AssetStatusEnum::INACTIVE, 404);

        $asset->load(['category', 'opd', 'contactPersons', 'galleries']);

        $relatedAssets = Asset::with(['category', 'opd'])
            ->published()
            ->where('asset_category_id', $asset->asset_category_id)
            ->where('id', '!=', $asset->id)
            ->take(4)
            ->get();

        return view('public.assets.show', compact('asset', 'relatedAssets'));
    }

    public function categoryDetail(AssetCategory $category, Request $request)
    {
        $assets = Asset::with(['category', 'opd'])
            ->published()
            ->where('asset_category_id', $category->id)
            ->latest('published_at')
            ->paginate(12)
            ->withQueryString();

        return view('public.category-detail', compact('category', 'assets'));
    }

    public function map()
    {
        $categories = AssetCategory::orderBy('name')->get();

        $assets = Asset::with(['category', 'opd'])
            ->published()
            ->whereNotNull('latitude')
            ->whereNotNull('longitude')
            ->get();

        $assets = $assets->map(fn ($a) => [
            'id' => $a->id,
            'name' => $a->name,
            'slug' => $a->slug,
            'category' => $a->category->slug ?? null,
            'category_name' => $a->category->name ?? '-',
            'address' => $a->address,
            'lat' => (float) $a->latitude,
            'lng' => (float) $a->longitude,
        ]);

        return view('public.map', compact('assets', 'categories'));
    }

    public function faq()
    {
        return view('public.faq');
    }

    public function about()
    {
        $opds = Opd::orderBy('name')->get();

        return view('public.about', compact('opds'));
    }

    public function contact()
    {
        $opds = Opd::orderBy('name')->get();

        return view('public.contact', compact('opds'));
    }
}