<?php

defined('ABSPATH') or die('No script kiddies please!!');

if ($this->ajax_nonce_verify()) {
    /**
     * Triggers just before processing the subscription form
     *
     * @since 1.0.0
     */
    do_action('std_before_form_process');
    $form_data = $_POST['form_data'];
    parse_str($form_data, $form_data);
    $form_data = $this->sanitize_array($form_data);
    $form_alias = sanitize_text_field($_POST['form_alias']);
    $form_row = $this->get_form_row_by_alias($form_alias);
    $form_details = maybe_unserialize($form_row->form_details);
    $subscriber_name = (!empty($form_data['std_name'])) ? $form_data['std_name'] : '';
    $subscriber_name_array = (!empty($subscriber_name)) ? explode(' ', $subscriber_name) : array('', '');
    $first_name = $subscriber_name_array[0];
    $last_name = end($subscriber_name_array);
    $required_field_flag = 0;
    $error_keys = [];

    /**
     * Name field required check
     */
    if (!empty($form_details['form']['name']['show']) && !empty($form_details['form']['name']['required']) && empty($form_data['std_name'])) {
        $required_field_flag = 1;
        $error_keys[] = 'std-name';
    }
    /**
     * Email field required check
     */
    if (empty($form_data['std_email'])) {
        $required_field_flag = 1;
        $error_keys[] = 'std-email';
    }
    /**
     * Custom Fields required check
     */
    if (!empty($form_details['form']['custom_fields'])) {
        foreach ($form_details['form']['custom_fields'] as $custom_field_key => $custom_field_details) {
            if (!empty($custom_field_details['show']) && !empty($custom_field_details['required'])) {
                if (empty($form_data['std_custom_fields'][$custom_field_key])) {
                    $required_field_flag = 1;
                    $error_keys[] = $custom_field_key;
                }
            }
        }
    }
    /**
     * Terms and agreement required check
     */
    if (!empty($form_details['form']['terms_agreement']['show']) && !empty($form_details['form']['terms_agreement']['agreement_text']) && empty($form_data['std_terms_agreement'])) {
        $required_field_flag = 1;
        $error_keys[] = 'std-terms-agreement';
    }
    if (!empty($form_details['form']['gdpr_agreement']['show']) && !empty($form_details['form']['gdpr_agreement']['required']) && !empty($form_details['form']['gdpr_agreement']['agreement_text']) && empty($form_data['std_gdpr_agreement'])) {
        $required_field_flag = 1;
        $error_keys[] = 'std-gdpr-agreement';
    }
    if (!empty($form_details['captcha']['enable'])) {
        $captcha = sanitize_text_field($form_data['g-recaptcha-response']); // get the captchaResponse parameter sent from our ajax
        if (empty($captcha)) {
            $error_keys[] = 'captcha';
            $required_field_flag = 1;
        } else {
            $secret_key = (!empty($form_details['captcha']['secret_key'])) ? esc_attr($form_details['captcha']['secret_key']) : '';
            $captcha_response = $this->validate_recaptcha_v3($captcha, $secret_key);

            if (!$captcha_response) {
                $error_keys[] = 'captcha';
                $required_field_flag = 1;
            }
        }
    }

    if ($required_field_flag) {
        $response['status'] = 403;
        $response['message'] = esc_attr($form_details['general']['required_error_message']);
        $response['data']['error_keys'] = $error_keys;
    } else {
        //It is okay to process the form now
        $subscriber_email = sanitize_email($form_data['std_email']);
        if (!empty($form_details['general']['unallowed_email_domains'])) {

            $subscriber_email_array = explode('@', $subscriber_email);
            $email_domain = end($subscriber_email_array);
            if (in_array($email_domain, $form_details['general']['unallowed_email_domains'])) {
                $response['status'] = 403;
                $response['message'] = (!empty($form_details['general']['unallowed_email_error_message'])) ? esc_html($form_details['general']['unallowed_email_error_message']) : esc_html__('Invalid email domain', 'subscribe-to-download');
                die(json_encode($response));
            }
        }
        if (empty($form_details['general']['instant_download'])) {
            if (!empty($form_details['general']['double_optin'])) {
                setcookie("std_name", $subscriber_name, time() + 24 * 365, '/');
                setcookie("std_email", $subscriber_email, time() + 24 * 365, '/');
                setcookie("std_alias", $form_alias, time() + 24 * 365, '/');

                if (!empty($form_data['std_custom_fields'])) {
                    setcookie("std_custom_fields", maybe_serialize($form_data['std_custom_fields']), time() + 24 * 365, '/');
                }
                if (!empty($form_details['form']['gdpr_agreement']['show'])) {
                    if (!empty($form_data['std_gdpr_agreement'])) {
                        setcookie("std_gdpr_agreement", 1, time() + 24 * 365, '/');
                    }
                } else {
                    setcookie("std_gdpr_agreement", 2, time() + 24 * 365, '/');
                }


                $from_email = (!empty($form_details['email']['from_email'])) ? $form_details['email']['from_email'] : $this->get_default_from_email();
                $from_name = (!empty($form_details['email']['from_name'])) ? $form_details['email']['from_name'] : esc_html__('No Reply', 'subscribe-to-download');
                $confirmation_subject = (!empty($form_details['email']['confirmation_subject'])) ? $form_details['email']['confirmation_subject'] : esc_html__('Subscription Confirmation', 'subscribe-to-download');
                $confirmation_email_message = (!empty($form_details['email']['confirmation_email_message'])) ? $form_details['email']['confirmation_email_message'] : $this->get_default_confirmation_email_message();
                $confirmation_verification_key = md5($subscriber_email);
                $confirmation_verification_link = home_url() . '/?std_subscription_confirmation=true&confirmation_verification_key=' . $confirmation_verification_key;
                $confirmation_email_message = str_replace('#confirmation_link', '<a href="' . $confirmation_verification_link . '">' . $confirmation_verification_link . '</a>', $confirmation_email_message);
                $confirmation_email_message = str_replace('#first_name', $first_name, $confirmation_email_message);
                $confirmation_email_message = str_replace('#last_name', $last_name, $confirmation_email_message);
                $charset = get_option('blog_charset');
                $headers[] = 'Content-Type: text/html; charset=' . $charset;
                $headers[] = "From: $from_name <$from_email>";
                $email_check = wp_mail($subscriber_email, $confirmation_subject, $confirmation_email_message, $headers);
                if ($email_check) {
                    $response['status'] = 200;
                    $response['type'] = esc_html__('Subscription Confirmation', 'subscribe-to-download');
                    $response['confirmation_verification_link'] = $confirmation_verification_link;
                    $response['message'] = esc_html($form_details['general']['success_message']);
                } else {
                    $response['status'] = 403;
                    $response['message'] = esc_html($form_details['general']['error_message']);
                }
            } else {
                include(STD_PATH . 'inc/cores/download-email.php');
            }
        } else {
            include(STD_PATH . 'inc/cores/download-email.php');
        }
    }
    if ($response['status'] == 200) {
        if (!empty($form_details['general']['redirection']) && !empty($form_details['general']['redirection_url'])) {
            $response['redirection_url'] = esc_url($form_details['general']['redirection_url']);
        }
    }

    die(json_encode($response));
} else {
    $this->permission_denied();
}
