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

    class STD_Admin extends STD_Library {

        function __construct() {
            add_action('admin_menu', array($this, 'add_std_menu'));
            /**
             * Subscribers export to csv
             */
            add_action('admin_post_std_export_csv', array($this, 'export_to_csv'));

            /**
             * Admin footer
             */
            add_action('admin_footer', array($this, 'add_extra_html'));

            /**
             * Constant contact authorize
             *
             * @return void
             */

            add_action('admin_post_constant_contact_authorize', array($this, 'authorize_constant_contact'));
        }

        function authorize_constant_contact() {
            if (!empty($_GET['authorize_nonce']) && wp_verify_nonce($_GET['authorize_nonce'], 'std_cc_nonce')) {
                
                include(STD_PATH . 'inc/cores/authorize-constant-contact.php');
            } else {
                $this->permission_denied();
            }
        }

        function add_std_menu() {
            add_menu_page(esc_html__('Subscribe to Download', 'subscribe-to-download'), esc_html__('Subscribe to Download', 'subscribe-to-download'), 'manage_options', 'subscribe-to-download', array($this, 'generate_main_page'), 'dashicons-download');
            add_submenu_page('subscribe-to-download', esc_html__('Subscription Forms', 'subscribe-to-download'), esc_html__('Subscription Forms', 'subscribe-to-download'), 'manage_options', 'subscribe-to-download', array($this, 'generate_main_page'));
            add_submenu_page('subscribe-to-download', esc_html__('Add Subscription Form', 'subscribe-to-download'), esc_html__('Add Subscription Form', 'subscribe-to-download'), 'manage_options', 'add-subscription-form', array($this, 'add_subscription_form'));
            add_submenu_page('subscribe-to-download', esc_html__('Subscribers', 'subscribe-to-download'), esc_html__('Subscribers', 'subscribe-to-download'), 'manage_options', 'std-subscribers', array($this, 'generate_subscribers_list'));
            add_submenu_page('subscribe-to-download', esc_html__('Settings', 'subscribe-to-download'), esc_html__('Settings', 'subscribe-to-download'), 'manage_options', 'std-settings', array($this, 'settings_page'));
            add_submenu_page('subscribe-to-download', esc_html__('Help', 'subscribe-to-download'), esc_html__('Help', 'subscribe-to-download'), 'manage_options', 'std-help', array($this, 'render_help_page'));
            add_submenu_page('subscribe-to-download', esc_html__('About', 'subscribe-to-download'), esc_html__('About', 'subscribe-to-download'), 'manage_options', 'std-about', array($this, 'render_about_page'));
        }

        function generate_main_page() {
            if (isset($_GET['action'], $_GET['form_id']) && $_GET['action'] == 'edit_form') {
                if (!empty($_GET['form_id'])) {
                    $form_id = intval($_GET['form_id']);
                    $form_row = $this->get_form_row_by_id($form_id);

                    if (empty($form_row)) {
                        echo sprintf(esc_html__("No form found with ID %d", 'subscribe-to-download'), $form_id);
                    } else {
                        $form_details = maybe_unserialize($form_row->form_details);
                    }
                }
                include(STD_PATH . 'inc/views/backend/forms/subscription-form-edit.php');
            } else {
                include(STD_PATH . 'inc/views/backend/forms/subscription-forms-list.php');
            }
        }

        function add_subscription_form() {
            include(STD_PATH . 'inc/views/backend/forms/subscription-form-add.php');
        }

        function generate_subscribers_list() {
            if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'view_subscriber' && !empty($_REQUEST['subscriber_id'])) {
                include(STD_PATH . 'inc/views/backend/subscribers/view-subscriber.php');
            } else {

                include(STD_PATH . 'inc/views/backend/subscribers/list-subscribers.php');
            }
        }

        function export_to_csv() {
            if (!empty($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'std_export_csv_nonce')) {
                $current_date_time = date('Y-m-d_H-i-s');
                $filename = sanitize_title("subscribers-list-$current_date_time") . '.csv';
                header('Content-type: application/csv');
                header('Content-Disposition: attachment; filename=' . $filename);
                $csv_rows = $this->get_subscriber_csv_rows();

                /**
                 * Filters csv rows
                 *
                 * @param array $csv_rows
                 *
                 * @since 1.0.0
                 */
                $csv_rows = apply_filters('std_csv_rows', $csv_rows);

                $csv_output = fopen('php://output', 'w');
                foreach ($csv_rows as $csv_row) {
                    fputcsv($csv_output, $csv_row);
                }
                exit;
            } else {
                $this->permission_denied();
            }
        }

        function get_subscriber_csv_rows() {
            global $wpdb;
            $subscriber_table = STD_SUBSCRIBERS_TABLE;
            $form_table = STD_FORM_TABLE;
            if (!empty($_GET['form_alias'])) {
                $form_alias = sanitize_text_field($_GET['form_alias']);
                $form_row = $wpdb->get_row($wpdb->prepare("select * from $form_table where form_alias = '%s'", $form_alias));
                $form_details = maybe_unserialize($form_row->form_details);
                if (!empty($_GET['keyword'])) {
                    $keyword = sanitize_text_field($_GET['keyword']);
                    $subscriber_query = $wpdb->prepare("select * from $subscriber_table inner join $form_table on $subscriber_table.subscriber_form_alias = $form_table.form_alias where subscriber_form_alias = %s and (subscriber_name like %s or subscriber_email like %s)", $form_alias, '%' . $keyword . '%', '%' . $keyword . '%');
                } else {
                    $subscriber_query = $wpdb->prepare("select * from $subscriber_table inner join $form_table on $subscriber_table.subscriber_form_alias = $form_table.form_alias where subscriber_form_alias = %s", $form_alias);
                }
            } else {
                if (!empty($_GET['keyword'])) {
                    $keyword = sanitize_text_field($_GET['keyword']);
                    $subscriber_query = $wpdb->prepare("select * from $subscriber_table inner join $form_table on $subscriber_table.subscriber_form_alias = $form_table.form_alias where (subscriber_name like %s or subscriber_email like %s)", '%' . $keyword . '%', '%' . $keyword . '%');
                } else {
                    $subscriber_query = "select * from $subscriber_table inner join $form_table on $subscriber_table.subscriber_form_alias = $form_table.form_alias";
                }
            }
            $subscriber_rows = $wpdb->get_results($subscriber_query);
            $csv_rows = array();
            $csv_rows_pre_fields = ['Subscriber Name', 'Subscriber Email'];
            $csv_rows_custom_fields = [];
            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'])) {

                        $csv_rows_custom_fields[] = $custom_field_details['label'];
                    }
                }
            }
            $csv_rows_post_fields = ['GDPR Agreement', 'Subscription Form', 'Download Status', 'User IP', 'Subscribed Date'];
            if (!empty($_GET['form_alias'])) {
                $csv_heading_rows = array_merge($csv_rows_pre_fields, $csv_rows_custom_fields, $csv_rows_post_fields);
                $csv_rows[] = $csv_heading_rows;
            } else {

                $csv_rows[] = array('Subscriber Name', 'Subscriber Email', 'GDPR Agreement', 'Subscription Form', 'Download Status', 'User IP', 'Subscribed Date');
            }
            if (!empty($subscriber_rows)) {
                foreach ($subscriber_rows as $subscriber_row) {
                    $subscriber_custom_fields = maybe_unserialize($subscriber_row->subscriber_custom_fields);
                    $download_status = (!empty($subscriber_row->subscriber_download_status)) ? esc_html__('Yes', 'subscribe-to-download') : esc_html__('No', 'subscribe-to-download');
                    switch ($subscriber_row->subscriber_gdpr_agreement) {
                        case 0:
                            $std_gdpr_agreement = __('No', 'subscribe-to-download');
                            break;
                        case 1:
                            $std_gdpr_agreement = __('Yes', 'subscribe-to-download');
                            break;
                        case 2:
                            $std_gdpr_agreement = __('Unavailable', 'subscribe-to-download');
                            break;
                        default:
                            $std_gdpr_agreement = __('Unavailable', 'subscribe-to-download');

                            break;
                    }
                    if (!empty($_GET['form_alias'])) {
                        $csv_rows_pre_fields = [
                            $subscriber_row->subscriber_name,
                            $subscriber_row->subscriber_email
                        ];
                        $csv_rows_custom_fields = [];
                        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'])) {
                                    if (!empty($subscriber_custom_fields[$custom_field_key])) {

                                        $custom_field_value = (is_array($subscriber_custom_fields[$custom_field_key])) ? implode(', ', $subscriber_custom_fields[$custom_field_key]) : $subscriber_custom_fields[$custom_field_key];
                                    } else {
                                        $custom_field_value = '';
                                    }
                                    $csv_rows_custom_fields[] = $custom_field_value;
                                }
                            }
                        }
                        $csv_rows_post_fields = [
                            $std_gdpr_agreement,
                            $subscriber_row->form_title,
                            $download_status,
                            $subscriber_row->subscribed_user_ip,
                            $subscriber_row->subscription_date
                        ];
                        $csv_row = array_merge($csv_rows_pre_fields, $csv_rows_custom_fields, $csv_rows_post_fields);
                    } else {
                        $csv_row = array(
                            $subscriber_row->subscriber_name,
                            $subscriber_row->subscriber_email,
                            $std_gdpr_agreement,
                            $subscriber_row->form_title,
                            $download_status,
                            $subscriber_row->subscribed_user_ip,
                            $subscriber_row->subscription_date
                        );
                    }


                    $csv_rows[] = $csv_row;
                }
            }
            return $csv_rows;
        }

        function settings_page() {
            include(STD_PATH . 'inc/views/backend/std-settings.php');
        }

        function render_help_page() {
            include(STD_PATH . 'inc/views/backend/std-help.php');
        }

        function render_about_page() {
            include(STD_PATH . 'inc/views/backend/std-about.php');
        }

        function add_extra_html() {
?>
            <script type="text/html" id="tmpl-mc-lists">
                <?php include(STD_PATH . 'inc/views/backend/js-templates/mailchimp-lists.php'); ?>
            </script>
            <script type="text/html" id="tmpl-ml-groups">
                <?php include(STD_PATH . 'inc/views/backend/js-templates/mailerlite-groups.php'); ?>
            </script>
            <script type="text/html" id="tmpl-ck-forms">
                <?php include(STD_PATH . 'inc/views/backend/js-templates/convertkit-forms.php'); ?>
            </script>
            <script type="text/html" id="tmpl-email-domain">
                <?php include(STD_PATH . 'inc/views/backend/js-templates/email-domain-template.php'); ?>
            </script>
<?php
        }
    }

    new STD_Admin();
}
