<?php

namespace App\Http\Controllers;

//use Alfrasc\MatomoTracker\Facades\LaravelMatomoTracker;
use Illuminate\Http\Request;
use App\Models\IkeaProducts;
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\CountryCode;
use App\Models\CurrencyRates;
use Inertia\Inertia;
use App\Http\Controllers\CountryCompareController;

class ProductsCompareController extends Controller
{
    private $countryCompareController;
    public function __construct(CountryCompareController $countryCompareController)
    {
        $this->countryCompareController = $countryCompareController;
    }
    public function compare(Request $request)
    {
        $codes = $request->input("codes");
        $countries = $request->input("countries");
        $online = $request->input("online");
        $text = $request->input("text");
        $country = $request->input("country");

        $vars = ["codes" => $codes, "countries" => $countries, "country" => $country, "online" => $online, "text" => $text, "ip" => $request->ip(), "referer" => $request->headers->get('referer')];

        Log::channel('db')->info("{codes} {countries} {country} {online} {text} {ip} {referer}", $vars );
        //LaravelMatomoTracker::doTrackAction('compare', $text);



        $codes = collect($codes);
        $countries = collect($countries);

        if ($countries != null && count($countries)) {
            $hCountry = CountryCode::countryHash();
            $countries = $countries->map(function ($country) use ($hCountry) {
                return $hCountry[$country["name"]];
            });
        } else {
            $countries = [];
        }

        $cHash = CountryCode::code_countryHash();
        if (is_array($codes) == false)
            $aCodes = $codes;
        else
            $aCodes = $codes->map(function ($code) {
                return $code;
            });

        if ($online == true) {
            Log::info("ONLINE {codes} {countries}", ["codes" => $codes, "countries" => $countries, "online" => $online]);
            $products = $this->countryCompareController->compare($countries, $cHash, $codes);
        } else {
            $products =  IkeaProducts::whereIn("itemNoGlobal", $aCodes);
            if (count($countries)) $products->whereIn("country", $countries);
            $products = $products->get();
        }

        $products = $products->map(function ($product) use ($cHash) {
            $product["countryName"] = $cHash[$product["country"]];
            return $product;
        });
        Log::info("{products}", ["products" => $products]);
        return [
            'products' => $products,
            'countryHash' => $cHash,
        ];
    }
}
