<?php

declare(strict_types=1);

namespace Oktagon\WooCommerce\XConnect;

class Ajax
{
    public function __construct()
    {
        \add_action(
            'wp_ajax_oktagon-x-connect-for-woocommerce-get-shipping-options-in-general',
            [
                $this,
                'getShippingOptionsInGeneral'
            ]
        );
        \add_action(
            'wp_ajax_oktagon-x-connect-for-woocommerce-validate-code',
            [
                $this,
                'validateCode'
            ]
        );
    }

    public function validateCode(): void
    {
        $code = !empty($_POST['code'])
            ? sanitize_text_field($_POST['code'])
            : '';
        $code = str_replace(
            [
                '&gt;',
                '&lt;',
                '&amp;',
                "\\'"
            ],
            [
                '>',
                '<',
                '&',
                "'",
            ],
            $code
        );
        $nonce = !empty($_POST['nonce'])
            ? sanitize_text_field($_POST['nonce'])
            : '';
        $error = '';
        if (
            !\wp_verify_nonce(
                $nonce,
                'woocommerce-settings'
            )
        ) {
            $error = 'Invalid nonce!';
        }
        $valid = false;
        if (!$error) {
            try {
                $parser = new Parser(new Lexer());
                $valid = true;
                $parser->evaluate(
                    $code,
                    [
                        'productCount' => 10,
                        'productQuantitySum' => 200,
                        'subtotal' => 200,
                        'subtotalPostDiscounts' => 300,
                        'weight' => 100,
                    ],
                    [
                        'allProductsInFreightClass' => function (): bool {
                            return false;
                        },
                        'anyProductInFreightClass' => function (): bool {
                            return true;
                        },
                    ],
                    [
                        'allProductsInFreightClass' => 1,
                        'anyProductInFreightClass' => 1,
                    ]
                );
            } catch (\Exception $e) {
                $valid = false;
                $error = $e->getMessage();
            }
        }
        echo wp_json_encode([
            'code' => $code,
            'error' => $error,
            'valid' => $valid,
        ]);
        \wp_die();
    }

    public function getShippingOptionsInGeneral(): void
    {
        $nonce = !empty($_POST['nonce'])
            ? sanitize_text_field($_POST['nonce'])
            : '';
        $locale = '';
        $error = '';
        $options = [];
        $services = [];
        if (
            !\wp_verify_nonce(
                $nonce,
                'woocommerce-settings'
            )
        ) {
            $error = 'Invalid nonce!';
        }
        if (!$error) {
            $locale = Meta::getLocale();

            // NOTE These are shipping options from enabled and activated services
            $options = Meta::getShippingOptionsInGeneral();

            // Build service meta data array with titles and features
            if ($servicesData = Meta::getServices()) {
                $enabledAndActivatedServices = Meta::getEnabledAndActivatedServices();
                foreach ($servicesData as $serviceKey => $serviceData) {
                    if (
                        !empty($serviceData['description'])
                        && is_array($serviceData['description'])
                        && !empty($serviceData['description']['title'])
                        && is_array($serviceData['description']['title'])
                        && isset($serviceData['attributes'])
                        && is_array($serviceData['attributes'])
                        && isset($serviceData['features'])
                        && is_array($serviceData['features'])
                    ) {
                        $services[$serviceKey] = [
                            'attributes' => $serviceData['attributes'],
                            'enabled' => !empty($enabledAndActivatedServices[$serviceKey]),
                            'features' => $serviceData['features'],
                            'title' => $serviceData['description']['title'],
                        ];
                    }
                }
            }
        }
        echo wp_json_encode([
            'error' => $error,
            'locale' => $locale,
            'options' => $options,
            'services' => $services,
        ]);
        \wp_die();
    }
}
