<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\HomeSection;
use App\Models\Menu;
use App\Models\Product;
use App\Models\Slider;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class HomeController extends Controller
{
    public function home()
    {
        $data['products'] = Product::paginate(12);

        $data['discounted_products'] = Product::where('discount_price', '>', 0)
            ->whereColumn('discount_price', '<', 'price')
            ->orderBy('discount_price', 'asc')
            ->get();

        $data['tranding'] = Product::latest()->get();

        $data['heroSection'] = Slider::where('type', 'large')->latest()->first();
        $data['smallSliders'] = Slider::where('type', 'small')->get();

        $data['justNowProducts'] = Product::latest()->get();

        $data['menus'] = Menu::whereNull('parent_id')
            ->with('submenus')
            ->orderBy('order')
            ->get();

        try {
            $query = HomeSection::with(['menu.submenus']);

            if (Schema::hasColumn('home_sections', 'is_active')) {
                $query->where('is_active', true);
            }

            if (Schema::hasColumn('home_sections', 'order')) {
                $query->orderBy('order');
            }

            $data['homeSections'] = $query->get();
        } catch (\Throwable $e) {
            Log::error('HomeSections load error: ' . $e->getMessage());
            $data['homeSections'] = collect();
        }

        return view('frontend.home')->with($data);
    }

    public function details(Product $product)
    {
        $product->load(['category', 'subcategory', 'galleries', 'tags', 'variants']);
        $tranding = Product::latest()->get();

        return view('frontend.details', ['product' => $product, 'tranding' => $tranding]);
    }

    public function trending(Product $product)
    {
        $product->load(['category', 'subcategory', 'galleries', 'tags', 'variants']);
        $tranding = Product::latest()->get();

        return view('frontend.details', ['product' => $product, 'tranding' => $tranding]);
    }

    public function cart()
    {
        return view('frontend.cart');
    }

    public function checkout()
    {
        return view('frontend.checkout');
    }

    public function discProduct()
    {
        $data['products'] = Product::paginate(10);
        $data['menus'] = Menu::whereNull('parent_id')
            ->with('submenus')
            ->orderBy('order')
            ->get();

        return view('frontend.home')->with($data);
    }
}
