<?php
defined('ABSPATH') or die('No script kiddies please!!');
if (!class_exists('STD_Hooks')) {

    class STD_Hooks extends STD_Library {

        function __construct() {
            add_action('template_redirect', array($this, 'form_preview'));
            add_action('template_redirect', array($this, 'verify_subscription_confirmation'));
            add_action('std_end_form_process', array($this, 'process_third_party_subscriptions'), 10, 2);
            add_action('wp_footer', array($this, 'add_popup_wrapper'));
            add_action('template_redirect', array($this, 'unsubscribe_action'));
            add_action('std_custom_fields', array($this, 'render_custom_field_html'), 10, 1);
            add_action('std_end_form_process', [$this, 'send_admin_notification_email'], 10, 2);

            add_action('template_redirect', [$this, 'authorize_constant_contact']);
        }

        function authorize_constant_contact() {
            if (isset($_GET['std_constant_contact_authorize'])) {
                include(STD_PATH . 'inc/cores/constant-contact-fetch-token.php');
                die();
            }
        }

        function form_preview() {
            if (isset($_GET['std_preview'], $_GET['_wpnonce']) && $_GET['std_preview'] && wp_verify_nonce($_GET['_wpnonce'], 'std_form_preview_nonce') && is_user_logged_in()) {
                wp_enqueue_style('std-preview', STD_URL . 'css/std-preview.css', array(), STD_VERSION);
                include(STD_PATH . 'inc/views/frontend/form-preview.php');
                die();
            }
        }

        function process_third_party_subscriptions($form_data, $form_details) {
            if (!empty($form_data['std_email'])) {
                if (!empty($form_data['std_name'])) {
                    $name_array = explode(' ', $form_data['std_name']);
                    $fname = $name_array[0];
                    $lname = (count($name_array) > 1) ? end($name_array) : '';
                } else {
                    $fname = '';
                    $lname = '';
                }
                $third_party_flag = true;
                if (!empty($form_details['form']['gdpr_agreement']['show'])) {
                    if (empty($form_data['std_gdpr_agreement'])) {
                        $third_party_flag = false;
                    }
                }
                if ($third_party_flag) {
                    $std_settings = get_option('std_settings');
                    include(STD_PATH . '/inc/cores/third-party-subscriptions/mailchimp-subscription.php');
                    include(STD_PATH . '/inc/cores/third-party-subscriptions/constant-contact-subscription.php');
                    include(STD_PATH . '/inc/cores/third-party-subscriptions/constant-contact-v3-subscription.php');
                    include(STD_PATH . '/inc/cores/third-party-subscriptions/mailerlite-subscription.php');
                    include(STD_PATH . '/inc/cores/third-party-subscriptions/sendinblue-subscription.php');
                    include(STD_PATH . '/inc/cores/third-party-subscriptions/convertkit-subscription.php');
                }
            }
        }

        function verify_subscription_confirmation() {
            if (isset($_GET['std_subscription_confirmation'], $_GET['confirmation_verification_key'])) {
                nocache_headers();
                $confirmation_verification_key = sanitize_text_field($_GET['confirmation_verification_key']);
                if (!empty($_COOKIE['std_email']) && !empty($_COOKIE['std_alias'])) {
                    $subscriber_email = sanitize_email($_COOKIE['std_email']);
                    $subscriber_name = (!empty($_COOKIE['std_name'])) ? sanitize_text_field($_COOKIE['std_name']) : '';
                    $std_gdpr_agreement = (!empty($_COOKIE['std_gdpr_agreement'])) ? sanitize_text_field($_COOKIE['std_gdpr_agreement']) : '';
                    if (hash_equals(md5($subscriber_email), $confirmation_verification_key)) {
                        $form_alias = sanitize_text_field($_COOKIE['std_alias']);
                        $form_row = $this->get_form_row_by_alias($form_alias);
                        $form_details = (is_serialized($form_row->form_details)) ? unserialize($form_row->form_details, ['allowed_classes' => false]) : [];
                        $form_data['std_email'] = $subscriber_email;
                        $form_data['std_name'] = $subscriber_name;
                        if (!empty($_COOKIE['std_custom_fields'])) {
                            $std_custom_field = is_serialized(stripslashes($_COOKIE['std_custom_fields'])) ? unserialize(stripslashes($_COOKIE['std_custom_fields']), ['allowed_classes' => false]) : '';
                            if (!empty($std_custom_field)) {
                                $form_data['std_custom_fields'] = $std_custom_field;
                            }
                        }

                        $form_data['std_gdpr_agreement'] = $std_gdpr_agreement;
                        include(STD_PATH . '/inc/cores/download-email.php');
                        include(STD_PATH . '/inc/views/frontend/confirmation-message-template.php');

                        die();
                    }
                }
            }
        }

        function add_popup_wrapper() {
?>
            <div class="std-temp-popup-wrapper"></div>
<?php
        }

        function unsubscribe_action() {
            if (!empty($_GET['std_action']) && $_GET['std_action'] == 'unsubscribe' && !empty($_GET['unsubscribe_key'])) {
                $unsubscribe_key = sanitize_text_field($_GET['unsubscribe_key']);

                if ($this->is_valid_encryption_key($unsubscribe_key)) {
                    global $wpdb;
                    $wpdb->delete(STD_SUBSCRIBERS_TABLE, array('subscriber_encryption_key' => $unsubscribe_key), array('%s'));
                    $std_settings = get_option('std_settings');
                    $unsubscribe_message = (!empty($std_settings['extra']['unsubscribe_message'])) ? $std_settings['extra']['unsubscribe_message'] : $this->default_unsubscribe_message();
                    echo $this->sanitize_html($unsubscribe_message);
                    die();
                }
            }
        }

        function render_custom_field_html($form_row) {
            include(STD_PATH . '/inc/views/frontend/custom-fields-html.php');
        }

        function send_admin_notification_email($form_data, $form_details) {
            if (!empty($form_details['email']['admin_notification'])) {
                $admin_notification_subject = $form_details['email']['admin_notification_subject'];

                $admin_notification_email_message = $form_details['email']['admin_notification_email_message'];

                $admin_notification_email_message = str_replace('#email', $form_data['std_email'], $admin_notification_email_message);
                $admin_notification_email_message = str_replace('#name', (!empty($form_data['std_name'])) ? $form_data['std_name'] : '', $admin_notification_email_message);
                $custom_fields_html = '';
                if (!empty($form_details['form']['custom_fields'])) {
                    $custom_field_html_array = [];
                    foreach ($form_details['form']['custom_fields'] as $custom_field_key => $custom_field_details) {
                        $field_type = $custom_field_details['field_type'];
                        if ($field_type == 'hidden') {
                            $custom_field_details['show'] = 1;
                        }
                        if (!empty($custom_field_details['show'])) {

                            $custom_field_label =  $custom_field_details['label'];

                            if (!empty($form_data['std_custom_fields'][$custom_field_key])) {

                                $custom_field_value = (is_array($form_data['std_custom_fields'][$custom_field_key])) ? implode(', ', $form_data['std_custom_fields'][$custom_field_key]) : $form_data['std_custom_fields'][$custom_field_key];
                            } else {
                                $custom_field_value = '';
                            }
                            $custom_field_html_array[] = $custom_field_label . ': ' . $custom_field_value;
                        }
                    }
                    $custom_field_html = implode('<br/>', $custom_field_html_array);
                }
                if (!empty($custom_field_html)) {
                    $admin_notification_email_message = str_replace('#custom_fields', $custom_field_html, $admin_notification_email_message);
                }
                $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');
                $charset = get_option('blog_charset');
                $headers[] = 'Content-Type: text/html; charset=' . $charset;
                $headers[] = "From: $from_name <$from_email>";
                $admin_email = get_option('admin_email');
                $notification_emails = (!empty($form_details['email']['admin_notification_emails'])) ? explode(',', $form_details['email']['admin_notification_emails']) : array($admin_email);
                add_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
                foreach ($notification_emails as $notification_email) {

                    wp_mail($notification_email, $admin_notification_subject, $admin_notification_email_message, $headers);
                }
                remove_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
            }
        }
    }

    new STD_Hooks();
}
