<?php

namespace ElementPack\Modules\CouponCode;

use ElementPack\Base\Element_Pack_Module_Base;

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

class Module extends Element_Pack_Module_Base {
    public function __construct() {
        parent::__construct();

        add_action('wp_ajax_element_pack_coupon_code', [$this, 'coupon_decryption']);
        add_action('wp_ajax_nopriv_element_pack_coupon_code', [$this, 'coupon_decryption']);
    }

    public function get_name() {
        return 'coupon-code';
    }

    public function get_widgets() {

        $widgets = ['Coupon_Code'];

        return $widgets;
    }

    public function coupon_decryption() {
        if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'element-pack-site' ) ) {
            wp_send_json_error( esc_html__( 'Security verification failed.', 'bdthemes-element-pack' ) );
        }

        $encryption = isset($_POST['coupon_code']) ? sanitize_text_field( wp_unslash( $_POST['coupon_code'] ) ) : '';
        $ciphering = "AES-128-CTR";
        $options   = 0;
        $decryption_iv = substr( wp_salt( 'nonce' ), 0, 16 );
        $decryption_key = wp_salt( 'auth' );

        $decryption = openssl_decrypt(
            $encryption,
            $ciphering,
            $decryption_key,
            $options,
            $decryption_iv
        );

        if ( $decryption === false ) {
            $decryption_iv_legacy = '1234567891011121';
            $decryption_key_legacy = "ElementPack";
            $decryption = openssl_decrypt(
                $encryption,
                $ciphering,
                $decryption_key_legacy,
                $options,
                $decryption_iv_legacy
            );
        }

        echo esc_html($decryption);

        wp_die();
    }
}
