<?php

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

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

class SnapppayProductsController extends Controller
{
    /**
     * show products
     */
    public function index(Request $request)
    {
        $products = Product::where('status', 'publish')->orderBy('updated_at', 'desc')->paginate(100)
            ->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'];
                    }

                    // اصالت
                    if ($product->best_inventory) {
                        $props['original'] = $product->best_inventory['original'];
                    }

                    // وضعیت
                    if ($product->best_inventory) {
                        $props['used'] = $product->best_inventory['used'];
                    }
                }

                $prices = [];
                if ($product->inventory && $product->in_stock_status && $product->best_inventory != null) {
                    $prices['regular_price'] = $product->best_inventory['price'] * 10;
                    $prices['sale_price'] = $product->best_price * 10;
                }

                $description = [];
                foreach ($product->get_attrs as $item) {
                    $description[$item['key']] = $item['value'];
                }

                return [
                    'id' => $product->uuid,
                    'title' => $product->title,
                    'subtitle' => $product->title_en,
                    'link' => route('main.products.show', $product->slug),
                    'image_link' => $product->get_images_link,
                    'availability' => $product->inventory && $product->in_stock_status ? 'in stock' : 'out of stock',
                    ...$prices,
                    'category' => $product->category ? $product->category['title'] : null,
                    'description' => $description,
                    'brand' => $product->brand ? $product->brand['title'] : null,
                    ...$props,
                ];
            });

        return response($products);
    }
}
