<?php

$subscriber_row = $this->get_subscriber_row_by_email($form_data['std_email'], $form_alias);
$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');
$subject = (!empty($form_details['email']['subject'])) ? $form_details['email']['subject'] : esc_html__('Subscription Successful', 'subscribe-to-download');
$default_message = $this->get_default_email_message();
$email_message = (!empty($form_details['email']['email_message'])) ? $form_details['email']['email_message'] : $this->sanitize_escaping_linebreaks($default_message);
$charset = get_option('blog_charset');
$headers[] = 'Content-Type: text/html; charset=' . $charset;
$headers[] = "From: $from_name <$from_email>";
$form_template = $form_details['layout']['template'];
$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);

if (!empty($form_details['form']['gdpr_agreement']['show'])) {
    if (!empty($form_data['std_gdpr_agreement'])) {
        $std_gdpr_agreement = 1;
    } else {
        $std_gdpr_agreement = 0;
    }
} else {
    $std_gdpr_agreement = 2;
}

if (empty($subscriber_row)) {
    $user_ip = $this->get_user_IP();
    //if subscriber isn't already subscribed
    $encryption_key = $this->generate_encryption_key();
    if (!empty($form_details['general']['encrypt_link'])) {
        if (!empty($form_details['general']['link_expire']) && !empty($form_details['general']['link_expire_time'])) {

            $link_expire_time = intval($form_details['general']['link_expire_time']) * 60;
            $transient_name = 'std_' . $encryption_key;
            $transient_value = 1;
            set_transient($transient_name, $transient_value, $link_expire_time);
        }
        $download_url = home_url() . '?std_encryption_key=' . $encryption_key . '&form=' . $form_alias;
    } else {
        $download_url = esc_url($form_details['general']['download_file']);
    }
    if (!empty($download_url)) {
        $email_message = str_replace('#download_link', "<a href='$download_url'>$download_url</a>", $email_message);
        $email_message = str_replace('#first_name', $first_name, $email_message);
        $email_message = str_replace('#last_name', $last_name, $email_message);


        if (empty($form_details['general']['instant_download'])) {
            //     add_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
            $email_check = wp_mail($form_data['std_email'], $subject, $email_message, $headers);
            //   remove_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
        } else {
            // setting this true to insert into db without sending email when instant download is enabled
            $email_check = true;
        }
        if ($email_check) {
            setcookie("std_encryption_key", $encryption_key, time() + 3600 * 24 * 365, '/');

            global $wpdb;
            $wpdb->insert(
                STD_SUBSCRIBERS_TABLE,
                array(
                    'subscriber_name' => $subscriber_name,
                    'subscriber_email' => $form_data['std_email'],
                    'subscriber_custom_fields' => (!empty($form_data['std_custom_fields'])) ? maybe_serialize($form_data['std_custom_fields']) : '',
                    'subscriber_form_alias' => $form_alias,
                    'subscriber_encryption_key' => $encryption_key,
                    'subscribed_user_ip' => $user_ip,
                    'subscriber_gdpr_agreement' => $std_gdpr_agreement
                ),
                array(
                    '%s', // subscriber_name
                    '%s', // subscriber_email
                    '%s', // subscriber_custom_fields
                    '%s', // subscriber_form_alias
                    '%s', // subscriber_encryption_key
                    '%s', // subscriber_user_ip
                    '%d'  // subscriber_gdpr_agreement
                )
            );
            $response['status'] = 200;
            $response['message'] = esc_html($form_details['general']['success_message']);
            if (!empty($form_details['general']['instant_download'])) {
                $instant_download_button_label = (!empty($form_details['general']['instant_download_button_label'])) ? esc_html($form_details['general']['instant_download_button_label']) : esc_html__('Download', 'subscribe-to-download');
                $response['instant_download_button'] = "<a href='$download_url' target='_blank' class='std-instant-download-button-link'><button type='button'  class='std-instant-download-button std-form-submit'><i class='fas fa-download' aria-hidden='true'></i>$instant_download_button_label</button></a>";
            }
        } else {
            $response['status'] = 403;
            $response['message'] = esc_html($form_details['general']['error_message']);
        }
    } else {
        setcookie("std_encryption_key", $encryption_key, time() + 3600 * 24 * 365, '/');
        global $wpdb;
        $wpdb->insert(
            STD_SUBSCRIBERS_TABLE,
            array(
                'subscriber_name' => $subscriber_name,
                'subscriber_email' => $form_data['std_email'],
                'subscriber_custom_fields' => (!empty($form_data['std_custom_fields'])) ? maybe_serialize($form_data['std_custom_fields']) : '',
                'subscriber_form_alias' => $form_alias,
                'subscriber_encryption_key' => $encryption_key,
                'subscribed_user_ip' => $user_ip,
                'subscriber_gdpr_agreement' => $std_gdpr_agreement
            ),
            array(
                '%s', // subscriber_name
                '%s', // subscriber_email
                '%s', // subscriber_custom_fields
                '%s', // subscriber_form_alias
                '%s', // subscriber_encryption_key
                '%s', // subscriber_user_ip
                '%d'  // subscriber_gdpr_agreement
            )
        );
        $response['status'] = 200;
        $response['type'] = esc_html__('Default subscription', 'subscribe-to-download');
        $response['message'] = esc_html($form_details['general']['success_message']);
    }
} else {
    //if subscriber is already subscribed
    $encryption_key = $subscriber_row->subscriber_encryption_key;
    if (!empty($form_details['general']['encrypt_link'])) {
        if (!empty($form_details['general']['link_expire']) && !empty($form_details['general']['link_expire_time'])) {
            $link_expire_time = intval($form_details['general']['link_expire_time']) * 60;
            $transient_name = 'std_' . $encryption_key;
            $transient_value = 1;
            set_transient($transient_name, $transient_value, $link_expire_time);
        }
        $download_url = home_url() . '?std_encryption_key=' . $encryption_key . '&form=' . $form_alias;
    } else {
        $download_url = esc_url($form_details['general']['download_file']);
    }
    if (!empty($download_url)) {
        $email_message = str_replace('#download_link', '<a href="' . $download_url . '">' . $download_url . '</a>', $email_message);
        $email_message = str_replace('#first_name', $first_name, $email_message);
        $email_message = str_replace('#last_name', $last_name, $email_message);
        /**
         * Filters email message
         *
         * @param string $email_message
         * @param array $form_data
         *
         * @since 1.0.0
         */
        $email_message = apply_filters('std_email_message', $email_message, $form_data);
        if (empty($form_details['general']['instant_download'])) {
            add_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
            $email_check = wp_mail($form_data['std_email'], $subject, $email_message, $headers);
            remove_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
        } else {
            // setting this true to insert into db without sending email when instant download is enabled
            $email_check = true;
        }

        if ($email_check) {
            setcookie("std_encryption_key", $encryption_key, time() + 3600 * 24 * 365, '/');
            global $wpdb;
            $response['status'] = 200;
            $response['download_link'] = $download_url;
            $response['message'] = esc_html($form_details['general']['success_message']);
            if (!empty($form_details['general']['instant_download'])) {
                $instant_download_button_label = (!empty($form_details['general']['instant_download_button_label'])) ? esc_html($form_details['general']['instant_download_button_label']) : esc_html__('Download', 'subscribe-to-download');
                $response['instant_download_button'] = "<a href='$download_url' target='_blank' class='std-instant-download-button-link'><button type='button'  class='std-instant-download-button std-form-submit'><i class='fas fa-download' aria-hidden='true'></i>$instant_download_button_label</button></a>";
            }
        } else {
            $response['status'] = 403;
            $response['message'] = esc_html($form_details['general']['error_message']);
        }
    } else {
        $response['status'] = 200;
        $response['type'] = esc_html__('Default subscription', 'subscribe-to-download');
        $response['message'] = esc_html($form_details['general']['success_message']);
    }
}
/**
 * Triggers at the end of processing the subscription form successfully
 *
 * @param array $form_data
 *
 * @since 1.0.0
 */
do_action('std_end_form_process', $form_data, $form_details);
