<?php

namespace App\Http\Controllers\Marketplace;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use Inertia\Inertia;

class SearchController extends Controller
{
    // 1. For the Dropdown (Live Search)
    public function suggestions(Request $request)
    {
        $q = $request->query('q', '');

        if (strlen($q) < 2) {
            return response()->json([]);
        }

        // Fetch top 5 matching products securely (UPDATED to include flash_sale_percentage)
        $products = Product::with(['images', 'seller:id,company_name,name,flash_sale_percentage'])
            ->where(function($query) use ($q) {
                // Group the OR logic so it doesn't break other conditions
                $query->where('title', 'like', "%{$q}%")
                      ->orWhereHas('category', function($cat) use ($q) {
                          $cat->where('name', 'like', "%{$q}%");
                      });
            })
            ->select('id', 'title', 'slug', 'price', 'original_price', 'currency_code', 'seller_id', 'is_free_shipping', 'discount_percentage')
            ->take(5)
            ->get();

        return response()->json($products);
    }

    // 2. For the Full Search Page (/search?q=...)
    public function index(Request $request)
    {
        $q = $request->query('q', '');

        // include flash_sale_percentage
        $productsQuery = Product::with(['images', 'seller:id,company_name,name,country_id,flash_sale_percentage', 'seller.country']);

        if (!empty($q)) {
            $productsQuery->where(function($query) use ($q) {
                $query->where('title', 'like', "%{$q}%")
                      ->orWhereHas('category', function($cat) use ($q) {
                          $cat->where('name', 'like', "%{$q}%");
                      });
            });
        }

        // Paginate results (16 items per page)
        $products = $productsQuery->latest()->paginate(16)->withQueryString();

        return Inertia::render('Marketplace/Search', [
            'products' => $products,
            'searchQuery' => $q
        ]);
    }
}