<?php

namespace OtomaticAi\Utils\Amazon;

use OtomaticAi\Utils\Settings;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class Amazon
{
    static public function shortcode($atts)
    {
        $atts = shortcode_atts([
            "template" => "grid_3x",
            "products" => "",
        ], $atts, 'otomatic-ai-amazon-products');

        // products
        $products = json_decode(base64_decode($atts['products']), true);

        // template
        $template = $atts['template'];

        if (empty($products)) {
            return '';
        }

        // override template for mobile
        if (function_exists('wp_is_mobile') && wp_is_mobile()) {
            $template = "grid_1x";
        }

        return self::make($products, $template);
    }

    static public function enqueueStyles()
    {
        // check if we are on a post/page and that the content contains the shortcode
        if (get_post() && has_shortcode(get_post()->post_content, 'otomatic-ai-amazon-products')) {
            wp_enqueue_style(
                'otomatic-ai-amazon-products',
                OTOMATIC_AI_ROOT_URL . 'public/css/amazon-products.css',
                [],
                OTOMATIC_AI_VERSION
            );
        }
    }

    static public function make($products, $template)
    {
        $html = [];

        // schema.org
        $schema = [
            "@context" => "https://schema.org",
            "@type" => "Product",
            "name" => Arr::get($products, "0.title"),
            "aggregateRating" => [
                "ratingValue" => floatval(Arr::get($products, "0.stars", 0)),
                "reviewCount" => intval(Arr::get($products, "0.ratings", 0)),
            ]
        ];
        $html[] = '<script type="application/ld+json">' . json_encode($schema) . '</script>';

        // products
        switch ($template) {
            case "list":
                $html[] = '<div class="amazon-products" data-template="' . $template . '">';

                foreach ($products as $product) {
                    $html[] = self::makeProduct($product, $template);
                }

                $html[] = '</div>';
                break;
            case "grid_1x":
            case "grid_2x":
            case "grid_3x":
                $html[] = '<div class="amazon-products" data-template="' . $template . '">';

                foreach ($products as $product) {
                    $html[] = self::makeProduct($product, $template);
                }

                $html[] = '</div>';
                break;
            default:
                return '';
        }

        return implode("\n", $html);
    }

    static public function makeProduct($product, $template)
    {
        $html = [];

        $title = Arr::get($product, "title");
        $asin = Arr::get($product, "asin");
        $priceAmount = Arr::get($product, "price.amount");
        $priceCurrency = Arr::get($product, "price.currency", "USD");
        $ratings = Arr::get($product, "ratings");
        $stars = Arr::get($product, "stars");
        $thumbnail = Arr::get($product, "thumbnail");
        $store = Arr::get($product, "store");

        $affiliateId = Settings::get('amazon.affiliate_id');

        $link = "https://www.$store/dp/$asin";
        if (!empty($affiliateId)) {
            $link = $link . "?tag=$affiliateId";
        }

        if (empty($title) || empty($asin) || empty($store)) {
            return '';
        }

        switch ($template) {
            case "list":
                $html[] = '<div class="amazon-product">';

                if (!empty($thumbnail)) {
                    $html[] = '<div class="amazon-product-thumbnail">';
                    $html[] = '<img src="' . $thumbnail . '" alt="' . $title . '">';
                    $html[] = '</div>';
                }


                $html[] = '<div class="amazon-product-content">';

                $html[] = '<div class="amazon-product-title">' . $title . '</div>';

                $html[] = self::makePrice($priceAmount, $priceCurrency);

                if ($ratings !== null || $stars !== null) {
                    $html[] = '<div class="amazon-product-ratings">';
                    if ($stars !== null) {
                        $html[] = self::makeStars($stars);
                    }
                    if ($ratings !== null) {
                        $html[] = '<span>' . $ratings . '</span>';
                    }

                    $html[] = '</div>';
                }

                $html[] = '<div class="amazon-product-button">';
                $html[] = '<a href="' . $link . '" target="_blank" rel="nofollow">';
                $html[] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/></svg>';
                $html[] = '</a>';
                $html[] = '</div>';

                $html[] = '</div>';

                $html[] = '</div>';
                break;
            case "grid_1x":
            case "grid_2x":
            case "grid_3x":
                $html[] = '<div class="amazon-product">';

                $html[] = '<div class="amazon-product-content">';

                if (!empty($thumbnail)) {
                    $html[] = '<div class="amazon-product-thumbnail">';
                    $html[] = '<img src="' . $thumbnail . '" alt="' . $title . '">';
                    $html[] = '</div>';
                }


                $html[] = '<div class="amazon-product-title">' . $title . '</div>';

                $html[] = self::makePrice($priceAmount, $priceCurrency);

                if ($ratings !== null || $stars !== null) {
                    $html[] = '<div class="amazon-product-ratings">';
                    if ($stars !== null) {
                        $html[] = self::makeStars($stars);
                    }
                    if ($ratings !== null) {
                        $html[] = '<span>' . $ratings . '</span>';
                    }

                    $html[] = '</div>';
                }

                $html[] = '</div>';

                $html[] = '<div class="amazon-product-button">';
                $html[] = '<a href="' . $link . '" target="_blank" rel="nofollow">';
                $html[] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/></svg>';
                $html[] = '</a>';
                $html[] = '</div>';

                $html[] = '</div>';
                break;
        }

        return implode("\n", $html);
    }

    static public function makePrice($priceAmount, $priceCurrency)
    {
        $html = [];

        if ($priceCurrency === "EUR") {
            $html[] = '<div class="amazon-product-price">' . $priceAmount . '€' . '</div>';
        } else if ($priceCurrency === "USD") {
            $html[] = '<div class="amazon-product-price">$' . $priceAmount . '</div>';
        } else {
            $html[] = '<div class="amazon-product-price">' . $priceAmount . ' ' . $priceCurrency . '</div>';
        }

        return implode("\n", $html);
    }

    static public function makeStars($stars)
    {
        $svgs = [
            "full" => "M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",
            "half" => "M12 18.338a2.1 2.1 0 0 0-.987.244L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.12 2.12 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.12 2.12 0 0 0 1.597-1.16l2.309-4.679A.53.53 0 0 1 12 2",
        ];
        $maxStars = 5;

        if ($stars === null) {
            return '';
        }

        $stars = floatval($stars);

        $html = [];

        $fullStars = floor($stars);
        $halfStar = is_float($stars) ? true : false;
        $emptyStars = $maxStars - $fullStars - ($halfStar ? 1 : 0);

        $html[] = '<div class="amazon-product-stars">';
        for ($i = 0; $i < $fullStars; $i++) {
            $html[] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-type="full"><path d="' . $svgs['full'] . '"/></svg>';
        }

        if ($halfStar) {
            $html[] = '<div class="amazon-product-star-half">';
            $html[] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-type="half-left"><path d="' . $svgs['half'] . '"/></svg>';
            $html[] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-type="half-right"><path d="' . $svgs['half'] . '"/></svg>';
            $html[] = '</div>';
        }

        for ($i = 0; $i < $emptyStars; $i++) {
            $html[] = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" data-type="empty"><path d="' . $svgs['full'] . '"/></svg>';
        }
        $html[] = '</div>';

        return implode("\n", $html);
    }
}
