<?php

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

// Add Custom Meta Box For Orders
// ======================================================

function cryptoniq_custom_order_panel( $order ) {
    $order_id = $order->get_id();

    ?>
    <div class="order_data_column">

        <h3>Cryptoniq</h3>

        <p class="form-field form-field-wide">
            <strong><?php esc_html_e( 'Coin', 'cryptoniq-pro' ); ?>:</strong>
            <br>
            <?php
				$coin_ticker = $order->get_meta( 'cryptoniq_coin_ticker' );
				$coin_name   = cryptoniq_get_coin_data( $coin_ticker, 'name' );

				echo esc_html( $coin_name );
			?>
        </p>

        <p class="form-field form-field-wide">
            <strong><?php esc_html_e( 'Amount of coins', 'cryptoniq-pro' ); ?>:</strong>
            <br>
            <?php echo esc_html( $order->get_meta( 'cryptoniq_coin_amount' ) ); ?>
        </p>

        <p class="form-field form-field-wide">
            <strong><?php esc_html_e( 'Start time', 'cryptoniq-pro' ); ?>:</strong>
            <br>
            <?php echo esc_html( $order->get_meta( 'cryptoniq_time_start' ) ); ?>
        </p>

        <p class="form-field form-field-wide">
            <strong><?php esc_html_e( 'Transaction ID', 'cryptoniq-pro' ); ?>:</strong>
            <br>
            <?php echo esc_html( $order->get_meta( 'cryptoniq_tx' ) ); ?>
        </p>

        <p class="form-field form-field-wide">
            <strong><?php esc_html_e( 'Address', 'cryptoniq-pro' ); ?>:</strong>
            <br>
            <?php echo esc_html( $order->get_meta( 'cryptoniq_coin_wallet' ) ); ?>
        </p>

    </div>
    <?php
}
add_action( 'woocommerce_admin_order_data_after_order_details', 'cryptoniq_custom_order_panel' );


function cryptoniq_save_order_meta_box( $post_id, $post ) {
    // Verify nonce (sanitized + unslashed per WordPress coding standards).
    if ( ! isset( $_POST['cryptoniq_meta_box_nonce_field'] ) ) {
        return;
    }
    $nonce = sanitize_text_field( wp_unslash( $_POST['cryptoniq_meta_box_nonce_field'] ) );
    if ( ! wp_verify_nonce( $nonce, 'cryptoniq_meta_box_nonce' ) ) {
        return;
    }
    // Capability check — only users who can edit the order may update meta.
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    $fields = array(
        'cryptoniq_coin_ticker' => 'sanitize_text_field',
        'cryptoniq_coin_amount' => 'floatval',
        'cryptoniq_time_start'  => 'intval',
        'cryptoniq_tx'          => 'sanitize_text_field',
        'cryptoniq_wallet'      => 'sanitize_text_field',
    );

    foreach ( $fields as $field => $sanitize_callback ) {
        if ( isset( $_POST[ $field ] ) ) {
            $raw   = wp_unslash( $_POST[ $field ] );
            $clean = call_user_func( $sanitize_callback, $raw );
            update_post_meta( $post_id, $field, $clean );
        }
    }
}
add_action( 'woocommerce_process_shop_order_meta', 'cryptoniq_save_order_meta_box', 10, 2 );