/*
 Theme Name: Storefront Child
 Template: storefront
*/
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'show_second_gallery_image_as_main', 10, 2 );

function show_second_gallery_image_as_main( $html, $attachment_id ) {
    global $product;

    // Hent galleribilleder
    $gallery_ids = $product->get_gallery_image_ids();

    // Hvis der er mindst 1 galleri-billede
    if( ! empty( $gallery_ids ) ) {
        // Tag første galleri-billede
        $first_gallery_image_id = $gallery_ids[0];
        $image_url = wp_get_attachment_image_url( $first_gallery_image_id, 'full' );

        // Erstat HTML med galleri-billedet
        $html = '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( get_post_meta($first_gallery_image_id, '_wp_attachment_image_alt', true) ) . '" />';
    }

    return $html;
}

add_filter( 'woocommerce_single_product_image_html', 'custom_single_product_image', 10, 2 );

function custom_single_product_image( $html, $post_id ) {
    // Hent billed-id fra custom felt (fx 'single_product_image')
    $custom_image_id = get_post_meta( $post_id, 'single_product_image', true );

    if ( $custom_image_id ) {
        $image_url = wp_get_attachment_image_url( $custom_image_id, 'full' );
        $html = '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( get_post_meta($custom_image_id, '_wp_attachment_image_alt', true) ) . '" />';
    }

    return $html;
}
