<?php

namespace App\Http\Controllers\Api\v1\Emalls;

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

class EmallsProductsController extends Controller
{
    /**
     * show products
     */
    public function index(Request $request)
    {
        $itemPerPage = $request->exists('item_per_page') && is_int((int)$request->item_per_page) && (int)$request->item_per_page > 0
            ? (int)$request->item_per_page
            : 100;

        $products = Product::where('status', 'publish')
            ->orderBy('updated_at', 'desc')
            ->paginate($itemPerPage)
            ->through(function ($product) {
                $props = [];

                if ($product->best_inventory && isset($product->best_inventory['props'])) {
                    $propsCollection = collect($product->best_inventory['props']);

                    // رنگ
                    $colorProp = $propsCollection->firstWhere('name', 'رنگ');
                    if ($colorProp && isset($colorProp['value']) && is_array($colorProp['value'])) {
                        $props['color'] = $colorProp['value']['label'];
                    }

                    // گارانتی
                    $guaranteeProp = $propsCollection->firstWhere('name', 'گارانتی');
                    if ($guaranteeProp && isset($guaranteeProp['value'])) {
                        $props['guarantee'] = $guaranteeProp['value'];
                    }
                }

                return [
                    'title' => $product->title,
                    'id' => $product->uuid,
                    'price' => $product->inventory && $product->in_stock_status ? $product->best_price : null,
                    'old_price' => $product->inventory && $product->in_stock_status && $product->has_discount ? $product->best_inventory['price'] : null,
                    'category' => $product->category ? $product->category['title'] : null,
                    'image' => $product->get_images[0]['link'] ?? null,
                    ...$props,
                    'is_available' => $product->inventory && $product->in_stock_status,
                    'url' => route('main.products.show', $product->slug),
                ];
            });

        return response()->json([
            'success' => true,
            'products' => $products->items(),
            'total_items' => $products->total(),
            'pages_count' => $products->lastPage(),
            'item_per_page' => $products->perPage(),
            'page_num' => $products->currentPage(),
        ]);
    }
}
