<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

add_action( 'wp_ajax_get_shipment_action', 'get_shipment_action' );

function get_shipment_action() {
    // Admin-only endpoint for the Woo orders list shipment-status modal.
    if ( ! current_user_can( 'manage_woocommerce' ) && ! current_user_can( 'manage_options' ) && ! current_user_can( 'edit_shop_orders' ) ) {
        wp_die( '', '', array( 'response' => 403 ) );
    }

    // Nonce (preferred: X-WP-Nonce from our JS). Keep backward compatibility with legacy TrackFree nonce.
    $nonce = '';
    if ( isset( $_SERVER['HTTP_X_WP_NONCE'] ) ) {
        $nonce = wp_unslash( $_SERVER['HTTP_X_WP_NONCE'] );
    } elseif ( isset( $_REQUEST['_wpnonce'] ) ) {
        $nonce = wp_unslash( $_REQUEST['_wpnonce'] );
    }
    $nonce = is_string( $nonce ) ? sanitize_text_field( $nonce ) : '';
    if ( ! $nonce || ( ! wp_verify_nonce( $nonce, 'tfree_nonce' ) && ! wp_verify_nonce( $nonce, 'TrackFree' ) ) ) {
        wp_die( '', '', array( 'response' => 403 ) );
    }

    $order_id = isset( $_POST['order_id'] ) ? absint( wp_unslash( $_POST['order_id'] ) ) : 0;
    if ( ! $order_id ) {
        wp_die();
    }

    $trackfree_account_api_key = get_option( 'trackfree_account_api_key' );
    $trackfree_account_verify  = get_option( 'trackfree_account_verify' );
    if ( ! $trackfree_account_api_key || ! $trackfree_account_verify ) {
        echo '<div class="trackfree-error-container">' . esc_html__( 'Please connect your TrackFree account to view shipment status.', 'trackfree-woocommerce-tracking' ) . '</div>';
        wp_die();
    }

    $shipment_details = get_post_meta( $order_id, '_trackfree_shipment_details', true );
    if ( ! is_array( $shipment_details ) || empty( $shipment_details ) ) {
        echo '<div class="trackfree-error-container">' . esc_html__( 'No shipments found for this order.', 'trackfree-woocommerce-tracking' ) . '</div>';
        wp_die();
    }

    $total_shipments        = count( $shipment_details );
    $update_shipment_details = $shipment_details;

    $render_shipment = function( $i, $idx, $shipment_values ) use ( $trackfree_account_api_key, &$update_shipment_details ) {
        $trackfree_courier_name    = isset( $shipment_values['courier_name'] ) ? (string) $shipment_values['courier_name'] : '';
        $trackfree_tracking_number = isset( $shipment_values['tracking_num'] ) ? (string) $shipment_values['tracking_num'] : '';

        echo '<div class="trackfree-shipment-content trackfree-tab-content ' . ( $i === 1 ? 'trackfree_active' : '' ) . '" id="shipment-detail_' . (int) $i . '">';

        if ( ! $trackfree_tracking_number ) {
            echo '<p>' . esc_html__( 'No tracking number available for this shipment.', 'trackfree-woocommerce-tracking' ) . '</p>';
            echo '</div>';
            return;
        }

        $track_request = array(
            'key'          => $trackfree_account_api_key,
            'tracking_num' => $trackfree_tracking_number,
            'courier_name' => $trackfree_courier_name,
            'request_type' => 'list',
        );

        $response = wp_remote_get(
            trackfree_url() . '/api/wc_track_data',
            array(
                'sslverify' => tfree_sslverify(),
                'timeout'   => 15,
                'body'      => $track_request,
            )
        );

        if ( is_wp_error( $response ) ) {
            echo '<p>' . esc_html__( 'Unable to fetch tracking details right now.', 'trackfree-woocommerce-tracking' ) . '</p>';
            echo '</div>';
            return;
        }

        $track_data = json_decode( wp_remote_retrieve_body( $response ), true );

        if ( is_array( $track_data ) && ( $track_data['response'] ?? '' ) === 'success' ) {
            // Preserve existing fields (like fulfilment_items) and only update status-related fields.
            $update_shipment_details[ $idx ]['tracking_num']        = $track_data['trackingNum'] ?? $trackfree_tracking_number;
            $update_shipment_details[ $idx ]['courier_name']        = $track_data['courierName'] ?? $trackfree_courier_name;
            $update_shipment_details[ $idx ]['status']              = $track_data['status'] ?? '';
            $update_shipment_details[ $idx ]['estimated_delivery']  = $track_data['estimateDeliveryDate'] ?? '';
            $update_shipment_details[ $idx ]['delivered_date']      = $track_data['deliveredDate'] ?? '';

            echo '<div id="track_details_' . (int) $i . '">';
            shipment_preview_template( $track_data );
            echo '</div>';

            show_shipment_details( $track_data['trackDetails']['trackValues'] ?? array(), $i, 'mb' );
        } else {
            echo '<p>' . esc_html( $trackfree_tracking_number ) . '</p>';
            echo '<p>' . esc_html( $trackfree_courier_name ) . '</p>';
            echo '<p>' . esc_html__( 'This tracking does not exist', 'trackfree-woocommerce-tracking' ) . '</p>';

            // Keep existing tracking/courier but clear status fields.
            $update_shipment_details[ $idx ]['tracking_num']       = $trackfree_tracking_number;
            $update_shipment_details[ $idx ]['courier_name']       = $trackfree_courier_name;
            $update_shipment_details[ $idx ]['status']             = '';
            $update_shipment_details[ $idx ]['estimated_delivery'] = '';
            $update_shipment_details[ $idx ]['delivered_date']     = '';
        }

        echo '</div>';
    };

    if ( $total_shipments > 1 ) {
        echo '<div class="media-router" style="margin-top:10px;">';
        for ( $t = 1; $t <= $total_shipments; $t++ ) {
            echo '<a href="javascript:void(0);" style="font-size:12px;" class="trackfree_shipement_menu_item media-menu-item ' . ( $t === 1 ? 'active' : '' ) . '" id="shipment-item-link_' . (int) $t . '">Shipememt ' . (int) $t . '</a>';
        }
        echo '</div>';
        echo '<div style="clear: both;"></div>';

        $i = 1;
        foreach ( $shipment_details as $idx => $shipment_values ) {
            $render_shipment( $i, $idx, $shipment_values );
            $i++;
        }
    } else {
        $render_shipment( 1, 0, $shipment_details[0] );
    }

    // Persist status updates, but keep the full shipment list (do not drop empty shipments).
    update_post_meta( $order_id, '_trackfree_shipment_details', wc_clean( array_values( $update_shipment_details ) ) );
    if ( get_option( 'trackfree_auto_order_status_update' ) == 1 ) {
        trackfree_update_order_status( array_values( $update_shipment_details ), $order_id );
    }

    wp_die();
}

function shipment_preview_template( $track_data ) {
    ?>
    <div class="trackfree-shipment-preview">
        <img src="<?php echo esc_url( $track_data['courierLogo'] ); ?>" alt="<?php echo esc_attr( $track_data['courierName'] ); ?>" width="36" style="opacity: 0.4;"/>
        <br/>
        <?php echo esc_html( $track_data['trackingNum'] ); ?>
    </div>
    <div class="trackfree-shipment-preview-link">
        <a class="trackfree-view-tracking-link" href="<?php echo esc_url( trackfree_track_page_url( $track_data['trackingNum'] ) ); ?>" target="_blank" rel="noopener noreferrer">
            <?php _e( 'View tracking', 'trackfree-woocommerce-tracking' ); ?>
        </a>
    </div>
    <?php
}
