<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Admin;

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

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $search = $request->query('search', '');

        $products = Product::with(['seller:id,name,company_name', 'category:id,name', 'images'])
            ->when($search, function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('id', $search)
                  ->orWhereHas('seller', function ($s) use ($search) {
                      $s->where('name', 'like', "%{$search}%")
                        ->orWhere('company_name', 'like', "%{$search}%");
                  });
            })
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return Inertia::render('cp/Products/Index', [
            'products' => $products,
            'filters' => ['search' => $search]
        ]);
    }

    public function destroy(Product $product, ProductService $productService)
    {
        // Using the ProductService safely deletes the physical images from storage 
        // before deleting the database record, saving server space!
        $productService->deleteProduct($product);
        
        return back()->with('success', 'Product deleted permanently.');
    }
}