/*
 Theme Name: Astra Child Custom
 Template: astra
*/
// 底部加载弹窗JS
add_action('wp_footer', function(){
?>
<script>
jQuery(function($){
    $('a[href^="#product-modal"]').click(function(e){
        e.preventDefault();
        let href = $(this).attr('href');
        let pid = href.split('pid=')[1];
        let modalWrap = $('#product-modal');
        $.post(elementorFrontend.config.ajaxurl,{
            action:'load_modal_product',
            pid:pid
        },function(html){
            modalWrap.find('.modal-popup-shortcode-content').html(html);
            modalWrap.addClass('open');
            modalWrap.css('display','block');
        })
    });
    $(document).on('click','#product-modal .modal-popup-close, #product-modal .modal-popup-overlay',function(){
        $('#product-modal').removeClass('open').css('display','none');
    })
})
</script>
<?php
}, 99);

add_shortcode('popup_single_product', function($attr){
    $pid = $attr['id'];
    $product = wc_get_product($pid);
    if( !$product ) return '<p>产品不存在</p>';
    ob_start();
    ?>
    <div style="padding:20px;max-width:800px;margin:0 auto;">
        <div style="margin-bottom:16px;">
            <?php echo get_the_post_thumbnail($pid, 'large', ['style'=>'width:100%;height:auto;']); ?>
        </div>
        <h2 style="margin:0 0 10px;"><?php echo esc_html($product->get_name()); ?></h2>
        <div style="font-size:22px;color:#d82020;margin-bottom:12px;">
            <?php echo $product->get_price_html(); ?>
        </div>
        <div style="line-height:1.7;margin-bottom:20px;">
            <?php echo $product->get_short_description(); ?>
        </div>
        <a href="<?php echo esc_url($product->get_permalink()); ?>" style="display:inline-block;padding:10px 26px;background:#222;color:#fff;text-decoration:none;border-radius:4px;">查看完整产品</a>
    </div>
    <?php
    return ob_get_clean();
});

add_action('wp_ajax_load_modal_product', 'load_modal_product');
add_action('wp_ajax_nopriv_load_modal_product', 'load_modal_product');
function load_modal_product(){
    $pid = isset($_POST['pid']) ? intval($_POST['pid']) : 0;
    echo do_shortcode("[popup_single_product id='$pid']");
    wp_die();
}