<?php

if (!defined("ABSPATH")) {
    exit();
}

require_once CRYPTONIQ_DIR_PATH . "admin/validators.php";
require_once CRYPTONIQ_DIR_PATH . "admin/webhooks.php";

if (!class_exists("Redux")) {
    return;
}

$opt_name = CRYPTONIQ_OPTION;
$img_dir = CRYPTONIQ_DIR_URL . "admin/assets/images";

// Set Arguments
// ======================================================

Redux::setArgs($opt_name, [
    "class" => "cryptoniq-options",
    "opt_name" => $opt_name,
    "display_name" => "Cryptoniq",
    "display_version" => CRYPTONIQ_VER,
    "menu_type" => "menu",
    "allow_sub_menu" => true,
    "menu_title" => "Cryptoniq",
    "page_title" => "Cryptoniq",
    "google_api_key" => "",
    "google_update_weekly" => false,
    "async_typography" => true,
    "admin_bar" => true,
    "admin_bar_icon" => "dashicons-portfolio",
    "admin_bar_priority" => 51,
    "global_variable" => "",
    "dev_mode" => false,
    "show_options_object" => false,
    "update_notice" => true,
    "customizer" => false,
    "page_priority" => 51,
    "page_parent" => "themes.php",
    "page_permissions" => "manage_woocommerce",
    "menu_icon" => "",
    "last_tab" => "",
    "page_icon" => "icon-themes",
    "page_slug" => "cryptoniq",
    "save_defaults" => true,
    "default_show" => false,
    "default_mark" => "",
    "show_import_export" => true,
    "transient_time" => 60 * MINUTE_IN_SECONDS,
    "output" => true,
    "output_tag" => false,
    "database" => "",
    "use_cdn" => true,
    'ajax_save' => false,
    "hints" => [
        "icon" => "el el-question-sign",
        "icon_position" => "right",
        "icon_color" => "lightgray",
        "icon_size" => "normal",
        "tip_style" => [
            "color" => "red",
            "shadow" => true,
            "rounded" => false,
            "style" => "",
        ],
        "tip_position" => [
            "my" => "top left",
            "at" => "bottom right",
        ],
        "tip_effect" => [
            "show" => [
                "effect" => "slide",
                "duration" => "500",
                "event" => "mouseover",
            ],
            "hide" => [
                "effect" => "slide",
                "duration" => "500",
                "event" => "click mouseleave",
            ],
        ],
    ],
]);

// Add Sections
// ======================================================

Redux::setSection($opt_name, [
    "title" => esc_html__("License", "cryptoniq"),
    "id" => "tab_license",
    "icon" => "icon ion-md-key",
    "fields" => [
        [
            "id" => "license_key",
            "type" => "text",
            "title" => esc_html__("License Key", "cryptoniq"),
            "subtitle" => sprintf(
                esc_html__('See how to get license key %1$s.', "cryptoniq"),
                '<a href="https://divengine.ticksy.com/article/13647/" target="_blank">' .
                    esc_html__("here", "cryptoniq") .
                    "</a>"
            ),
            "validate_callback" => "cryptoniq_license_validate",
        ],
    ],
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Coins", "cryptoniq"),
    "id" => "tab_coins",
    "icon" => "icon ion-md-cart",
    "fields" => [
        [
            "id" => "pay_coins",
            "class" => "cryptoniq-icons-checkbox",
            "type" => "checkbox",
            "title" => "Coins",
            "options" => [
                "BTC" => "coin: BTC",
                "ETH" => "coin: ETH",
                "LTC" => "coin: LTC",
                "DOGE" => "coin: DOGE",
                "ETH_ARB" => "coin: ETH: ARB",
                "ETH_OP" => "coin: ETH: OP",
                "BNB" => "coin: BNB",
                "SOL" => "coin: SOL",
                "TRX" => "coin: TRX",
            ],
        ],
        [
            "id" => "pay_usdt",
            "class" =>
                "cryptoniq-icons-checkbox cryptoniq-icons-stables cryptoniq-icons-stable-usdt",
            "type" => "checkbox",
            "title" => "USDT",
            "options" => [
                "USDT_ETH" => "coin: ETH",
                "USDT_ETH_ARB" => "coin: ETH: ARB",
                "USDT_ETH_OP" => "coin: ETH: OP",
                "USDT_BNB" => "coin: BNB",
                "USDT_SOL" => "coin: SOL",
                "USDT_TRX" => "coin: TRX",
            ],
        ],
        [
            "id" => "pay_usdc",
            "class" =>
                "cryptoniq-icons-checkbox cryptoniq-icons-stables cryptoniq-icons-stable-usdc",
            "type" => "checkbox",
            "title" => "USDC",
            "options" => [
                "USDC_ETH" => "coin: ETH",
                "USDC_ETH_ARB" => "coin: ETH: ARB",
                "USDC_ETH_OP" => "coin: ETH: OP",
                "USDC_BNB" => "coin: BNB",
                "USDC_SOL" => "coin: SOL",
            ],
        ],
        [
            "id" => "coins_type_break",
            "type" => "switch",
            "title" => "Line Break",
			"subtitle" => "Add line break for coin types",
			'default'  => true,
        ],
    ],
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Wallets", "cryptoniq"),
    "desc" => sprintf(
        esc_html__("Up to 50 addresses for all coins", "cryptoniq"),
        '<a href="https://divengine.ticksy.com/article/13482/" target="_blank">' .
            esc_html__("here", "cryptoniq") .
            "</a>"
    ),
    "id" => "tab_wallets",
    "icon" => "icon ion-md-wallet",
    "fields" => [
        [
            "id" => "wallets_btc",
            "type" => "multi_text",
            "title" => esc_html__("BTC", "cryptoniq"),
            "subtitle" => esc_html__("Add your BTC addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_eth",
            "type" => "multi_text",
            "title" => esc_html__("ETH", "cryptoniq"),
            "subtitle" => esc_html__("Add your ETH addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_ltc",
            "type" => "multi_text",
            "title" => esc_html__("LTC", "cryptoniq"),
            "subtitle" => esc_html__("Add your LTC addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_doge",
            "type" => "multi_text",
            "title" => esc_html__("DOGE", "cryptoniq"),
            "subtitle" => esc_html__("Add your DOGE addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_eth_arb",
            "type" => "multi_text",
            "title" => esc_html__("ETH: Arbitrum", "cryptoniq"),
            "subtitle" => esc_html__("Add your ETH addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_eth_op",
            "type" => "multi_text",
            "title" => esc_html__("ETH: Optimism", "cryptoniq"),
            "subtitle" => esc_html__("Add your ETH addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_bnb",
            "type" => "multi_text",
            "title" => esc_html__("BNB", "cryptoniq"),
            "subtitle" => esc_html__("Add your BNB addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_sol",
            "type" => "multi_text",
            "title" => esc_html__("SOL", "cryptoniq"),
            "subtitle" => esc_html__("Add your SOL addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_trx",
            "type" => "multi_text",
            "title" => esc_html__("TRX", "cryptoniq"),
            "subtitle" => esc_html__("Add your TRX addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdt_eth",
            "type" => "multi_text",
            "title" => esc_html__("ERC20 USDT", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your ERC20 USDT addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdt_eth_arb",
            "type" => "multi_text",
            "title" => esc_html__("Arbitrum One USDT", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your Arbitrum One USDT addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdt_eth_op",
            "type" => "multi_text",
            "title" => esc_html__("Optimism USDT", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your Optimism USDT addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdt_bnb",
            "type" => "multi_text",
            "title" => esc_html__("BEP20 USDT", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your BEP20 USDT addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdt_sol",
            "type" => "multi_text",
            "title" => esc_html__("SOL USDT", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your SOL USDT addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdt_trx",
            "type" => "multi_text",
            "title" => esc_html__("TRC20 USDT", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your TRC20 USDT addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdc_eth",
            "type" => "multi_text",
            "title" => esc_html__("ERC20 USDC", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your ERC20 USDC addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdc_eth_arb",
            "type" => "multi_text",
            "title" => esc_html__("Arbitrum One USDC", "cryptoniq"),
            "subtitle" => esc_html__("Add your USDC addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdc_eth_op",
            "type" => "multi_text",
            "title" => esc_html__("Optimism USDC", "cryptoniq"),
            "subtitle" => esc_html__("Add your USDC addresses", "cryptoniq"),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdc_bnb",
            "type" => "multi_text",
            "title" => esc_html__("BEP20 USDC", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your BEP20 USDC addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
        [
            "id" => "wallets_usdc_sol",
            "type" => "multi_text",
            "title" => esc_html__("SOL USDC", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add your SOL USDC addresses",
                "cryptoniq"
            ),
            "add_text" => esc_html__("Add address", "cryptoniq"),
            "validate_callback" => "cryptoniq_subscribe_wallet",
        ],
    ],
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Prices", "cryptoniq"),
    "id" => "tab_prices",
    "icon" => "icon ion-md-cash",
    "fields" => [
        [
            "id" => "price_coin_show",
            "type" => "checkbox",
            "title" => esc_html__("Show coin prices", "cryptoniq"),
            "subtitle" => esc_html__(
                "Add coin calculated prices near products prices.",
                "cryptoniq"
            ),
            "default" => "1",
        ],
        [
            "id" => "price_coin_ticker",
            "type" => "select",
            "title" => esc_html__("Coin", "cryptoniq"),
            "options" => [
                "BTC" => "BTC",
                "ETH" => "ETH",
                "LTC" => "LTC",
                "DOGE" => "DOGE",
                "BNB" => "BNB",
                "SOL" => "SOL",
                "TRX" => "TRX",
                "USDT" => "USDT",
            ],
            "default" => "BTC",
            "validate" => "not_empty",
            "required" => ["price_coin_show", "=", "1"],
        ],
        [
            "id" => "price_coin_sign",
            "type" => "select",
            "title" => esc_html__("Sign", "cryptoniq"),
            "options" => [
                "text" => esc_html__("Text", "cryptoniq"),
                "icon" => esc_html__("Icon", "cryptoniq"),
            ],
            "default" => "icon",
            "validate" => "not_empty",
            "required" => ["price_coin_show", "=", "1"],
        ],
        [
            "id" => "price_coin_divider",
            "type" => "text",
            "title" => esc_html__("Divider", "cryptoniq"),
            "default" => "/",
            "required" => ["price_coin_show", "=", "1"],
        ],
    ],
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Payment", "cryptoniq"),
    "id" => "tab_payment",
    "icon" => "icon ion-md-cart",
    "fields" => [
        [
            "id" => "order_status",
            "type" => "select",
            "title" => esc_html__("Order Status", "cryptoniq"),
            "subtitle" => esc_html__(
                "Select status for order after completed payment",
                "cryptoniq"
            ),
            "options" => [
                "processing" => "Processing",
                "completed" => "Completed",
                "on-hold" => "On Hold",
            ],
            "default" => "processing",
        ],
    ],
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Titles", "cryptoniq"),
    "id" => "tab_titles",
    "icon" => "icon ion-md-list-box",
    "fields" => [
        [
            "id" => "description",
            "type" => "textarea",
            "title" => esc_html__("Description", "cryptoniq"),
            "subtitle" => esc_html__(
                'Write some description for this payment type. It will be shown in \'Checkout\' page.',
                "cryptoniq"
            ),
            "default" => esc_html__("Pay with cryptocurrencies.", "cryptoniq"),
            "validate" => "not_empty",
        ],
    ],
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Colors", "cryptoniq"),
    "id" => "tab_colors",
    "icon" => "icon ion-md-color-fill",
    "fields" => [
        [
            "id" => "pg_bar_tx_errors",
            "type" => "color",
            "title" => esc_html__("Progress bar: Errors", "cryptoniq"),
            "default" => "#bf4141",
            "transparent" => false,
            "validate" => "color",
        ],
        [
            "id" => "pg_bar_tx_checking",
            "type" => "color",
            "title" => esc_html__("Progress bar: Checking", "cryptoniq"),
            "default" => "#000000",
            "transparent" => false,
            "validate" => "color",
        ],
        [
            "id" => "pg_bar_tx_process",
            "type" => "color",
            "title" => esc_html__("Progress bar: Processing", "cryptoniq"),
            "default" => "#255b40",
            "transparent" => false,
            "validate" => "color",
        ],
    ],
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Support", "cryptoniq"),
    "id" => "tab_help",
    "icon" => "icon ion-md-help-buoy",
    "desc" => sprintf(
        esc_html__(
            'For support, please get in touch via Telegram: %1$s.',
            "cryptoniq"
        ),
        '<a href="https://t.me/div_engine" target="_blank">@div_engine</a>'
    ),
]);

Redux::setSection($opt_name, [
    "title" => esc_html__("Import / Export", "cryptoniq"),
    "id" => "tab_import_export",
    "icon" => "icon ion-md-git-compare",
    "fields" => [
        [
            "id" => "opt-import-export",
            "type" => "import_export",
            "full_width" => true,
        ],
    ],
]);

// Add custom icons
// ======================================================

function cryptoniq_custom_icons()
{
    wp_enqueue_style("cryptoniq-libs-ionicons");
}
add_action(
    "redux/page/" . CRYPTONIQ_OPTION . "/enqueue",
    "cryptoniq_custom_icons"
);


















































/** AJAX endpoint to fetch license dates */
add_action('wp_ajax_cryptoniq_license_dates', function () {
    if ( ! current_user_can('manage_options') ) {
        wp_send_json_error(['message' => 'forbidden'], 403);
    }

    $license_key = cryptoniq_get_option('license_key');
    if ( empty($license_key) ) {
        wp_send_json_error(['message' => 'no_license_key'], 400);
    }

    $url = add_query_arg(
        ['licenseKey' => rawurlencode($license_key)],
        CRYPTONIQ_API_URL . 'license/dates'
    );

    $res = wp_remote_get($url, ['timeout' => 10, 'headers' => ['Accept' => 'application/json']]);
    if ( is_wp_error($res) ) {
        wp_send_json_error(['message' => 'network_error'], 500);
    }

    $code = wp_remote_retrieve_response_code($res);
    $data = json_decode(wp_remote_retrieve_body($res), true);

    if ($code !== 200 || !is_array($data)) {
        wp_send_json_error(['message' => 'bad_response', 'status' => $code], 500);
    }

    wp_send_json_success([
        'created_at' => $data['created_at'] ?? null,
        'expires_at' => $data['expires_at'] ?? null,
    ]);
});

/** Enqueue jQuery */
add_action('admin_enqueue_scripts', function () {
    if ( isset($_GET['page']) && $_GET['page'] === 'cryptoniq' ) {
        wp_enqueue_script('jquery');
    }
});

/** Inject widget in Redux header */
add_action('admin_footer', function () {
    if ( ! is_admin() || !isset($_GET['page']) || $_GET['page'] !== 'cryptoniq' ) return;
    ?>
    <script>
    jQuery(function($){
        var $hdr = $('.redux-container #redux-header');
        if (!$hdr.length) return;

        $hdr.css('position','relative');
        var $wrap = $('#cryptoniq-topbar-wrap');
        if (!$wrap.length) {
            $wrap = $('<div/>',{id:'cryptoniq-topbar-wrap'})
                .appendTo($hdr);
        }

        var $box = $('<div/>',{id:'cryptoniq-topbar-widget'})
            .addClass('status-blue') // default "checking" state
            .html('<span>License: Checking…</span>')
            .appendTo($wrap);

        $.post(ajaxurl, { action:'cryptoniq_license_dates' })
            .done(function(resp){
                if (!resp || !resp.success) throw new Error('bad');

                var expires = resp.data.expires_at ? new Date(resp.data.expires_at) : null;
                var daysLeft = null;
                if (expires) {
                    var now = new Date();
                    var diffMs = expires - now;
                    daysLeft = Math.max(0, Math.ceil(diffMs / (1000*60*60*24)));
                }

                // reset classes
                $box.removeClass('status-blue status-green status-red');

                if (!expires || daysLeft === 0) {
                    $box.addClass('status-red').html('<span>License: Invalid</span>');
                } else {
                    $box.addClass('status-green').html('<span>License: ' + daysLeft + ' days left</span>');
                }
            })
            .fail(function(){
                $box.removeClass('status-blue status-green').addClass('status-red')
                    .html('<span>License: Error</span>');
            });
    });
    </script>
    <?php
});