<?php

namespace App\Traits\Product;

use App\Models\Category;
use App\Models\Product;

trait FetchesProductData
{
    /**
     * Get all products for a specific seller with pagination.
     */
    protected function getSellerProducts(int $sellerId, int $perPage = 10)
    {
        return Product::where('seller_id', $sellerId)
            ->with(['category', 'images'])
            // --- NEW: Calculate Total Sold (Excluding Cancelled, Refunded, or Pending unpaid orders) ---
            ->withSum(['orderItems as total_sold' => function($query) {
                $query->whereHas('order', function($q) {
                    $q->whereNotIn('status', ['cancelled', 'refunded', 'pending']);
                });
            }], 'quantity')
            ->latest()
            ->paginate($perPage);
    }

    /**
     * Get a specific product ensuring it belongs to the seller.
     */
    protected function getSellerProductOrFail(int $productId, int $sellerId, array $relations = [])
    {
        $query = Product::where('seller_id', $sellerId);
        
        if (!empty($relations)) {
            $query->with($relations);
        }

        return $query->findOrFail($productId);
    }

    /**
     * Get the category tree (Parents + Subcategories) for dropdowns.
     */
    protected function getCategoryTree()
    {
        return Category::whereNull('parent_id')
            ->with('subcategories')
            ->get();
    }
}