<?php

namespace App\Services\Admin\Affiliates;

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

class AffiliatesService
{
    /** get affiliate product list */
    public function getProducts(Request $request)
    {
        /** @var LengthAwarePaginator */
        $products = Product::query()
            ->where('status', '!=', 'deleted')
            ->where('status', '!=', 'deep_deleted')
            ->where('status', '!=', 'awaiting')
            ->where('status', '!=', 'rejected')
            ->whereHas('affiliate')
            ->when($request->input('search'), function ($query, $search) {
                $query->where('title', 'like', "%{$search}%");
            })->when($request->input('publish'), function ($query, $publish) {
                if ($publish) {
                    $query->where('status', 'publish');
                }
            })->when($request->input('draft'), function ($query, $draft) {
                if ($draft) {
                    $query->where('status', 'draft');
                }
            })->when($request->input('hasPrice'), function ($query, $hasPrice) {
                if ($hasPrice) {
                    $query->whereHas('inventories', function ($query) {
                        $query->where('status', 'publish');
                    });
                }
            })->orderBy('created_at', 'desc')->with('user')->with('user.store')->paginate(20)->through(fn($product) => [
                'id' => $product->id,
                'user_id' => $product->user_id,
                'uuid' => $product->uuid,
                'title' => $product->title,
                'slug' => $product->slug,
                'get_images' => $product->get_images,
                'is_vip' => $product->is_vip,
                'get_affiliate' => $product->get_affiliate,
                'status' => $product->status,
                'user' => [
                    'id' => $product->user->id,
                    'get_name' => $product->user->get_name,
                    'type' => $product->user->type,
                    'seller' => $product->user->seller,
                    'store' => $product->user->store != null ? [
                        'id' => $product->user->store->id,
                        'uuid' => $product->user->store->uuid,
                        'name' => $product->user->store->name,
                    ] : null,
                ],
            ]);

        $products->withQueryString();

        return $products;
    }
}
