<?php
/**
 * LatePoint Create Coupon Action
 *
 * Handles creating coupons in LatePoint through SureForms.
 *
 * @package SureForms
 * @since 1.13.0
 */

namespace SRFM_Pro\Inc\Pro\Native_Integrations\Integrations\LatePoint\Actions;

use SRFM_Pro\Inc\Pro\Native_Integrations\WordPress_Action;
use SRFM_Pro\Inc\Traits\Get_Instance;

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/**
 * Create Coupon Action Class
 *
 * @since 1.13.0
 */
class Create_Coupon extends WordPress_Action {
	use Get_Instance;

	/**
	 * Integration name
	 *
	 * @var string
	 * @since 1.13.0
	 */
	protected $integration = 'latepoint';

	/**
	 * Action name
	 *
	 * @var string
	 * @since 1.13.0
	 */
	protected $action = 'create_coupon';

	/**
	 * Execute the create coupon action
	 *
	 * @param array $data Form submission data.
	 * @return array Action result.
	 * @throws \Exception If coupon creation fails.
	 * @since 1.13.0
	 */
	protected function execute( $data ) {
		try {
			// Prepare coupon rules.
			$rules = [
				'limit_per_customer' => $data['limit_per_customer'] ?? '',
				'limit_total'        => $data['limit_total'] ?? '',
				'orders_more'        => $data['orders_more'] ?? '',
				'orders_less'        => $data['orders_less'] ?? '',
				'agent_ids'          => $data['agent_ids'] ?? '',
				'customer_ids'       => $data['customer_ids'] ?? '',
				'service_ids'        => $data['service_ids'] ?? '',
			];

			$coupon_params = [
				'code'           => $data['code'] ?? '',
				'name'           => $data['name'] ?? '',
				'discount_value' => $data['discount_value'] ?? '',
				'discount_type'  => $data['discount_type'] ?? 'fixed',
				'rules'          => wp_json_encode( $rules ),
				'status'         => $data['status'] ?? 'active',
			];

			$coupon = new \OsCouponModel();
			$coupon->set_data( $coupon_params );

			if ( $coupon->save() ) {
				return [
					'success' => true,
					'message' => __( 'Coupon created successfully.', 'sureforms-pro' ),
					'data'    => [
						'coupon_id' => $coupon->id,
						'code'      => $coupon->code,
						'name'      => $coupon->name,
						'status'    => $coupon->status,
					],
				];
			}
				$errors    = $coupon->get_error_messages();
				$error_msg = $errors[0] ?? 'Coupon could not be created.';
				throw new \Exception( $error_msg );

		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'Failed to create coupon: %s', 'sureforms-pro' ),
					$e->getMessage()
				),
			];
		}
	}

	/**
	 * Check if LatePoint plugin is active
	 *
	 * @return bool True if LatePoint is active, false otherwise.
	 * @since 1.13.0
	 */
	protected function is_plugin_active() {
		return class_exists( 'OsCouponModel' );
	}
}

// Initialize the class.
Create_Coupon::get_instance();
