<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Produk;

class LandingController extends Controller
{
    public function index(Request $request)
    {
        $query = Produk::with('petani')->latest();

        if ($request->has('kategori') && $request->kategori != '' && $request->kategori != 'Semua') {
            $slug = $request->kategori;

            $query->whereHas('kategori', function ($q) use ($slug) {
                $q->where('slug', $slug);
            });
        }

        $produks = $query->take(8)->get();

        if ($request->ajax()) {
            return view('landing.partials.product_list', compact('produks'))->render();
        }

        $produkTerlaris = Produk::withSum(['detailTransaksis as total_terjual' => function ($query) {
            $query->whereHas('transaksi', function ($q) {
                $q->where('status', '!=', 'batal');
            });
        }], 'jumlah')
            ->orderByDesc('total_terjual')
            ->take(4)
            ->get();

        return view('landing.home', compact('produks', 'produkTerlaris'));
    }

    public function shop(Request $request)
    {
        $query = Produk::where('stok', '>', 0);

        if ($request->has('search') && $request->search != '') {
            $query->where('nama_produk', 'like', '%' . $request->search . '%');
        }

        // Filter Kategori
        if ($request->has('kategori') && $request->kategori != '') {
            $slug = $request->kategori;
            $query->whereHas('kategori', function ($q) use ($slug) {
                $q->where('slug', $slug);
            });
        }

        // Sorting
        if ($request->has('sort')) {
            switch ($request->sort) {
                case 'termurah':
                    $query->orderBy('harga', 'asc');
                    break;
                case 'termahal':
                    $query->orderBy('harga', 'desc');
                    break;
                case 'terbaru':
                    $query->latest();
                    break;
                default:
                    $query->latest();
                    break;
            }
        } else {
            $query->latest();
        }

        $produks = $query->paginate(9);

        return view('landing.shop', compact('produks'));
    }

    public function detail($id)
    {
        $produk = Produk::with(['kategori', 'petani', 'images'])->findOrFail($id);

        $produk_terkait = Produk::where('kategori_id', $produk->kategori_id)
            ->where('id', '!=', $produk->id)
            ->where('stok', '>', 0)
            ->inRandomOrder()
            ->take(4)
            ->get();

        return view('landing.detail', compact('produk', 'produk_terkait'));
    }
}
