<?php

namespace DEVELUXSCT\Options;
if (!defined('ABSPATH')) {
    exit;
}

class Default_Post_Query_Data
{
    /**
     * @throws \Exception
     */
    public static function get_default_single_product(): \WP_Post
    {
        $args = [
            'post_type' => 'product',
            'post_status' => 'publish',
            'posts_per_page' => 1,
        ];

        wp_reset_postdata();
        $query = new \WP_Query($args);

        if (!empty($query->post)) {
            return $query->post;
        }

        // No product found, create one programmatically
        $product_data = [
            'post_title' => 'Default Product',
            'post_content' => 'This is a default product created programmatically.',
            'post_status' => 'publish',
            'post_type' => 'product',
        ];

        $product_id = wp_insert_post($product_data);

        if (!$product_id || is_wp_error($product_id)) {
            throw new \RuntimeException('Failed to create a default product.');
        }

        // Optionally set default product metadata (e.g., price, stock status)
        update_post_meta($product_id, '_price', '0.00');
        update_post_meta($product_id, '_regular_price', '0.00');
        update_post_meta($product_id, '_stock_status', 'instock');
        update_post_meta($product_id, '_visibility', 'visible');

        // Return the newly created product
        return get_post($product_id);
    }

}