<?php

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

require_once CRYPTONIQ_DIR_PATH . 'admin/metabox.php';
require_once CRYPTONIQ_DIR_PATH . 'admin/framework/class-cryptoniq-options.php';

/**
 * Build the per-coin multi_text wallet fields.
 *
 * Field IDs (wallets_btc, wallets_eth, …) and validator must stay identical
 * to the previous Redux config so existing wallet data keeps loading.
 */
function cryptoniq_options_build_wallet_fields() {
    $is_pro     = function_exists( 'cryptoniq_is_pro' ) && cryptoniq_is_pro();
    $lite_slugs = array( 'btc', 'eth' );

    $coins = array(
        'btc'          => 'BTC',
        'eth'          => 'ETH',
        'ltc'          => 'LTC',
        'doge'         => 'DOGE',
        'eth_arb'      => esc_html__( 'ETH: Arbitrum', 'cryptoniq-pro' ),
        'eth_op'       => esc_html__( 'ETH: Optimism', 'cryptoniq-pro' ),
        'bnb'          => 'BNB',
        'sol'          => 'SOL',
        'trx'          => 'TRX',
        'usdt_eth'     => esc_html__( 'ERC20 USDT', 'cryptoniq-pro' ),
        'usdt_eth_arb' => esc_html__( 'Arbitrum One USDT', 'cryptoniq-pro' ),
        'usdt_eth_op'  => esc_html__( 'Optimism USDT', 'cryptoniq-pro' ),
        'usdt_bnb'     => esc_html__( 'BEP20 USDT', 'cryptoniq-pro' ),
        'usdt_sol'     => esc_html__( 'SOL USDT', 'cryptoniq-pro' ),
        'usdt_trx'     => esc_html__( 'TRC20 USDT', 'cryptoniq-pro' ),
        'usdc_eth'     => esc_html__( 'ERC20 USDC', 'cryptoniq-pro' ),
        'usdc_eth_arb' => esc_html__( 'Arbitrum One USDC', 'cryptoniq-pro' ),
        'usdc_eth_op'  => esc_html__( 'Optimism USDC', 'cryptoniq-pro' ),
        'usdc_bnb'     => esc_html__( 'BEP20 USDC', 'cryptoniq-pro' ),
        'usdc_sol'     => esc_html__( 'SOL USDC', 'cryptoniq-pro' ),
    );

    $fields = array();
    foreach ( $coins as $slug => $label ) {
        $locked = ! $is_pro && ! in_array( $slug, $lite_slugs, true );
        $field  = array(
            'id'                => 'wallets_' . $slug,
            'type'              => 'multi_text',
            'title'             => $label,
            'subtitle'          => sprintf(
                /* translators: %s: coin label */
                esc_html__( 'Add your %s addresses', 'cryptoniq-pro' ),
                $label
            ),
            'add_text'          => esc_html__( 'Add address', 'cryptoniq-pro' ),
            'unique'            => true, // dedupe within this coin's list
            'validate_full'     => true, // validate once per field with full array
            'validate_callback' => 'cryptoniq_subscribe_wallet',
        );
        if ( $locked ) {
            $field['locked']       = true;
            $field['locked_label'] = esc_html__( 'Not Activated', 'cryptoniq-pro' );
        }
        $fields[] = $field;
    }
    return $fields;
}

/**
 * Resolve a coin SVG URL.
 */
function cryptoniq_coin_icon_url( $slug ) {
    return CRYPTONIQ_DIR_URL . 'admin/assets/svg/coins/' . $slug . '.svg';
}

/**
 * Build the Coins tab — three image_select fields (plain coins / USDT / USDC)
 * plus the line-break switch.
 */
function cryptoniq_options_build_coins_section() {
    // Without a license only BTC and ETH are payable (public-explorer
    // polling). All other coins stay locked until a valid license is set.
    $is_pro     = function_exists( 'cryptoniq_is_pro' ) && cryptoniq_is_pro();
    $lite_coins = array( 'BTC', 'ETH' );

    // Plain coins: key => [ tooltip label, icon-slug ]
    // The tooltip label appears on hover (also used as aria-label for a11y).
    $coins = array(
        'BTC'     => array( 'Bitcoin (BTC)',                  'btc'  ),
        'ETH'     => array( 'Ethereum (ETH) — Mainnet',       'eth'  ),
        'LTC'     => array( 'Litecoin (LTC)',                 'ltc'  ),
        'DOGE'    => array( 'Dogecoin (DOGE)',                'doge' ),
        'ETH_ARB' => array( 'Ethereum (ETH) — Arbitrum One',  'arb'  ),
        'ETH_OP'  => array( 'Ethereum (ETH) — Optimism',      'op'   ),
        'BNB'     => array( 'BNB Smart Chain (BNB)',          'bnb'  ),
        'SOL'     => array( 'Solana (SOL)',                   'sol'  ),
        'TRX'     => array( 'TRON (TRX)',                     'trx'  ),
    );
    $coin_opts = array();
    foreach ( $coins as $k => $info ) {
        $locked = ! $is_pro && ! in_array( $k, $lite_coins, true );
        $coin_opts[ $k ] = array(
            'label'        => $info[0],
            'image'        => cryptoniq_coin_icon_url( $info[1] ),
            'locked'       => $locked,
            'locked_label' => $locked ? $info[0] . ' — Not Activated' : '',
        );
    }

    // Stablecoins: key => [ tooltip label, chain-icon-slug ]
    $usdt_chains = array(
        'USDT_ETH'     => array( 'Tether USD (ERC20) — Ethereum Mainnet',     'eth' ),
        'USDT_ETH_ARB' => array( 'Tether USD — Arbitrum One',          'arb' ),
        'USDT_ETH_OP'  => array( 'Tether USD — Optimism',              'op'  ),
        'USDT_BNB'     => array( 'Tether USD (BEP20) — BNB Smart Chain',    'bnb' ),
        'USDT_SOL'     => array( 'Tether USD — Solana',                'sol' ),
        'USDT_TRX'     => array( 'Tether USD (TRC20) — TRON',         'trx' ),
    );
    // Stablecoins require a license — lock them when none is active.
    $usdt_opts = array();
    foreach ( $usdt_chains as $k => $info ) {
        $usdt_opts[ $k ] = array(
            'label'        => $info[0],
            'image'        => cryptoniq_coin_icon_url( 'usdt' ),
            'badge'        => cryptoniq_coin_icon_url( $info[1] ),
            'locked'       => ! $is_pro,
            'locked_label' => ! $is_pro ? $info[0] . ' — Not Activated' : '',
        );
    }

    $usdc_chains = array(
        'USDC_ETH'     => array( 'USD Coin (ERC20) — Ethereum Mainnet',     'eth' ),
        'USDC_ETH_ARB' => array( 'USD Coin — Arbitrum One',          'arb' ),
        'USDC_ETH_OP'  => array( 'USD Coin — Optimism',              'op'  ),
        'USDC_BNB'     => array( 'USD Coin (BEP20) — BNB Smart Chain',    'bnb' ),
        'USDC_SOL'     => array( 'USD Coin — Solana',                'sol' ),
    );
    $usdc_opts = array();
    foreach ( $usdc_chains as $k => $info ) {
        $usdc_opts[ $k ] = array(
            'label'        => $info[0],
            'image'        => cryptoniq_coin_icon_url( 'usdc' ),
            'badge'        => cryptoniq_coin_icon_url( $info[1] ),
            'locked'       => ! $is_pro,
            'locked_label' => ! $is_pro ? $info[0] . ' — Not Activated' : '',
        );
    }

    $fields = array(
        array(
            'id'      => 'pay_coins',
            'type'    => 'image_select',
            'title'   => esc_html__( 'Coins', 'cryptoniq-pro' ),
            'options' => $coin_opts,
        ),
        array(
            'id'      => 'pay_usdt',
            'type'    => 'image_select',
            'title'   => 'USDT',
            'options' => $usdt_opts,
        ),
        array(
            'id'      => 'pay_usdc',
            'type'    => 'image_select',
            'title'   => 'USDC',
            'options' => $usdc_opts,
        ),
    );

    // Line-break switch only makes sense when there are multiple coin
    // categories visible — without a license only the plain-coins row is
    // unlocked, so the toggle would have no rows to break between.
    if ( $is_pro ) {
        $fields[] = array(
            'id'       => 'coins_type_break',
            'type'     => 'switch',
            'title'    => esc_html__( 'Line Break', 'cryptoniq-pro' ),
            'subtitle' => esc_html__( 'Add line break for coin types', 'cryptoniq-pro' ),
            'default'  => true,
        );
    }

    return array(
        'title'  => esc_html__( 'Coins', 'cryptoniq-pro' ),
        'icon'   => 'icon ion-md-cart',
        'fields' => $fields,
    );
}

/**
 * Build the Prices → Coin radio options (single-pick coin for displayed
 * product-page prices). BTC and ETH are always available; everything else
 * stays locked until a license is active.
 */
function cryptoniq_options_build_price_coin_options() {
    $is_pro     = function_exists( 'cryptoniq_is_pro' ) && cryptoniq_is_pro();
    $lite_coins = array( 'BTC', 'ETH' );

    $coins = array(
        'BTC'  => array( 'Bitcoin (BTC)',  'btc'  ),
        'ETH'  => array( 'Ethereum (ETH)', 'eth'  ),
        'LTC'  => array( 'Litecoin (LTC)', 'ltc'  ),
        'DOGE' => array( 'Dogecoin (DOGE)','doge' ),
        'BNB'  => array( 'BNB',            'bnb'  ),
        'SOL'  => array( 'Solana (SOL)',   'sol'  ),
        'TRX'  => array( 'TRON (TRX)',     'trx'  ),
        'USDT' => array( 'Tether (USDT)',  'usdt' ),
    );

    $out = array();
    foreach ( $coins as $k => $info ) {
        $locked = ! $is_pro && ! in_array( $k, $lite_coins, true );
        $out[ $k ] = array(
            'label'        => $info[0],
            'image'        => cryptoniq_coin_icon_url( $info[1] ),
            'locked'       => $locked,
            'locked_label' => $locked ? $info[0] . ' — Not Activated' : '',
        );
    }
    return $out;
}

/**
 * Build the Lite vs PRO comparison panel content (rich HTML, rendered via the
 * `content` key on the section). Returned string is filtered through wp_kses_post
 * by the framework, so styles need to live in the panel CSS (admin.css).
 */
function cryptoniq_options_build_compare_content() {
    $is_pro = function_exists( 'cryptoniq_is_pro' ) && cryptoniq_is_pro();

    // Feature rows: [ feature label, lite value, pro value ]
    // Values can be a string or the literal markers 'yes' / 'no' (rendered as icons).
    $rows = array(
        array( esc_html__( 'Coins supported',          'cryptoniq-pro' ), 'BTC, ETH', '20+ coins (incl. LTC, DOGE, SOL, TRX, BNB, ARB, OP)' ),
        array( esc_html__( 'Stablecoins (USDT / USDC)','cryptoniq-pro' ), 'no',       'All major chains (ERC-20, TRC-20, BEP-20, SPL, OP, ARB)' ),
        array( esc_html__( 'Transaction detection',    'cryptoniq-pro' ), esc_html__( 'Polling every few seconds', 'cryptoniq-pro' ), esc_html__( 'Instant — push from Cryptoniq API', 'cryptoniq-pro' ) ),
        array( esc_html__( 'Detection reliability',    'cryptoniq-pro' ), esc_html__( 'Public explorer rate-limits', 'cryptoniq-pro' ), esc_html__( 'Dedicated server, no rate-limits', 'cryptoniq-pro' ) ),
        array( esc_html__( 'Fiat currency conversion', 'cryptoniq-pro' ), 'EUR', esc_html__( '150+ currencies', 'cryptoniq-pro' ) ),
        array( esc_html__( 'Show coin prices on product pages', 'cryptoniq-pro' ), 'no', 'yes' ),
        array( esc_html__( 'Wallet addresses (total)', 'cryptoniq-pro' ), esc_html__( '10 addresses', 'cryptoniq-pro' ), esc_html__( '50 addresses', 'cryptoniq-pro' ) ),
        array( esc_html__( 'Multiple wallet addresses per coin','cryptoniq-pro' ), 'yes', 'yes' ),
        array( esc_html__( 'Custom checkout colors',   'cryptoniq-pro' ), 'yes', 'yes' ),
        array( esc_html__( 'Custom checkout description','cryptoniq-pro' ), 'yes', 'yes' ),
        array( esc_html__( 'Priority support',         'cryptoniq-pro' ), 'no', 'yes' ),
        array( esc_html__( 'Lifetime updates',         'cryptoniq-pro' ), 'yes', 'yes' ),
    );

    $cell = function ( $val ) {
        if ( $val === 'yes' ) {
            return '<span class="cn-cmp-yes" aria-label="Yes"><i class="icon ion-md-checkmark"></i></span>';
        }
        if ( $val === 'no' ) {
            return '<span class="cn-cmp-no" aria-label="No"><i class="icon ion-md-close"></i></span>';
        }
        return '<span class="cn-cmp-text">' . esc_html( $val ) . '</span>';
    };

    ob_start();
    ?>
    <div class="cn-compare">
        <div class="cn-compare-table">
            <div class="cn-compare-head">
                <div class="cn-compare-cell cn-cmp-feature">&nbsp;</div>
                <div class="cn-compare-cell cn-cmp-lite">
                    <div class="cn-cmp-plan">Lite</div>
                    <div class="cn-cmp-price"><?php esc_html_e( 'Free', 'cryptoniq-pro' ); ?></div>
                </div>
                <div class="cn-compare-cell cn-cmp-pro">
                    <div class="cn-cmp-plan">PRO</div>
                    <div class="cn-cmp-price"><?php esc_html_e( 'One-time payment', 'cryptoniq-pro' ); ?></div>
                </div>
            </div>

            <?php foreach ( $rows as $row ) : ?>
                <div class="cn-compare-row">
                    <div class="cn-compare-cell cn-cmp-feature"><?php echo esc_html( $row[0] ); ?></div>
                    <div class="cn-compare-cell cn-cmp-lite"><?php echo $cell( $row[1] ); ?></div>
                    <div class="cn-compare-cell cn-cmp-pro"><?php echo $cell( $row[2] ); ?></div>
                </div>
            <?php endforeach; ?>

            <div class="cn-compare-foot">
                <div class="cn-compare-cell cn-cmp-feature">&nbsp;</div>
                <div class="cn-compare-cell cn-cmp-lite">
                    <?php if ( $is_pro ) : ?>
                        <span class="cn-cmp-tag"><?php esc_html_e( 'You are here', 'cryptoniq-pro' ); ?></span>
                    <?php else : ?>
                        <span class="cn-cmp-tag cn-cmp-tag-current"><?php esc_html_e( 'Active', 'cryptoniq-pro' ); ?></span>
                    <?php endif; ?>
                </div>
                <div class="cn-compare-cell cn-cmp-pro">
                    <?php if ( $is_pro ) : ?>
                        <span class="cn-cmp-tag cn-cmp-tag-current"><?php esc_html_e( 'Active', 'cryptoniq-pro' ); ?></span>
                    <?php else : ?>
                        <a class="cn-btn cn-btn-primary cn-cmp-cta" href="https://cryptoniq.io" target="_blank" rel="noopener">
                            <?php esc_html_e( 'Upgrade to PRO', 'cryptoniq-pro' ); ?>
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

/**
 * Lite → PRO upgrade hook.
 *
 * When the user just activated a license (previous license_key was empty,
 * new one is set), re-register every wallet field's saved addresses with
 * the Cryptoniq API. Lite-mode addresses were only format-checked locally
 * and never registered with Tatum, so without this sync the merchant's
 * webhooks wouldn't route.
 *
 * Behavior per coin field:
 *   - empty list → skip
 *   - API accepts the list → addresses are registered (no DB change needed)
 *   - API rejects → that coin's field is cleared, coin name added to the
 *     "rejected" list for the admin notice
 *   - network error → leave the field as-is, merchant can re-save later
 */
add_action( 'update_option_' . CRYPTONIQ_OPTION, 'cryptoniq_sync_wallets_on_upgrade', 10, 2 );
function cryptoniq_sync_wallets_on_upgrade( $old_value, $value ) {
    if ( ! is_array( $value ) ) {
        return;
    }

    $old_license = is_array( $old_value ) && ! empty( $old_value['license_key'] ) ? $old_value['license_key'] : '';
    $new_license = ! empty( $value['license_key'] ) ? $value['license_key'] : '';

    // Only fire on the transition empty → valid license.
    if ( $old_license !== '' || $new_license === '' ) {
        return;
    }

    $synced   = 0;
    $rejected = array(); // [ 'BTC' => ['asdasd', '23r23r23r'], 'ETH' => [...] ]
    $dirty    = false;

    foreach ( $value as $key => $list ) {
        if ( strpos( $key, 'wallets_' ) !== 0 || ! is_array( $list ) || empty( $list ) ) {
            continue;
        }
        $coin = strtoupper( str_replace( 'wallets_', '', $key ) );

        $response = wp_remote_post( CRYPTONIQ_API_URL . 'subscriptions/add', array(
            'headers' => array( 'Content-Type' => 'application/json' ),
            'body'    => wp_json_encode( array(
                'licenseKey' => $new_license,
                'coin'       => $coin,
                'address'    => $list,
            ) ),
            'timeout' => 30,
        ) );

        if ( is_wp_error( $response ) ) {
            continue; // network blip — leave as-is, merchant can re-save
        }

        $code = wp_remote_retrieve_response_code( $response );
        $body = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( $code >= 400 ) {
            // Atomic API: nothing was committed on its side. We can safely
            // drop just the invalid addresses (returned by the API) and
            // keep the rest registered.
            $invalid = ( is_array( $body ) && ! empty( $body['invalidAddresses'] ) && is_array( $body['invalidAddresses'] ) )
                ? array_map( 'strval', $body['invalidAddresses'] )
                : array();

            if ( ! empty( $invalid ) ) {
                $invalid_lc = array_map( 'strtolower', $invalid );
                $kept = array_values( array_filter( $list, function ( $a ) use ( $invalid_lc ) {
                    return ! in_array( strtolower( trim( (string) $a ) ), $invalid_lc, true );
                } ) );

                $value[ $key ]      = $kept;
                $rejected[ $coin ]  = $invalid;
                $synced            += count( $kept ); // valid ones were registered on the retry below
                $dirty              = true;

                // Re-send only the valid ones so they actually land on the API side
                // (the atomic 400 above rolled back EVERYTHING — including the valid ones).
                if ( ! empty( $kept ) ) {
                    wp_remote_post( CRYPTONIQ_API_URL . 'subscriptions/add', array(
                        'headers' => array( 'Content-Type' => 'application/json' ),
                        'body'    => wp_json_encode( array(
                            'licenseKey' => $new_license,
                            'coin'       => $coin,
                            'address'    => $kept,
                        ) ),
                        'timeout' => 30,
                    ) );
                }
            } else {
                // Older API or generic 400 — fall back to "drop the whole list".
                $rejected[ $coin ] = $list;
                $value[ $key ]    = array();
                $dirty            = true;
            }
        } else {
            $synced += count( $list );
        }
    }

    // Persist any drops. We don't recurse: the update_option_ hook only
    // fires on actual changes, and we just re-set the same license_key, so
    // the empty → non-empty check above won't re-trigger this branch.
    if ( $dirty ) {
        update_option( CRYPTONIQ_OPTION, $value );
    }

    set_transient( 'cryptoniq_pro_upgrade_result', array(
        'synced'   => $synced,
        'rejected' => $rejected,
    ), 120 );
}

/**
 * One-time admin notice on the Cryptoniq options page after a successful
 * lite → PRO upgrade — summarises how many wallet addresses got registered
 * with the API, and which coins (if any) had addresses rejected.
 */
add_action( 'admin_notices', 'cryptoniq_pro_upgrade_admin_notice' );
function cryptoniq_pro_upgrade_admin_notice() {
    if ( ! is_admin() || ! isset( $_GET['page'] ) || $_GET['page'] !== 'cryptoniq-pro' ) {
        return;
    }
    $result = get_transient( 'cryptoniq_pro_upgrade_result' );
    if ( ! is_array( $result ) ) {
        return;
    }
    delete_transient( 'cryptoniq_pro_upgrade_result' );

    $synced   = isset( $result['synced'] ) ? (int) $result['synced'] : 0;
    $rejected = isset( $result['rejected'] ) && is_array( $result['rejected'] ) ? $result['rejected'] : array();
    $class    = ! empty( $rejected ) ? 'notice-warning' : 'notice-info';
    ?>
    <div class="notice <?php echo esc_attr( $class ); ?> is-dismissible">
        <p>
            <strong><?php esc_html_e( 'Welcome to Cryptoniq PRO!', 'cryptoniq-pro' ); ?></strong>
            <?php
            if ( $synced > 0 ) {
                printf(
                    /* translators: %d: number of addresses */
                    ' ' . esc_html( _n(
                        '%d wallet address has been verified and registered with the Cryptoniq API.',
                        '%d wallet addresses have been verified and registered with the Cryptoniq API.',
                        $synced,
                        'cryptoniq-pro'
                    ) ),
                    $synced
                );
            } elseif ( empty( $rejected ) ) {
                echo ' ' . esc_html__( 'You can now configure PRO coins, stablecoins, and additional wallet addresses.', 'cryptoniq-pro' );
            }

            if ( ! empty( $rejected ) ) {
                echo '<br><strong>' . esc_html__( 'Rejected by the server (please remove or fix):', 'cryptoniq-pro' ) . '</strong>';
                echo '<ul style="margin:6px 0 0 24px;list-style:disc;">';
                foreach ( $rejected as $coin => $addresses ) {
                    if ( ! is_array( $addresses ) ) continue;
                    echo '<li><code>' . esc_html( $coin ) . '</code>: ' . esc_html( implode( ', ', $addresses ) ) . '</li>';
                }
                echo '</ul>';
            }
            ?>
        </p>
    </div>
    <?php
}

/**
 * Hard-cap total wallet addresses on save. Trims overflow from the order
 * in which fields appear (oldest-key first, newest entries within a field
 * dropped first). Only counts currently-editable wallet keys, so a site
 * whose license expired can still edit BTC/ETH up to the smaller cap
 * while their licensed-coin addresses sit safely in storage.
 */
add_filter( 'pre_update_option_' . CRYPTONIQ_OPTION, 'cryptoniq_enforce_wallet_limit', 10, 1 );
function cryptoniq_enforce_wallet_limit( $value ) {
    if ( ! is_array( $value ) ) {
        return $value;
    }

    $limit  = cryptoniq_wallet_limit();
    $active = cryptoniq_active_wallet_keys();
    $total  = 0;

    foreach ( $active as $key ) {
        if ( empty( $value[ $key ] ) || ! is_array( $value[ $key ] ) ) {
            continue;
        }

        // Drop empty/whitespace rows so they don't eat into the cap.
        $rows = array_values( array_filter( $value[ $key ], function ( $v ) {
            return is_string( $v ) && trim( $v ) !== '';
        } ) );

        $remaining = $limit - $total;
        if ( count( $rows ) > $remaining ) {
            $rows = array_slice( $rows, 0, max( 0, $remaining ) );
        }
        $value[ $key ] = $rows;
        $total += count( $rows );
    }

    return $value;
}

function cryptoniq_load_options_panel() {
    $config = require CRYPTONIQ_DIR_PATH . 'admin/options.php';
    if ( is_array( $config ) ) {
        Cryptoniq_Options::register( $config );
    }
}
add_action( 'init', 'cryptoniq_load_options_panel', 1 );

function cryptoniq_admin_styles() {
    wp_enqueue_style(
        'my-admin-style',
        plugins_url( '/assets/css/cryptoniq.css', __FILE__ ),
        array(),
        CRYPTONIQ_VER
    );

    wp_enqueue_script(
        'my-admin-script',
        plugins_url( '/assets/js/cryptoniq.js', __FILE__ ),
        array(),
        CRYPTONIQ_VER,
        true
    );

    // Pass wallet-cap settings to the admin JS so it can live-count and
    // disable Add buttons when the merchant hits the limit.
    wp_localize_script( 'my-admin-script', 'cryptoniqAdmin', array(
        'walletLimit'  => cryptoniq_wallet_limit(),
        'walletKeys'   => cryptoniq_active_wallet_keys(),
        'isPro'        => cryptoniq_is_pro(),
        'walletLabels' => array(
            'counter'       => __( '%1$d of %2$d addresses used', 'cryptoniq-pro' ),
            'limit_reached' => __( 'Address limit reached', 'cryptoniq-pro' ),
        ),
    ) );
}
add_action( 'admin_enqueue_scripts', 'cryptoniq_admin_styles' );

/**
 * Enqueue Ionicons on the options page (used for tab icons).
 */
function cryptoniq_options_panel_assets() {
    if ( ! is_admin() || ! isset( $_GET['page'] ) || $_GET['page'] !== 'cryptoniq-pro' ) {
        return;
    }
    wp_enqueue_style( 'cryptoniq-libs-ionicons' );
    wp_enqueue_script( 'jquery' );
}
add_action( 'admin_enqueue_scripts', 'cryptoniq_options_panel_assets' );

/**
 * AJAX endpoint to fetch license dates (used by header widget below).
 */
add_action( 'wp_ajax_cryptoniq_license_dates', function () {
    // CSRF protection — nonce is generated in the admin_footer JS block.
    check_ajax_referer( 'cryptoniq_license_dates' );

    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'forbidden' ), 403 );
    }

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

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

    $res = wp_remote_get( $url, array(
        'timeout' => 10,
        'headers' => array( 'Accept' => 'application/json' ),
    ) );
    if ( is_wp_error( $res ) ) {
        wp_send_json_error( array( '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( array( 'message' => 'bad_response', 'status' => $code ), 500 );
    }

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

/**
 * Status badge in the header title row — always visible, instantly tells
 * the merchant whether their license is active. The "days left" pill
 * next to it is a separate widget injected only when a license IS set;
 * this badge is the always-on indicator.
 */
add_action( 'cryptoniq_options/' . CRYPTONIQ_OPTION . '/header_title_extra', 'cryptoniq_render_mode_badge' );
function cryptoniq_render_mode_badge() {
    $is_pro = cryptoniq_is_pro();
    $class  = $is_pro ? 'cn-mode-pro' : 'cn-mode-lite';
    $label  = $is_pro ? esc_html__( 'PRO', 'cryptoniq-pro' ) : esc_html__( 'LITE', 'cryptoniq-pro' );

    $icon = '';
    if ( $is_pro ) {
        $icon = '<i class="icon ion-md-flash cn-mode-icon" aria-hidden="true"></i>';
    }

    echo '<span class="cn-mode-badge ' . esc_attr( $class ) . '">' . $icon . esc_html( $label ) . '</span>';
}

/**
 * Inject the "days left" license-status widget into the options-page
 * header. Only runs when a license is set — without one there's nothing
 * meaningful to show, and no reason to hit api.cryptoniq.io for
 * /license/dates on every options page load.
 */
add_action( 'admin_footer', function () {
    if ( ! is_admin() || ! isset( $_GET['page'] ) || $_GET['page'] !== 'cryptoniq-pro' ) {
        return;
    }
    if ( ! cryptoniq_is_pro() ) {
        return;
    }
    ?>
    <script>
    jQuery(function ($) {
        var $target = $('.cryptoniq-options-wrap .cn-header-title');
        if (!$target.length) return;

        var icon = function (name) {
            return '<i class="icon ion-md-' + name + '" aria-hidden="true"></i>';
        };

        var $box = $('<div/>', { id: 'cryptoniq-topbar-widget' })
            .addClass('status-blue')
            .html(icon('sync') + '<span>License: Checking…</span>')
            .appendTo($target);

        $.post(ajaxurl, {
            action: 'cryptoniq_license_dates',
            _ajax_nonce: '<?php echo esc_js( wp_create_nonce( '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 diffMs = expires - new Date();
                    daysLeft = Math.max(0, Math.ceil(diffMs / (1000 * 60 * 60 * 24)));
                }

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

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