<?php

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

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

        wp_reset_postdata();
        $develuxsct_query = new \WP_Query($develuxsct_args);

        if (!empty($develuxsct_query->post)) {
            return $develuxsct_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);
    }

}