<?php
/**
 * Geoport - Transport & Logistics WordPress Theme
 * WP Cargo Tracking Image Enhancement
 */

/*----------------------------------------------------------------------------*/
/* WP CARGO PRODUCT IMAGE IN TRACKING RESULTS
/*----------------------------------------------------------------------------*/

// 1. Add image upload field to shipments
add_action('admin_init', 'geoport_wpcargo_add_image_field');
function geoport_wpcargo_add_image_field() {
    add_meta_box(
        'wpcargo_product_image',
        'Product Image',
        'geoport_wpcargo_render_image_upload',
        'wpcargo_shipment',
        'normal',
        'high'
    );
}

function geoport_wpcargo_render_image_upload($post) {
    wp_nonce_field('geoport_wpcargo_save_image', 'geoport_wpcargo_image_nonce');
    $image_id = get_post_meta($post->ID, '_wpcargo_product_image', true);
    ?>
    <div>
        <input type="hidden" id="_wpcargo_product_image" name="_wpcargo_product_image" value="<?php echo esc_attr($image_id); ?>">
        <input type="button" id="upload_product_image" class="button" value="Upload Image">
        <div id="product_image_preview">
            <?php if ($image_id) : ?>
                <img src="<?php echo esc_url(wp_get_attachment_url($image_id)); ?>" style="max-width: 200px; margin-top: 10px;">
            <?php endif; ?>
        </div>
    </div>
    <script>
    jQuery(document).ready(function($) {
        $('#upload_product_image').click(function(e) {
            e.preventDefault();
            var frame = wp.media({
                title: 'Select Product Image',
                multiple: false
            }).on('select', function() {
                var attachment = frame.state().get('selection').first().toJSON();
                $('#_wpcargo_product_image').val(attachment.id);
                $('#product_image_preview').html('<img src="' + attachment.url + '" style="max-width: 200px; margin-top: 10px;">');
            }).open();
        });
    });
    </script>
    <?php
}

// 2. Save image data
add_action('save_post_wpcargo_shipment', 'geoport_wpcargo_save_image');
function geoport_wpcargo_save_image($post_id) {
    if (!isset($_POST['geoport_wpcargo_image_nonce']) || 
        !wp_verify_nonce($_POST['geoport_wpcargo_image_nonce'], 'geoport_wpcargo_save_image')) {
        return;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    if (isset($_POST['_wpcargo_product_image'])) {
        update_post_meta($post_id, '_wpcargo_product_image', sanitize_text_field($_POST['_wpcargo_product_image']));
    }
}
// 1. FORCE display specific image on tracking page
add_action('wpcargo_after_barcode', function($shipment_id) {
    echo '<div class="wpcargo-product-image" style="';
    echo 'margin:25px auto;padding:20px;background:#f9f9f9;';
    echo 'border-radius:8px;border:1px solid #ddd;text-align:center;';
    echo 'max-width:600px;">';
    echo '<h4 style="margin-top:0;">Product Image</h4>';
    echo '<img src="https://internationalpostalshipping.ltd/wp-content/uploads/2025/04/Annotation-2025-04-23-005857.jpg" ';
    echo 'style="max-width:100%;height:auto;display:block;margin:0 auto;">';
    echo '</div>';
});

// 2. Fallback JavaScript injection
add_action('wp_footer', function() {
    if(!is_wpcargo_tracking_page()) return;
    echo '<script>
    jQuery(document).ready(function($) {
        if($(".wpcargo-product-image").length === 0) {
            $(".wpcargo-barcode").after(\'<div class="wpcargo-product-image">\'+
                \'<h4>Product Image</h4>\'+
                \'<img src="https://internationalpostalshipping.ltd/wp-content/uploads/2025/04/Annotation-2025-04-23-005857.jpg" style="max-width:100%;margin:0 auto;display:block;">\'+
            \'</div>\');
        }
    });
    </script>';
});

// 3. Display on tracking page (with debug mode)
add_filter('wpcargo_track_details', 'geoport_wpcargo_show_tracking_image', 20, 1);
function geoport_wpcargo_show_tracking_image($shipment_id) {
    $image_id = get_post_meta($shipment_id, '_wpcargo_product_image', true);
    if (!$image_id) return '';
    
    // Debug mode (visible to admins only)
    if (current_user_can('manage_options')) {
        error_log("WP Cargo Tracking Debug - Shipment ID: {$shipment_id}, Image ID: {$image_id}");
    }
    
    // Get default tracking output
    ob_start();
    do_action('wpcargo_before_tracking_details', $shipment_id);
    wpcargo_template_tracking_details($shipment_id);
    do_action('wpcargo_after_tracking_details', $shipment_id);
    $tracking_output = ob_get_clean();
    
    // Prepare image HTML
    $image_html = '<div class="wpcargo-product-image" style="text-align:center; margin:30px auto; padding:20px; background:#f9f9f9; border-radius:5px; border:1px solid #eee;">';
    $image_html .= '<h4 style="margin-top:0;">Product Image</h4>';
    $image_html .= wp_get_attachment_image($image_id, 'medium', false, array(
        'style' => 'max-width:100%; height:auto; display:block; margin:0 auto; border:1px solid #ddd;'
    ));
    $image_html .= '</div>';
    
    return $image_html . $tracking_output;
}

// 4. Fallback JavaScript display (in case PHP fails)
add_action('wp_footer', function() {
    if (!is_wpcargo_tracking_page()) return;
    
    $tracking_num = $_GET['wpcargo_tracking'] ?? '';
    $shipment_id = wpcargo_get_shipment_id($tracking_num);
    $image_id = get_post_meta($shipment_id, '_wpcargo_product_image', true);
    
    if ($image_id) {
        echo '<script>
        jQuery(document).ready(function($) {
            if ($(".wpcargo-product-image").length === 0) {
                $(".wpcargo-barcode").after(\'<div class="wpcargo-product-image">\'+
                    \'<h4>Product Image</h4>\'+
                    \'<img src="'.wp_get_attachment_url($image_id).'" style="max-width:100%; margin:20px auto; display:block;">\'+
                \'</div>\');
            }
        });
        </script>';
    }
});