/*
 Theme Name:   Woodmart Child
 Description:  Woodmart Child Theme
 Author:       XTemos
 Author URI:   http://xtemos.com
 Template:     woodmart
 Version:      1.0.0
 Text Domain:  woodmart
*/
/**
 * 下载外部图片并返回 attachment ID
 */
function woodmart_import_download_image($url){
    if(empty($url)) return false;

    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $tmp = download_url($url);

    if(is_wp_error($tmp)) return false;

    $file = [
        'name'     => basename($url),
        'tmp_name' => $tmp,
    ];

    $id = media_handle_sideload($file, 0);

    if(is_wp_error($id)){
        @unlink($tmp);
        return false;
    }

    return $id;
}

/**
 * WP All Import 钩子：写入 WoodMart 变体图库
 */
add_action('pmxi_saved_post', function($post_id){
    global $wpdb;

    error_log("pmxi_saved_post Hook Run: Post ID = $post_id");

    // 只处理变体
    if(get_post_type($post_id) !== 'product_variation'){
        return;
    }

    // 获取 CSV 中的 gallery 字段
    $urls = get_post_meta($post_id, 'variation_gallery', true);
    error_log("csv里面的变体图片 $post_id: $urls");

    if(empty($urls)){
        error_log("No gallery URLs found for $post_id");
        return;
    }

    // 拆分图片链接
    $urls = preg_split('/[;,|\s]+/', $urls);
    $ids  = [];

    foreach($urls as $url){

        $url = trim($url);
        if(!$url) continue;

        // 提取文件名（用作 LIKE 查询）
        $file_name = basename($url);

        // 查询是否已存在附件（通过 _wp_attached_file）
        $existing_id = $wpdb->get_var($wpdb->prepare(
            "SELECT p.ID 
             FROM {$wpdb->posts} p
             JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID
             WHERE p.post_type = 'attachment'
             AND pm.meta_key = '_wp_attached_file'
             AND pm.meta_value LIKE %s
             LIMIT 1",
             '%' . $wpdb->esc_like($file_name) . '%'
        ));

        if($existing_id){
            $id = intval($existing_id);
            error_log("图片已存在，复用ID: $id | 变体ID: $post_id");
        } else {
            // 下载新图片
            $id = woodmart_import_download_image($url);
            if($id){
                error_log("下载成功: 图片ID $id | 变体ID: $post_id");
            } else {
                error_log("下载失败 URL: $url");
                continue;
            }
        }

        $ids[] = $id;
    }

    if(!empty($ids)){
        // 设置主图 
        update_post_meta($post_id, '_thumbnail_id', $ids[0]); 
        error_log("主图已设置: {$ids[0]} for $post_id");
        
        // 写入 rtwpvg_images
        update_post_meta($post_id, 'rtwpvg_images', $ids);
        error_log("已写入 rtwpvg_images ($post_id): " . serialize($ids));
    }
});


