<?php
/**
 * CreateCouponAction — applies one shared WooCommerce coupon code to every customer.
 *
 * Free tier uses a single reusable code (shareable). Pro offers unique single-use codes.
 *
 * @package CartCue\Actions
 */

namespace CartCue\Actions;

use CartCue\Context;

defined( 'ABSPATH' ) || exit;

class CreateCouponAction extends AbstractAction {

	public function get_slug(): string {
		return 'create_coupon';
	}

	public function get_label(): string {
		return __( 'Apply a shared coupon code', 'cartcue-sales-automation' );
	}

	/**
	 * Pro-only coupon options (shown as locked upsell on free).
	 *
	 * @return string[]
	 */
	public function get_pro_feature_labels(): array {
		return [
			__( 'Unique single-use code per customer', 'cartcue-sales-automation' ),
		];
	}

	public function get_settings_fields(): array {
		return [
			[
				'key'         => 'coupon_code',
				'label'       => __( 'Shared coupon code', 'cartcue-sales-automation' ),
				'type'        => 'text',
				'default'     => 'WELCOME10',
				'placeholder' => __( 'e.g. WELCOME10', 'cartcue-sales-automation' ),
				'description' => __( 'The same code is sent to every customer — it can be shared or reused. For one-time codes, upgrade to Pro.', 'cartcue-sales-automation' ),
			],
			[
				'key'     => 'discount_type',
				'label'   => __( 'Discount type', 'cartcue-sales-automation' ),
				'type'    => 'select',
				'default' => 'percent',
				'options' => [
					'percent'    => __( 'Percentage', 'cartcue-sales-automation' ),
					'fixed_cart' => __( 'Fixed cart discount', 'cartcue-sales-automation' ),
				],
			],
			[
				'key'     => 'amount',
				'label'   => __( 'Discount amount', 'cartcue-sales-automation' ),
				'type'    => 'number',
				'default' => 10,
			],
			[
				'key'     => 'expiry_days',
				'label'   => __( 'Expires after (days, 0 = never)', 'cartcue-sales-automation' ),
				'type'    => 'number',
				'default' => 7,
			],
		];
	}

	public function run( array $settings, Context $context ): void {
		$code = strtoupper( preg_replace( '/[^A-Z0-9\-]/i', '', (string) ( $settings['coupon_code'] ?? '' ) ) );
		if ( '' === $code ) {
			throw new \RuntimeException( 'Create Coupon: shared coupon code is required.' );
		}

		$type   = sanitize_key( $settings['discount_type'] ?? 'percent' );
		$amount = max( 0, (float) ( $settings['amount'] ?? 10 ) );
		if ( ! in_array( $type, [ 'percent', 'fixed_cart' ], true ) ) {
			$type = 'percent';
		}

		if ( $this->is_test( $context ) ) {
			$context->set( 'coupon_code', $code );
			$context->set( 'coupon_amount', (string) $amount );
			$context->set( 'coupon_type', $type );
			$context->set( 'coupon_expiry', '' );
			return;
		}

		$coupon_id = wc_get_coupon_id_by_code( $code );
		$expiry_str = '';

		if ( ! $coupon_id ) {
			$coupon = new \WC_Coupon();
			$coupon->set_code( $code );
			$coupon->set_discount_type( $type );
			$coupon->set_amount( $amount );
			$coupon->set_individual_use( false );
			$coupon->set_usage_limit( 0 );
			$coupon->set_usage_limit_per_user( 0 );

			$expiry_days = max( 0, (int) ( $settings['expiry_days'] ?? 7 ) );
			if ( $expiry_days > 0 ) {
				$expires = ( new \DateTimeImmutable( 'now', wp_timezone() ) )->modify( '+' . $expiry_days . ' days' );
				$coupon->set_date_expires( $expires );
				$expiry_str = $expires->format( get_option( 'date_format', 'Y-m-d' ) );
			}

			$workflow_id = (int) ( $context->data['workflow_id'] ?? 0 );
			if ( $workflow_id ) {
				$coupon->add_meta_data( '_cartcue_workflow_id', $workflow_id );
				$coupon->add_meta_data( '_cartcue_shared_coupon', 1 );
			}

			$coupon_id = $coupon->save();
			if ( ! $coupon_id ) {
				throw new \RuntimeException( 'Create Coupon: failed to save shared coupon.' );
			}
		} else {
			$coupon = new \WC_Coupon( $coupon_id );
			$expires = $coupon->get_date_expires();
			if ( $expires ) {
				$expiry_str = $expires->date( get_option( 'date_format', 'Y-m-d' ) );
			}
			$amount = (float) $coupon->get_amount();
			$type   = $coupon->get_discount_type();
		}

		$context->set( 'coupon_code', $code );
		$context->set( 'coupon_amount', (string) $amount );
		$context->set( 'coupon_type', $type );
		$context->set( 'coupon_expiry', $expiry_str );
	}
}
