<?php

namespace App\Http\Controllers;

use App\Models\Product;
use App\Models\Category;
use App\Models\Page;
use App\Models\Video;
use Illuminate\Http\Request;

class FrontController extends Controller
{
    public function index(Request $request)
    {
        $query = Product::with('category')->where('is_active', true);

        if ($request->has('q')) {
            $query->where('name', 'like', '%' . $request->q . '%');
        }

        if ($request->has('category')) {
            $query->whereHas('category', function($q) use ($request) {
                $q->where('slug', $request->category);
            });
        }

        $products = $query->latest()->paginate(12)->withQueryString();
        $categories = Category::where('is_active', true)->get();
        $videos = Video::active()->get();

        return view('welcome', compact('products', 'categories', 'videos'));
    }

    public function show($slug)
    {
        $product = Product::with(['category', 'testimonials'])->where('slug', $slug)->where('is_active', true)->firstOrFail();
        $relatedProducts = Product::where('category_id', $product->category_id)
            ->where('id', '!=', $product->id)
            ->where('is_active', true)
            ->inRandomOrder()
            ->take(3)
            ->get();

        return view('product-detail', compact('product', 'relatedProducts'));
    }

    public function page(string $slug)
    {
        $page = Page::where('slug', $slug)->where('status', 'published')->firstOrFail();
        return view('page', compact('page'));
    }

    public function pageJson(string $slug)
    {
        $page = Page::where('slug', $slug)->where('status', 'published')->firstOrFail();
        return response()->json([
            'title'            => $page->title,
            'slug'             => $page->slug,
            'content'          => clean($page->content),
            'meta_description' => $page->meta_description,
            'updated_at'       => $page->updated_at->translatedFormat('d F Y'),
            'url'              => route('page.show', $page->slug),
        ]);
    }

    public function sitemap()
    {
        $products = Product::where('is_active', true)->latest()->get();
        $pages = Page::where('status', 'published')->latest()->get();

        return response()->view('sitemap', [
            'products' => $products,
            'pages' => $pages
        ])->header('Content-Type', 'text/xml');
    }
}
