<?php

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



if (!class_exists('STD_Ajax_Admin')) {

    class STD_Ajax_Admin extends STD_Library {

        function __construct() {
            /**
             * Form save ajax
             */
            add_action('wp_ajax_std_form_save_action', array($this, 'form_settings_save_action'));
            add_action('wp_ajax_nopriv_std_form_save_action', array($this, 'permission_denied'));

            /**
             * Settings save ajax
             */
            add_action('wp_ajax_std_settings_save_action', array($this, 'settings_save_action'));
            add_action('wp_ajax_nopriv_std_settings_save_action', array($this, 'permission_denied'));

            /**
             * Form delete ajax
             *
             */
            add_action('wp_ajax_std_form_delete_action', array($this, 'form_delete_action'));
            add_action('wp_ajax_nopriv_std_form_delete_action', array($this, 'permission_denied'));

            /**
             * Form copy ajax
             *
             */
            add_action('wp_ajax_std_form_copy_action', array($this, 'form_copy_action'));
            add_action('wp_ajax_nopriv_std_form_copy_action', array($this, 'permission_denied'));

            /**
             * Mailchimp connect ajax
             *
             */
            add_action('wp_ajax_std_mailchimp_connect_action', array($this, 'mailchimp_connect_action'));
            add_action('wp_ajax_nopriv_std_mailchimp_connect_action', array($this, 'permission_denied'));
            /**
             * Constant Contact connect ajax
             *
             */
            add_action('wp_ajax_std_constant_contact_connect_action', array($this, 'constant_contact_connect_action'));
            add_action('wp_ajax_nopriv_std_constant_contact_connect_action', array($this, 'permission_denied'));
            /**
             * Mailerlite  connect ajax
             *
             */
            add_action('wp_ajax_std_mailerlite_connect_action', array($this, 'mailerlite_connect_action'));
            add_action('wp_ajax_nopriv_std_mailerlite_connect_action', array($this, 'permission_denied'));
            /**
             * Sendinblue  connect ajax
             *
             */
            add_action('wp_ajax_std_sendinblue_connect_action', array($this, 'sendinblue_connect_action'));
            add_action('wp_ajax_nopriv_std_sendinblue_connect_action', array($this, 'permission_denied'));

            /**
             * Convertkit  connect ajax
             *
             */
            add_action('wp_ajax_std_convertkit_connect_action', array($this, 'convertkit_connect_action'));
            add_action('wp_ajax_nopriv_std_convertkit_connect_action', array($this, 'permission_denied'));

            /**
             * Subscriber delete ajax
             *
             */
            add_action('wp_ajax_std_subscriber_delete_action', array($this, 'subscriber_delete_action'));
            add_action('wp_ajax_nopriv_std_subscriber_delete_action', array($this, 'permission_denied'));
        }

        function form_settings_save_action() {
            do_action('std_before_form_add_ajax');
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $form_data = $_POST['form_data'];

                $form_data = stripslashes_deep($form_data);
                parse_str($form_data, $form_data);
                $sanitize_rule = array(
                    'agreement_text' => 'html',
                    'gdpr_agreement' => 'html',
                    'text' => 'html',
                    'email_message' => 'to_br',
                    'link_expire_message' => 'to_br',
                    'optin_confirmation_message' => 'html',
                    'confirmation_email_message' => 'to_br',
                    'download_notification_email_message' => 'to_br',
                    'admin_notification_email_message' => 'to_br',
                    'custom_css' => 'to_br',
                    'footer_text' => 'html',
                );
                $form_data = $this->sanitize_array($form_data, $sanitize_rule);
                if (empty($form_data['form_details']['general']['download_file'])) {
                    $form_data['form_details']['general']['download_file_id'] = '';
                }

                $form_alias = $form_data['form_alias'];
                $form_title = $form_data['form_title'];
                $form_status = (!empty($form_data['form_status'])) ? 1 : 0;
                if (empty($form_title) || empty($form_alias)) {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('Form title or Alias cannot be empty.', 'subscribe-to-download');
                } else {
                    $form_id = (!empty($form_data['form_id'])) ? intval($form_data['form_id']) : 0;
                    if ($this->is_alias_available($form_alias, $form_id)) {
                        global $wpdb;
                        if (!empty($form_id)) {
                            //update if form id is available in the form
                            $update_check = $wpdb->update(
                                STD_FORM_TABLE,
                                array(
                                    'form_title' => $form_title,
                                    'form_alias' => $form_alias,
                                    'form_details' => maybe_serialize($form_data['form_details']),
                                    'form_status' => $form_status,
                                ),
                                array('form_id' => $form_id),
                                array('%s', '%s', '%s', '%s'),
                                array('%d')
                            );

                            $response['status'] = 200;
                            $response['message'] = esc_html__('Form updated successfully.', 'subsribe-to-download');
                        } else {
                            $insert_check = $wpdb->insert(
                                STD_FORM_TABLE,
                                array(
                                    'form_title' => $form_title,
                                    'form_alias' => $form_alias,
                                    'form_details' => maybe_serialize($form_data['form_details']),
                                    'form_status' => $form_status,
                                ),
                                array('%s', '%s', '%s', '%s')
                            );
                            if ($insert_check) {
                                $form_id = $wpdb->insert_id;
                                $response['status'] = 200;
                                $response['message'] = esc_html__('Form added successfully. Redirecting...', 'subsribe-to-download');
                                $response['redirect_url'] = admin_url('admin.php?page=subscribe-to-download&action=edit_form&form_id=' . $form_id);
                            } else {
                                $response['status'] = 403;
                                $response['message'] = esc_html__('Something went wrong. Please try again later.', 'subsribe-to-download');
                            }
                        }
                    } else {
                        $response['status'] = 403;
                        $response['message'] = esc_html__('Form alias already used. Please use some other alias.', 'subscribe-to-download');
                    }
                }
                die(json_encode($response));
            } else {
                $this->permission_denied();
            }
        }

        function form_delete_action() {
            do_action('std_before_form_delete_ajax');
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $form_id = intval($_POST['form_id']);
                global $wpdb;
                $delete_check = $wpdb->delete(STD_FORM_TABLE, array('form_id' => $form_id), array('%d'));
                if ($delete_check) {
                    $response['status'] = 200;
                    $response['message'] = esc_html__('Form deleted successfully', 'subscribe-to-download');
                } else {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('There occurred some error. Please try again later.', 'subscribe-to-download');
                }
                echo json_encode($response);
                die();
            } else {
                $this->permission_denied();
            }
        }

        function form_copy_action() {
            do_action('std_before_form_copy_ajax');
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $form_id = intval($_POST['form_id']);
                global $wpdb;
                $copy_check = $this->copy_form($form_id);
                if ($copy_check) {
                    $response['status'] = 200;
                    $response['message'] = esc_html__('Form copied successfully.Redirecting..', 'subscribe-to-download');
                    $response['redirect_url'] = admin_url('admin.php?page=subscribe-to-download');
                } else {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('There occurred some error. Please try again later.', 'subscribe-to-download');
                }
                echo json_encode($response);
                die();
            } else {
                $this->permission_denied();
            }
        }

        function mailchimp_connect_action() {
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $api_key = sanitize_text_field($_POST['api_key']);
                if (empty($api_key)) {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('Missing API Key', 'subscribe-to-download');
                } else {
                    $api_url = STD_MC_API_URL;
                    $dash_position = strpos($api_key, '-');
                    if ($dash_position !== false) {
                        $api_url = str_replace('//api.', '//' . substr($api_key, $dash_position + 1) . ".api.", $api_url);
                        $api_url = $api_url . 'lists/?count=1000';
                        $method = 'GET';
                        $args = array(
                            'url' => $api_url,
                            'headers' => $this->get_mc_headers($api_key),
                            'timeout' => 10,
                            'sslverify' => true,
                        );
                        $mailchimp_connection = wp_remote_get($api_url, $args);
                        if (!is_wp_error($mailchimp_connection)) {
                            $response_body = json_decode(wp_remote_retrieve_body($mailchimp_connection));
                            $response_code = (!empty($mailchimp_connection['response']['code'])) ? $mailchimp_connection['response']['code'] : 403;
                            if ($response_code == 200) {
                                $lists = $response_body->lists;
                                $response['status'] = 200;
                                $response['message'] = esc_html__('Connection successful. Please check the fetched lists.', 'subscribe-to-download');
                                $response['api_response'] = $lists;
                                $response['api_raw_response'] = wp_remote_retrieve_body($mailchimp_connection);
                            } else {
                                $response['status'] = $mailchimp_connection['response']['code'];
                                $response['message'] = esc_html__('There occurred some error. Please check API response.', 'subscribe-to-download');
                                $response['api_response'] = $response_body;
                            }
                        } else {
                            $response['status'] = 403;
                            $response['message'] = esc_html__("The connection couldn't be made with Mailchimp API. Please check your api key.", 'subscribe-to-download');
                        }
                    } else {
                        $response['status'] = 403;
                        $response['message'] = esc_html__('Invalid API Key', 'subscribe-to-download');
                    }
                }

                echo json_encode($response);
                die();
            } else {
                $this->permission_denied();
            }
        }
        function mailerlite_connect_action() {
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $api_key = sanitize_text_field($_POST['api_key']);
                if (empty($api_key)) {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('Missing API Key', 'subscribe-to-download');
                } else {
                    $api_url = STD_ML_API_URL;



                    $api_url = $api_url . 'groups';
                    $method = 'GET';
                    $args = array(
                        'url' => $api_url,
                        'headers' => $this->get_ml_headers($api_key),
                        'timeout' => 10,
                        'sslverify' => true,
                    );
                    $mailerlite_connection = wp_remote_get($api_url, $args);
                    if (!is_wp_error($mailerlite_connection)) {
                        $response_body = json_decode(wp_remote_retrieve_body($mailerlite_connection));
                        $response_code = (!empty($mailerlite_connection['response']['code'])) ? $mailerlite_connection['response']['code'] : 403;
                        if ($response_code == 200) {
                            $lists = $response_body;
                            $response['status'] = 200;
                            $response['message'] = esc_html__('Connection successful. Please check the fetched lists.', 'subscribe-to-download');
                            $response['api_response'] = $lists;
                            $response['api_raw_response'] = wp_remote_retrieve_body($mailerlite_connection);
                        } else {
                            $response['status'] = $mailerlite_connection['response']['code'];
                            $response['message'] = esc_html__('There occurred some error. Please check API response.', 'subscribe-to-download');
                            $response['api_response'] = $response_body;
                        }
                    } else {
                        $response['status'] = 403;
                        $response['message'] = esc_html__("The connection couldn't be made with Mailerlite API. Please check your api key.", 'subscribe-to-download');
                    }
                }


                echo json_encode($response);
                die();
            } else {
                $this->permission_denied();
            }
        }
        function sendinblue_connect_action() {
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $api_key = sanitize_text_field($_POST['api_key']);
                if (empty($api_key)) {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('Missing API Key', 'subscribe-to-download');
                } else {
                    $api_url = STD_SIB_API_URL;
                    $api_url = $api_url . 'contacts/lists';
                    $method = 'GET';
                    $args = array(
                        'url' => $api_url,
                        'headers' => $this->get_sib_headers($api_key),
                        'timeout' => 10,
                        'sslverify' => true,
                    );
                    $sendinblue_connection = wp_remote_get($api_url, $args);
                    if (!is_wp_error($sendinblue_connection)) {
                        $response_body = json_decode(wp_remote_retrieve_body($sendinblue_connection));
                        $response_code = (!empty($sendinblue_connection['response']['code'])) ? $sendinblue_connection['response']['code'] : 403;
                        if ($response_code == 200) {
                            $lists = $response_body->lists;;
                            $response['status'] = 200;
                            $response['message'] = esc_html__('Connection successful. Please check the fetched lists.', 'subscribe-to-download');
                            $response['api_response'] = $lists;
                            $response['api_raw_response'] = wp_remote_retrieve_body($sendinblue_connection);
                        } else {
                            $response['status'] = $sendinblue_connection['response']['code'];
                            $response['message'] = esc_html__('There occurred some error. Please check API response.', 'subscribe-to-download');
                            $response['api_response'] = $response_body;
                        }
                    } else {
                        $response['status'] = 403;
                        $response['message'] = esc_html__("The connection couldn't be made with Sendinblue API. Please check your api key.", 'subscribe-to-download');
                    }
                }


                echo json_encode($response);
                die();
            } else {
                $this->permission_denied();
            }
        }
        function convertkit_connect_action() {
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $api_key = sanitize_text_field($_POST['api_key']);
                if (empty($api_key)) {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('Missing API Key', 'subscribe-to-download');
                } else {
                    $api_url = STD_CK_API_URL;
                    $api_url = $api_url . 'forms?api_key=' . $api_key;
                    $method = 'GET';
                    $args = array(
                        'url' => $api_url,
                        'headers' => $this->get_ck_headers(),
                        'timeout' => 10,
                        'sslverify' => true,
                    );
                    $convertkit_connection = wp_remote_get($api_url, $args);
                    if (!is_wp_error($convertkit_connection)) {
                        $response_body = json_decode(wp_remote_retrieve_body($convertkit_connection));
                        $response_code = (!empty($convertkit_connection['response']['code'])) ? $convertkit_connection['response']['code'] : 403;
                        if ($response_code == 200) {
                            $lists = $response_body->forms;;
                            $response['status'] = 200;
                            $response['message'] = esc_html__('Connection successful. Please check the fetched lists.', 'subscribe-to-download');
                            $response['api_response'] = $lists;
                            $response['api_raw_response'] = wp_remote_retrieve_body($convertkit_connection);
                        } else {
                            $response['status'] = $convertkit_connection['response']['code'];
                            $response['message'] = esc_html__('There occurred some error. Please check API response.', 'subscribe-to-download');
                            $response['api_response'] = $response_body;
                        }
                    } else {
                        $response['status'] = 403;
                        $response['message'] = esc_html__("The connection couldn't be made with Sendinblue API. Please check your api key.", 'subscribe-to-download');
                    }
                }


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

        function settings_save_action() {
            do_action('std_before_settings_save_ajax');
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $form_data = $_POST['form_data'];
                $form_data = stripslashes_deep($form_data);
                parse_str($form_data, $form_data);
                $sanitize_rule = array('mailchimp_lists' => 'html', 'unsubscribe_message' => 'to_br');
                $form_data = $this->sanitize_array($form_data, $sanitize_rule);

                $std_settings = $form_data['std_settings'];
                update_option('std_settings', $std_settings);
                $response['status'] = 200;
                $response['message'] = esc_html__('Settings saved successfully.', 'subscribe-to-download');
                echo json_encode($response);
                die();
            } else {
                $this->permission_denied();
            }
        }

        function constant_contact_connect_action() {
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $api_key = sanitize_text_field($_POST['api_key']);
                $access_token = sanitize_text_field($_POST['access_token']);
                if (empty($api_key) || empty($access_token)) {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('Missing API Key or Access Token', 'subscribe-to-download');
                } else {
                    $api_url = STD_CC_API_URL;
                    $lists_api_url = $api_url . 'lists/?api_key=' . $api_key;

                    $method = 'GET';
                    $args = array(
                        'url' => $api_url,
                        'headers' => $this->get_cc_headers($access_token),
                        'timeout' => 10,
                        'sslverify' => true,
                    );
                    $constant_contact_connection = wp_remote_get($lists_api_url, $args);
                    if (!is_wp_error($constant_contact_connection)) {
                        $response_body = json_decode(wp_remote_retrieve_body($constant_contact_connection));
                        $response_code = (!empty($constant_contact_connection['response']['code'])) ? $constant_contact_connection['response']['code'] : 403;
                        if ($response_code == 200) {
                            $response['status'] = 200;
                            $response['message'] = esc_html__('Connection successful. Please check the fetched lists.', 'subscribe-to-download');
                            $response['api_response'] = $response_body;
                            $response['api_raw_response'] = wp_remote_retrieve_body($constant_contact_connection);
                        } else {
                            $response['status'] = $constant_contact_connection['response']['code'];
                            $response['message'] = esc_html__('There occurred some error. Please check API response.', 'subscribe-to-download');
                            $response['api_response'] = $response_body;
                        }
                    } else {
                        $response['status'] = 403;
                        $response['message'] = esc_html__("The connection couldn't be made with Constant Contact API. Please check your api key and access token.", 'subscribe-to-download');
                    }
                }

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

        function subscriber_delete_action() {
            do_action('std_before_subscriber_delete_ajax');
            if ($this->admin_ajax_nonce_verify() && current_user_can('manage_options')) {
                $subscriber_id = intval($_POST['subscriber_id']);
                global $wpdb;
                $delete_check = $wpdb->delete(STD_SUBSCRIBERS_TABLE, array('subscriber_id' => $subscriber_id), array('%d'));
                if ($delete_check) {
                    $response['status'] = 200;
                    $response['message'] = esc_html__('Subscriber deleted successfully', 'subscribe-to-download');
                } else {
                    $response['status'] = 403;
                    $response['message'] = esc_html__('There occurred some error. Please try again later.', 'subscribe-to-download');
                }
                echo json_encode($response);
                die();
            } else {
                $this->permission_denied();
            }
        }
    }

    new STD_Ajax_Admin();
}
