<?php
/**
 * M2C Shortcodes
 * Provides shortcodes for embedding M2C functionality
 */

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

class M2C_Shortcodes {
    
    public function __construct() {
        add_shortcode('m2c_wallet_connect', array($this, 'wallet_connect_button'));
        add_shortcode('m2c_payment_qr', array($this, 'payment_qr_generator'));
        add_shortcode('m2c_balance', array($this, 'wallet_balance'));
        add_shortcode('m2c_rewards', array($this, 'rewards_display'));

        // NFT shared-trust buy-by-QR (scan with any EIP-681 capable wallet:
        //   Red Envelope Wallet, MetaMask Mobile, Trust Wallet, OKX, etc.)
        add_shortcode('m2c_nft_share', array($this, 'nft_share_buy_qr'));

        // Light-weight status polling for the shortcode UI
        add_action('rest_api_init', array($this, 'register_nft_share_endpoints'));
    }
    
    /**
     * Wallet connect button shortcode
     * Usage: [m2c_wallet_connect]
     */
    public function wallet_connect_button($atts) {
        $atts = shortcode_atts(array(
            'text' => __('Connect M2C Wallet', 'ab2bc-red-envelope'),
            'class' => 'm2c-connect-btn',
        ), $atts);
        
        ob_start();
        ?>
        <button class="<?php echo esc_attr($atts['class']); ?>" onclick="connectM2CWallet()">
            <?php echo esc_html($atts['text']); ?>
        </button>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Payment QR generator shortcode
     * Usage: [m2c_payment_qr amount="100" token="USDC"]
     */
    public function payment_qr_generator($atts) {
        $atts = shortcode_atts(array(
            'amount' => '0',
            'token' => 'USDC',
            'merchant' => get_option('m2c_merchant_wallet_address', ''),
        ), $atts);
        
        if (empty($atts['merchant'])) {
            return '<p class="error">' . __('Merchant wallet not configured', 'ab2bc-red-envelope') . '</p>';
        }
        
        $qr_generator = new M2C_QR_Generator();
        $qr_data = $qr_generator->generate_payment_qr(array(
            'order_id' => 0,
            'amount' => floatval($atts['amount']),
            'token' => $atts['token'],
            'merchant_wallet' => $atts['merchant'],
            'customer_wallet' => '',
            'expiry_minutes' => 10,
        ));
        
        $qr_string = json_encode($qr_data);
        
        ob_start();
        ?>
        <div class="m2c-shortcode-qr">
            <div id="m2c-qr-<?php echo md5($qr_string); ?>"></div>
            <script>
            new QRCode(document.getElementById('m2c-qr-<?php echo md5($qr_string); ?>'), {
                text: <?php echo json_encode($qr_string); ?>,
                width: 256,
                height: 256
            });
            </script>
        </div>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Wallet balance display shortcode
     * Usage: [m2c_balance address="0x..."]
     */
    public function wallet_balance($atts) {
        $atts = shortcode_atts(array(
            'address' => '',
            'chain' => 'aqy',
        ), $atts);
        
        if (empty($atts['address'])) {
            return '<p class="error">' . __('Wallet address required', 'ab2bc-red-envelope') . '</p>';
        }
        
        $api = new M2C_API_Client();
        $balance = $api->get_wallet_balance($atts['address'], $atts['chain']);
        
        if (isset($balance['error'])) {
            return '<p class="error">' . esc_html($balance['error']) . '</p>';
        }
        
        ob_start();
        ?>
        <div class="m2c-balance-display">
            <h4><?php _e('Wallet Balance', 'ab2bc-red-envelope'); ?></h4>
            <?php if (isset($balance['balances'])): ?>
                <ul class="m2c-balance-list">
                    <?php foreach ($balance['balances'] as $token => $amount): ?>
                        <li>
                            <span class="token"><?php echo esc_html($token); ?></span>
                            <span class="amount"><?php echo number_format($amount, 4); ?></span>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php else: ?>
                <p><?php _e('No balance data available', 'ab2bc-red-envelope'); ?></p>
            <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }
    
    /**
     * Rewards display shortcode
     * Usage: [m2c_rewards address="0x..."]
     */
    public function rewards_display($atts) {
        $atts = shortcode_atts(array(
            'address' => '',
            'limit' => 10,
        ), $atts);
        
        if (empty($atts['address'])) {
            return '<p class="error">' . __('Wallet address required', 'ab2bc-red-envelope') . '</p>';
        }
        
        $api = new M2C_API_Client();
        $distributions = $api->get_aqy_distributions($atts['address'], intval($atts['limit']));
        
        if (isset($distributions['error'])) {
            return '<p class="error">' . esc_html($distributions['error']) . '</p>';
        }
        
        ob_start();
        ?>
        <div class="m2c-rewards-display">
            <h4><?php _e('AQY Rewards History', 'ab2bc-red-envelope'); ?></h4>
            <?php if (!empty($distributions['data'])): ?>
                <table class="m2c-rewards-table">
                    <thead>
                        <tr>
                            <th><?php _e('Date', 'ab2bc-red-envelope'); ?></th>
                            <th><?php _e('Amount', 'ab2bc-red-envelope'); ?></th>
                            <th><?php _e('Type', 'ab2bc-red-envelope'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($distributions['data'] as $dist): ?>
                            <tr>
                                <td><?php echo esc_html(date('Y-m-d H:i', strtotime($dist['created_at']))); ?></td>
                                <td class="amount"><?php echo number_format($dist['aqy_amount'], 4); ?> AQY</td>
                                <td><?php echo esc_html($dist['distribution_type']); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p><?php _e('No rewards yet', 'ab2bc-red-envelope'); ?></p>
            <?php endif; ?>
        </div>
        <?php
        return ob_get_clean();
    }

    /* ------------------------------------------------------------------ *
     *  NFT Shared-Trust Buy-by-QR Shortcode
     *
     *  Usage:
     *    [m2c_nft_share product_id="2081"]
     *    [m2c_nft_share contract="0xABCD..." chain_id="2026"
     *                   share_uuid="050403f5-acd5-48e9-b0e6-8872847be874"
     *                   price_usdc="100"]
     *
     *  Resolves trust contract / chain / share UUID from product meta when
     *  not supplied as attributes, then renders an EIP-681 QR that any
     *  EIP-681 capable wallet (Red Envelope Wallet, MetaMask Mobile, Trust
     *  Wallet, OKX, etc.) can scan to call buyShare(uint256 qty, bytes32 uuid)
     *  on the trust contract pre-filled with the USDC price and uuid.
     * ------------------------------------------------------------------ */
    public function nft_share_buy_qr($atts) {
        $atts = shortcode_atts(array(
            'product_id'  => 0,
            'contract'    => '',
            'chain_id'    => '',
            'share_uuid'  => '',
            'price_usdc'  => '',
            'qty'         => '1',
            'token'       => 'USDC',
            'label'       => __('Scan to buy NFT share', 'ab2bc-red-envelope'),
            'wallet_url'  => 'https://re.ab2bc.com',
        ), $atts, 'm2c_nft_share');

        // Pull missing values from product meta when product_id is provided.
        if (!empty($atts['product_id']) && function_exists('wc_get_product')) {
            $product = wc_get_product(intval($atts['product_id']));
            if ($product) {
                if ($atts['contract']   === '') $atts['contract']   = (string) $product->get_meta('_m2c_trust_contract');
                if ($atts['chain_id']   === '') $atts['chain_id']   = (string) $product->get_meta('_m2c_chain_id');
                if ($atts['share_uuid'] === '') $atts['share_uuid'] = (string) $product->get_meta('_m2c_share_uuid');
                if ($atts['price_usdc'] === '') {
                    $p = (string) $product->get_price();
                    if ($p !== '') $atts['price_usdc'] = $p;
                }
            }
        }

        $missing = array();
        foreach (array('contract','chain_id','share_uuid','price_usdc') as $k) {
            if ($atts[$k] === '' || $atts[$k] === null) $missing[] = $k;
        }
        if ($missing) {
            return '<div class="m2c-nft-share-err" style="padding:12px;border:1px dashed #b91c1c;color:#b91c1c;border-radius:6px;font-family:system-ui,sans-serif">' .
                esc_html__('NFT-share buy QR not configured:', 'ab2bc-red-envelope') .
                ' ' . esc_html(implode(', ', $missing)) .
                '</div>';
        }

        $contract  = trim($atts['contract']);
        $chain_id  = intval($atts['chain_id']);
        $share_uid = trim($atts['share_uuid']);
        $qty       = max(1, intval($atts['qty']));
        $price     = (float) $atts['price_usdc'];
        $token     = sanitize_text_field($atts['token']);

        if (!preg_match('/^0x[a-fA-F0-9]{40}$/', $contract)) {
            return '<div style="color:#b91c1c;font-family:system-ui,sans-serif">' .
                esc_html__('Invalid trust contract address.', 'ab2bc-red-envelope') . '</div>';
        }

        // USDC 6-decimal scaling.
        $amount_units = (string) intval(round($price * $qty * 1e6));

        // UUID -> 0x-prefixed bytes32.
        $hex = strtolower(preg_replace('/[^a-f0-9]/i', '', $share_uid));
        if (strlen($hex) > 64) $hex = substr($hex, 0, 64);
        $hex = str_pad($hex, 64, '0', STR_PAD_LEFT);
        $uuid_b32 = '0x' . $hex;

        // EIP-681 transaction request.
        $eip681 = sprintf(
            'ethereum:%s@%d/buyShare?uint256=%s&bytes32=%s',
            $contract, $chain_id, $amount_units, $uuid_b32
        );

        // Red Envelope deeplink (PWA handles the same intent).
        $deeplink = add_query_arg(array(
            'action'   => 'buyShare',
            'contract' => $contract,
            'chain'    => $chain_id,
            'uuid'     => $share_uid,
            'qty'      => $qty,
            'price'    => $price,
            'token'    => $token,
        ), trailingslashit($atts['wallet_url']) . 'scan');

        $uid = 'm2c-nft-share-' . wp_generate_password(8, false, false);
        $total_display = number_format($price * $qty, 2);

        ob_start();
        ?>
        <div id="<?php echo esc_attr($uid); ?>"
             class="m2c-nft-share-card"
             data-contract="<?php echo esc_attr($contract); ?>"
             data-chain="<?php echo esc_attr($chain_id); ?>"
             data-uuid="<?php echo esc_attr($share_uid); ?>"
             style="max-width:380px;margin:16px auto;padding:20px;border-radius:14px;
                    background:linear-gradient(135deg,#111827 0%,#1f2937 100%);
                    color:#e5e7eb;font-family:system-ui,sans-serif;
                    box-shadow:0 8px 24px rgba(0,0,0,.25);text-align:center;">
            <div style="font-size:18px;font-weight:700;color:#fbbf24;margin-bottom:4px;">
                <?php echo esc_html($atts['label']); ?>
            </div>
            <div style="font-size:13px;color:#cbd5e1;margin-bottom:14px;">
                <?php echo esc_html(sprintf(
                    /* translators: 1: qty, 2: price, 3: token, 4: total */
                    __('%1$d share × $%2$s %3$s = $%4$s', 'ab2bc-red-envelope'),
                    $qty, number_format($price, 2), $token, $total_display
                )); ?>
            </div>
            <div class="m2c-nft-qr" style="background:#fff;padding:12px;border-radius:8px;display:inline-block;line-height:0;">
                <img alt="QR" style="display:block;width:240px;height:240px;"
                     src="https://api.qrserver.com/v1/create-qr-code/?size=480x480&qzone=1&data=<?php echo rawurlencode($eip681); ?>" />
            </div>
            <div style="font-size:11px;color:#94a3b8;margin-top:10px;word-break:break-all;">
                <?php echo esc_html(substr($contract, 0, 10) . '…' . substr($contract, -8)); ?>
                · <?php echo esc_html__('chain', 'ab2bc-red-envelope'); ?> <?php echo (int)$chain_id; ?>
            </div>
            <a href="<?php echo esc_url($deeplink); ?>"
               style="display:inline-block;margin-top:14px;padding:10px 18px;border-radius:8px;
                      background:#fbbf24;color:#111827;font-weight:700;text-decoration:none;">
                <?php echo esc_html__('Open in Red Envelope Wallet', 'ab2bc-red-envelope'); ?>
            </a>
            <div class="m2c-nft-status" style="margin-top:12px;font-size:13px;color:#cbd5e1;min-height:18px;">
                <?php echo esc_html__('Waiting for on-chain confirmation…', 'ab2bc-red-envelope'); ?>
            </div>
        </div>
        <script>
        (function(){
            var el = document.getElementById('<?php echo esc_js($uid); ?>');
            if (!el) return;
            var status = el.querySelector('.m2c-nft-status');
            var url = '<?php echo esc_url_raw(rest_url('m2c/v1/nft-share/status')); ?>'
                + '?contract=' + encodeURIComponent(el.dataset.contract)
                + '&chain='    + encodeURIComponent(el.dataset.chain)
                + '&uuid='     + encodeURIComponent(el.dataset.uuid);
            var stopped = false, tries = 0;
            function poll(){
                if (stopped || tries++ > 240) return;            // ~20 min cap
                fetch(url, {credentials:'same-origin', cache:'no-store'})
                    .then(function(r){ return r.json(); })
                    .then(function(j){
                        if (!j) return;
                        if (j.minted) {
                            stopped = true;
                            status.style.color = '#10b981';
                            status.textContent = <?php echo wp_json_encode(__('✅ NFT share delivered to your wallet', 'ab2bc-red-envelope')); ?>;
                            if (j.tx_url) {
                                var a = document.createElement('a');
                                a.href = j.tx_url; a.target = '_blank';
                                a.style.cssText = 'display:block;margin-top:6px;color:#fbbf24;font-size:12px;';
                                a.textContent = <?php echo wp_json_encode(__('View transaction', 'ab2bc-red-envelope')); ?>;
                                status.appendChild(a);
                            }
                        } else if (j.pending) {
                            status.textContent = <?php echo wp_json_encode(__('⏳ Transaction pending…', 'ab2bc-red-envelope')); ?>;
                        }
                    })
                    .catch(function(){})
                    .finally(function(){ if(!stopped) setTimeout(poll, 5000); });
            }
            setTimeout(poll, 3000);
        })();
        </script>
        <?php
        return ob_get_clean();
    }

    /**
     * REST: GET /m2c/v1/nft-share/status
     * Query: contract, chain, uuid, [wallet]
     * Returns: { pending:bool, minted:bool, tx_hash?:string, tx_url?:string }
     *
     * Delegates to the ab2bcRun backend if M2C_BACKEND_URL is defined;
     * otherwise returns { pending:true } so the front-end keeps polling.
     */
    public function register_nft_share_endpoints() {
        register_rest_route('m2c/v1', '/nft-share/status', array(
            'methods'             => 'GET',
            'permission_callback' => '__return_true',
            'callback'            => array($this, 'rest_nft_share_status'),
            'args' => array(
                'contract' => array('required' => true,  'sanitize_callback' => 'sanitize_text_field'),
                'chain'    => array('required' => true,  'sanitize_callback' => 'absint'),
                'uuid'     => array('required' => true,  'sanitize_callback' => 'sanitize_text_field'),
                'wallet'   => array('required' => false, 'sanitize_callback' => 'sanitize_text_field'),
            ),
        ));
    }

    public function rest_nft_share_status($req) {
        $contract = (string) $req->get_param('contract');
        $chain    = (int)    $req->get_param('chain');
        $uuid     = (string) $req->get_param('uuid');
        $wallet   = (string) $req->get_param('wallet');

        if (!preg_match('/^0x[a-fA-F0-9]{40}$/', $contract)) {
            return new WP_REST_Response(array('error' => 'bad_contract'), 400);
        }

        $ckey   = 'm2c_nfts_' . md5($contract . '|' . $chain . '|' . $uuid . '|' . $wallet);
        $cached = get_transient($ckey);
        if (is_array($cached) && !empty($cached['minted'])) {
            return new WP_REST_Response($cached, 200, array(
                'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
            ));
        }

        $backend = defined('M2C_BACKEND_URL') ? rtrim(M2C_BACKEND_URL, '/') : '';
        $result  = array('pending' => true, 'minted' => false);

        if ($backend) {
            $url  = $backend . '/api/nft-share/status?' . http_build_query(array(
                'contract' => $contract,
                'chain'    => $chain,
                'uuid'     => $uuid,
                'wallet'   => $wallet,
            ));
            $resp = wp_remote_get($url, array('timeout' => 4));
            if (!is_wp_error($resp) && wp_remote_retrieve_response_code($resp) === 200) {
                $json = json_decode(wp_remote_retrieve_body($resp), true);
                if (is_array($json)) {
                    $result = array_merge($result, $json);
                }
            }
        }

        if (!empty($result['minted'])) {
            set_transient($ckey, $result, HOUR_IN_SECONDS);
        }

        return new WP_REST_Response($result, 200, array(
            'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
        ));
    }
}

// Initialize only if not already done
if (!isset($GLOBALS['m2c_shortcodes'])) {
    $GLOBALS['m2c_shortcodes'] = new M2C_Shortcodes();
}
