/*
 Theme Name:   Woodmart Child
 Description:  Woodmart Child Theme
 Author:       XTemos
 Author URI:   http://xtemos.com
 Template:     woodmart
 Version:      1.0.0
 Text Domain:  woodmart
*/
add_action('init', 'batch_rename_product_images');

function batch_rename_product_images() {
    if (!is_admin() || !isset($_GET['batch_rename'])) return;

    $paged = isset($_GET['paged']) ? intval($_GET['paged']) : 1;
    $batch_size = 100; // Change if needed

    $args = array(
        'post_type' => 'product',
        'posts_per_page' => $batch_size,
        'paged' => $paged,
        'post_status' => 'publish',
    );

    $products = get_posts($args);

    if (empty($products)) {
        echo "✅ All done!";
        exit;
    }

    foreach ($products as $product) {
        $product_id = $product->ID;
        $title = sanitize_title($product->post_title);
        $thumbnail_id = get_post_thumbnail_id($product_id);

        if ($thumbnail_id) {
            $file_path = get_attached_file($thumbnail_id);
            $file_info = pathinfo($file_path);

            $new_file_name = $title . '.' . $file_info['extension'];
            $new_file_path = $file_info['dirname'] . '/' . $new_file_name;

            if (file_exists($file_path) && !file_exists($new_file_path)) {
                rename($file_path, $new_file_path);
                update_attached_file($thumbnail_id, $new_file_path);

                $upload_dir = wp_upload_dir();
                $new_url = str_replace($upload_dir['basedir'], $upload_dir['baseurl'], $new_file_path);
                wp_update_attachment_metadata($thumbnail_id, wp_generate_attachment_metadata($thumbnail_id, $new_file_path));
                wp_update_post([
                    'ID' => $thumbnail_id,
                    'guid' => $new_url,
                ]);
            }

            // ✅ Set Alt Text
            update_post_meta($thumbnail_id, '_wp_attachment_image_alt', $product->post_title);
        }
    }

    // Auto-run next batch
    $next_page = $paged + 1;
    $next_url = add_query_arg([
        'batch_rename' => '1',
        'paged' => $next_page,
    ], home_url());

    echo "✅ Batch $paged complete. <a href='$next_url'>Run next batch</a> or wait to auto-run...";
    echo "<script>setTimeout(function(){ window.location.href = '$next_url'; }, 2000);</script>";
    exit;
}
