<?php
/**
 * WooCommerce sample products for onboarding.
 *
 * @package EasySite_Pro
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Create demo products if none exist.
 *
 * @return int Number created.
 */
function easysite_create_sample_products() {
	if ( ! easysite_wc_active() || ! function_exists( 'wc_get_products' ) ) {
		return 0;
	}

	$onboarding = get_option( 'easysite_onboarding', array() );
	if ( ! empty( $onboarding['create_sample_products'] ) ) {
		update_option( 'woocommerce_currency', 'GBP' );
		update_option( 'woocommerce_currency_pos', 'left' );
	}

	$existing = wc_get_products( array( 'limit' => 1, 'status' => 'publish' ) );
	if ( ! empty( $existing ) ) {
		return 0;
	}

	$samples = array(
		array(
			'name'        => __( 'Starter Kit', 'easysite-pro' ),
			'price'       => '25.00',
			'description' => __( 'Everything you need to get started. Quality materials and fast delivery.', 'easysite-pro' ),
			'featured'    => true,
		),
		array(
			'name'        => __( 'Premium Bundle', 'easysite-pro' ),
			'price'       => '49.00',
			'description' => __( 'Our most popular package with extra value and priority support.', 'easysite-pro' ),
			'featured'    => true,
		),
		array(
			'name'        => __( 'Deluxe Edition', 'easysite-pro' ),
			'price'       => '79.00',
			'description' => __( 'The complete experience with all accessories included.', 'easysite-pro' ),
			'featured'    => false,
		),
	);

	$created = 0;
	foreach ( $samples as $sample ) {
		if ( ! class_exists( 'WC_Product_Simple' ) ) {
			return $created;
		}
		$product = new WC_Product_Simple();
		$product->set_name( $sample['name'] );
		$product->set_regular_price( $sample['price'] );
		$product->set_description( $sample['description'] );
		$product->set_short_description( $sample['description'] );
		$product->set_status( 'publish' );
		$product->set_catalog_visibility( 'visible' );
		$product->set_featured( ! empty( $sample['featured'] ) );
		$product->save();
		$created++;
	}

	return $created;
}

/**
 * Hook sample products after starter import when opted in.
 *
 * @param string $starter_key Starter key.
 */
function easysite_maybe_create_shop_samples( $starter_key ) {
	$options = get_option( 'easysite_onboarding', array() );
	if ( empty( $options['create_sample_products'] ) ) {
		return;
	}
	easysite_create_sample_products();
}
add_action( 'easysite_starter_imported', 'easysite_maybe_create_shop_samples' );
add_action( 'easysite_onboarding_complete', 'easysite_maybe_create_shop_samples_on_finish', 10, 0 );

/**
 * Create samples on setup complete if shop starter or checkbox set.
 */
function easysite_maybe_create_shop_samples_on_finish() {
	$options = get_option( 'easysite_onboarding', array() );
	if ( empty( $options['create_sample_products'] ) ) {
		return;
	}
	easysite_create_sample_products();
}
