<?php
/**
 * LatePoint Update Coupon Action
 *
 * Handles updating existing 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.
}

/**
 * Update Coupon Action Class
 *
 * @since 1.13.0
 */
class Update_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 = 'update_coupon';

	/**
	 * Execute the update coupon action
	 *
	 * @param array $data Form submission data.
	 * @return array Action result.
	 * @throws \Exception If an error occurs during execution.
	 * @since 1.13.0
	 */
	protected function execute( $data ) {
		try {
			$coupon_id = isset( $data['coupon_id'] ) ? intval( $data['coupon_id'] ) : null;

			if ( ! $coupon_id ) {
				throw new \Exception( 'Coupon ID is required.' );
			}

			$coupon = new \OsCouponModel( $coupon_id );

			if ( ! isset( $coupon->id ) || ! $coupon->id ) {
				throw new \Exception( 'Coupon not found.' );
			}

			// Prepare updated rules, preserving existing values if not provided.
			$rules = [
				'limit_per_customer' => $data['limit_per_customer'] ?? $coupon->get_rule( 'limit_per_customer' ),
				'limit_total'        => $data['limit_total'] ?? $coupon->get_rule( 'limit_total' ),
				'orders_more'        => $data['orders_more'] ?? $coupon->get_rule( 'orders_more' ),
				'orders_less'        => $data['orders_less'] ?? $coupon->get_rule( 'orders_less' ),
				'agent_ids'          => $data['agent_ids'] ?? $coupon->get_rule( 'agent_ids' ),
				'customer_ids'       => $data['customer_ids'] ?? $coupon->get_rule( 'customer_ids' ),
				'service_ids'        => $data['service_ids'] ?? $coupon->get_rule( 'service_ids' ),
			];

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

			$coupon->set_data( $coupon_params );

			if ( $coupon->save() ) {
				return [
					'success' => true,
					'message' => __( 'Coupon updated 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 updated.';
				throw new \Exception( $error_msg );

		} catch ( \Exception $e ) {
			return [
				'success' => false,
				'message' => sprintf(
					// translators: %s: Error message.
					__( 'Failed to update 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.
Update_Coupon::get_instance();
