<?php

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

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AzkiProductsController extends Controller
{
    /**
     * show products
     */
    public function index(Request $request)
    {
        $shopTitle = Cache::remember('setting_shop_title', now()->addMonth(), function () {
            $shopTitle = Setting::where('key', 'shop_title')->first();
            return $shopTitle != null ? $shopTitle->value : null;
        });

        $products = Product::where('status', 'publish')->orderBy('updated_at', 'desc')->paginate(100)
            ->through(function ($product) use ($shopTitle) {
                $prices = [];
                if ($product->inventory && $product->in_stock_status) {
                    $prices['price_before_discount'] = $product->best_normal_price['price'] != null ? (int)str_replace(',', '', $product->best_normal_price['price']) * 10 : null;
                    $prices['total_price'] = $product->best_normal_price['discount_price'] != null ? (int)str_replace(',', '', $product->best_normal_price['discount_price']) * 10 : null;
                }

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

                return [
                    'merchant' => $shopTitle,
                    'name' => $product->title,
                    'category' => $product->category ? $product->category['title'] : null,
                    'description' => $product->title,
                    'image_url' => $product->get_images_link,
                    'listing_url' => route('main.products.show', $product->slug),
                    'ads_id' => $product->uuid,
                    'availability' => $product->inventory && $product->in_stock_status ? 'in stock' : 'out of stock',
                    ...$prices,
                ];
            });

        return response($products);
    }
}
