<?php
defined('ABSPATH') or die("you do not have acces to this page!");

if (!class_exists("cmplz_dataleak")) {
    class cmplz_dataleak extends cmplz_document
    {
        private static $_this;
        public $position;
        public $cookies = array();
        public $known_wizard_keys;
        public $total_steps;
        public $total_sections;
        public $page_url;

        function __construct()
        {
            if (isset(self::$_this))
	            wp_die(sprintf('%s is a singleton class and you cannot create a second instance.', get_class($this)));

            self::$_this = $this;

            //callback from settings
            add_action('cmplz_dataleak_last_step', array($this, 'wizard_last_step_callback'), 10, 1);

            //link action to custom hook
            foreach (cmplz_get_regions() as $region => $label){
	            add_action("cmplz_wizard_dataleak-$region", array($this, 'dataleak_after_last_step'), 10, 1);
            }

            //dataleaks:
            add_action('cmplz_dataleak_conclusion', array($this, 'dataleak_conclusion'));

            add_action('admin_enqueue_scripts', array($this, 'enqueue_assets_dataleaks'));

            add_action('wp_ajax_get_email_batch_progress', array($this, 'ajax_get_email_batch_progress'));


        }

        static function this()
        {
            return self::$_this;
        }



        public function enqueue_assets_dataleaks($hook)
        {
            global $post;

            if ((!$post || get_post_type($post) !== 'cmplz-dataleak') && (!isset($_GET['post_type']) || $_GET['post_type'] !== 'cmplz-dataleak')) return;

            wp_register_style('cmplz-fontawesome', cmplz_url . 'assets/fontawesome/fontawesome-all.css', "", cmplz_version);
            wp_enqueue_style('cmplz-fontawesome');

            if ($post) {

                $min = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? '' : '.min';
                $load_css = cmplz_get_value('use_document_css');
                if ($load_css) {
                    wp_register_style('cmplz-document', cmplz_url . "assets/css/document$min.css", false, cmplz_version);
                    wp_enqueue_style('cmplz-document');
                }

                wp_register_style('cmplz-wizard', cmplz_url . 'assets/css/wizard.css', false, cmplz_version);
                wp_enqueue_style('cmplz-wizard');

                wp_enqueue_script('cmplz_dataleak', cmplz_url . "pro/assets/js/dataleak.js", array('jquery'), cmplz_version, true);

                wp_localize_script(
                    'cmplz_dataleak',
                    'cmplz_dataleak',
                    array(
                        'admin_url' => admin_url('admin-ajax.php'),
                        'progress' => $this->get_email_batch_progress($post->ID),
                        'post_id' => $post->ID,
                        'complete_string' => __('Email sending complete', 'complianz-gdpr'),
                    )
                );
            }
        }

        public function get_email_batch_progress($post_id)
        {

            $args = array(
                'fields' => array('ID', 'user_email'),
            );
            $total_users = get_users($args);
            $total_count = count($total_users);

            //for each user, get email
            $args = array(
                'meta_query' => array(
                    array(
                        'key' => '_cmplz_dataleak_report_sent',
                        'value' => $post_id,
                        'compare' => '==',
                    )
                ),
                'fields' => array('ID', 'user_email'),
            );
            $sent_users = get_users($args);
            $sent_count = count($sent_users);
            if ($sent_count >= $total_count) return 100;

            return ($sent_count / $total_count) * 100;
        }

        public function send_email_batch($post_id)
        {

            if (!current_user_can('manage_options')) return;

            //for each user, get email
            $args = array(
                'meta_query' => array(
                    'relation' => 'OR',
                    array(
                        'key' => '_cmplz_dataleak_report_sent',
                        'value' => $post_id,
                        'compare' => '!=',
                    ),
                    array(
                        'key' => '_cmplz_dataleak_report_sent',
                        'compare' => 'NOT EXISTS',
                    )
                ),
                'number' => 10,
                'fields' => array('ID', 'user_email'),
            );
            $users = get_users($args);

            foreach ($users as $user) {
                update_user_meta($user->ID, '_cmplz_dataleak_report_sent', $post_id);
                $this->send_mail($user->user_email, $post_id);
            }

        }





        public function send_mail($to, $post_id)
        {
            if (!is_email($to)) return;

            $headers = array();
            $subject = get_post_meta($post_id, 'cmplz_subject', true);
            $sender = get_post_meta($post_id, 'cmplz_sender', true);
            if (empty($sender)) $sender = get_bloginfo('name');
            if (empty($subject)) $subject = __('Notification of dataleak', 'complianz-gdpr');

            $message = COMPLIANZ::$document->get_document_html(COMPLIANZ::$wizard->get_type($post_id), $this->get_region($post_id), $post_id);

            add_filter('wp_mail_content_type', function ($content_type) {
                return 'text/html';
            });

            //$attachments = array(WP_CONTENT_DIR . '/uploads/file_to_attach.zip');
            $success = wp_mail($to, $subject, $message, $headers);

            // Reset content-type to avoid conflicts -- http://core.trac.wordpress.org/ticket/23578
            remove_filter('wp_mail_content_type', 'set_html_content_type');
            return $success;
        }


        public function ajax_get_email_batch_progress()
        {
            if (!isset($_GET['post_id'])) return 0;
            $subject = (isset($_GET['subject'])) ? sanitize_text_field($_GET['subject']) : '';
            $sender = (isset($_GET['sender'])) ? sanitize_text_field($_GET['sender']) : '';


            $post_id = intval($_GET['post_id']);
            update_post_meta($post_id, 'cmplz_subject', $subject);
            update_post_meta($post_id, 'cmplz_sender', $sender);
            $this->send_email_batch($post_id);
            $output = array(
                "progress" => $this->get_email_batch_progress($post_id),
            );

            $obj = new stdClass();
            $obj = $output;
            echo json_encode($obj);
            wp_die();
        }




        public function dataleak_conclusion($post_id=false)
        {
            //if the function is called from a hook, the post_id is not a post_id, but a field
	        $region = $this->get_region($post_id);
	        //if (!is_numeric($post_id)) $post_id = false;
            $html = "";

            if ($region==='eu') {
                if (!$this->security_incident_has_occurred($post_id)) {
                    $html .= $this->wrap_line(__("No security incident has occurred.", 'complianz-gdpr') );
                } else {
                    if ($this->dataleak_has_to_be_reported($post_id)) {
                        $html .= $this->wrap_line(__("Please report this incident to the data protection authority.", 'complianz-gdpr') );

                        if ($this->dataleak_has_to_be_reported_to_involved($post_id)) {
                            $html .= $this->wrap_line(__("Because breached data presents a high risk to involved persons, you should also report this incident to those involved.", 'complianz-gdpr') );
                            $html .= $this->wrap_line(__("You can use the generated report to inform those involved.", 'complianz-gdpr') );
                            if (!$post_id) $html .= $this->wrap_line(__("Click view document to save and view this report.", 'complianz-gdpr') );
                        } else {
                            $html .= $this->wrap_line(__("It is not necessary to inform those involved.", 'complianz-gdpr') );
                        }

                    } else {
                        $html .= $this->wrap_line(__("The security incident does not have to be reported", 'complianz-gdpr') );
                    }
                }
            }


            if ($region==='uk') {
                if (!$this->security_incident_has_occurred($post_id)) {
                    $html .= $this->wrap_line(__("No security incident has occurred.", 'complianz-gdpr') );
                } else {
                    if ($this->dataleak_has_to_be_reported($post_id)) {
                        $html .= $this->wrap_line(sprintf(__("Please report this incident to the %sInformation Commissioner's Office%s.", 'complianz-gdpr'),'<a target="_blank" href="https://ico.org.uk/for-organisations/report-a-breach/">',"</a>" ));

                        if ($this->dataleak_has_to_be_reported_to_involved($post_id)) {
                            $html .= $this->wrap_line(__("Because breached data presents a high risk to involved persons, you should also report this incident to those involved.", 'complianz-gdpr') );
                            $html .= $this->wrap_line(__("You can use the generated report to inform those involved.", 'complianz-gdpr') );
                            if (!$post_id) $html .= $this->wrap_line(__("Click view document to save and view this report.", 'complianz-gdpr') );
                        } else {
                            $html .= $this->wrap_line(__("It is not necessary to inform those involved.", 'complianz-gdpr') );
                        }

                    } else {
                        $html .= $this->wrap_line(__("The security incident does not have to be reported", 'complianz-gdpr') );
                    }
                }
            }

            if ($region==='us') {
                $information_was_leaked = cmplz_get_value('what-information-was-involved-us')!=='none';
                $reach_large = cmplz_get_value('reach-of-dataloss-large-us', $post_id) == 'yes';
                if (!$this->security_incident_has_occurred($post_id)) {
                    $html .= $this->wrap_line(__("No security incident has occurred.", 'complianz-gdpr') );
                } else {
                    if ($information_was_leaked){
                        $html .= $this->wrap_line(__("You should report this incident to those involved.", 'complianz-gdpr') );
                        $html .= $this->wrap_line(__("You can use the generated report to inform those involved.", 'complianz-gdpr') );
                    }

                    if ($information_was_leaked && $reach_large) {
                        if (cmplz_get_value('california-visitors', $post_id) == 'yes') {
                            $html .= $this->wrap_line(__("The databreach concerns California residents, which means the databreach has to be reported to the Attorney General.", 'complianz-gdpr') );
                        }
                        $html .= $this->wrap_line(__("Considering the scale of the databreach, it is recommended to get legal counsel regarding this databreach.", 'complianz-gdpr') );

                    } else {
                        $html .= $this->wrap_line(__("The security incident does not have to be reported", 'complianz-gdpr') );
                    }
                }
            }

	        if ($region==='ca') {
		        $riskofabuse = cmplz_get_value('risk-of-data-loss-ca')==='1';
		        $sensitive = cmplz_get_value('risk-of-data-loss-ca')==='2';
		        $can_reduce_risk = cmplz_get_value('can-reduce-risk')==='yes';
		        if (!$this->security_incident_has_occurred($post_id)) {
			        $html .= $this->wrap_line(__("No security incident has occurred.", 'complianz-gdpr') );
		        } else {
			        if ($riskofabuse || $sensitive){
				        $html .= $this->wrap_line(__("Please report this incident to the data protection authority.", 'complianz-gdpr')." ".sprintf(__("%sReport link%s", "complianz-gdpr"),'<a href="https://www.priv.gc.ca/en/report-a-concern/report-a-privacy-breach-at-your-organization/report-a-privacy-breach-at-your-business/" target="_blank">', '</a>' ));

				        $html .= $this->wrap_line(__("You should report this incident to those involved.", 'complianz-gdpr') );
				        $html .= $this->wrap_line(__("You can use the generated report to inform those involved.", 'complianz-gdpr') );
			        } else {
				        $html .= $this->wrap_line(__("The security incident does not have to be reported", 'complianz-gdpr') );
			        }

			        if ($can_reduce_risk){
				        $html .= $this->wrap_line(__("You should make a notice to the organizations that may be able to reduce the risk of harm from the breach or to mitigate that harm.", 'complianz-gdpr') );

			        }
		        }
	        }

            cmplz_notice("<ul>$html</ul>");

        }

        public function wrap_line($msg){
            return '<li>'.$msg.'</li>';
        }


        public function dataleak_has_to_be_reported_to_involved($post_id = false)
        {
            $region = $this->get_region($post_id);
            if ($region=='eu') {
                return (cmplz_get_value('risk-of-data-loss', $post_id) == '3');
            }

            if ($region=='uk') {
                return (cmplz_get_value('risk-of-data-loss-uk', $post_id) == '3');
            }

	        if ($region=='ca') {
	             return (cmplz_get_value('risk-of-data-loss-ca', $post_id) == '3' || cmplz_get_value('risk-of-data-loss-ca', $post_id) == '4');
	        }

            return true;
        }

        public function dataleak_has_to_be_reported($post_id=false)
        {
            $region = $this->get_region($post_id);
            if ($region=='eu') {
                $has_security_incident_occurred = cmplz_get_value('security-incident-occurred', $post_id) === 'yes' ? true : false;
                $type_of_dataloss_not_serious = cmplz_get_value('type-of-dataloss', $post_id) == '3' ? true : false;
                $reach_of_dataloss_minor = cmplz_get_value('reach-of-dataloss', $post_id) == '3' ? true : false;

                if ($type_of_dataloss_not_serious || !$has_security_incident_occurred) return false;

                if ($reach_of_dataloss_minor) return false;
            }

            if ($region=='uk') {
                $has_security_incident_occurred = cmplz_get_value('security-incident-occurred-uk', $post_id) === 'yes' ? true : false;
                $type_of_dataloss_not_serious = cmplz_get_value('type-of-dataloss-uk', $post_id) == '3' ? true : false;
                $reach_of_dataloss_minor = cmplz_get_value('reach-of-dataloss-uk', $post_id) == '3' ? true : false;

                if ($type_of_dataloss_not_serious || !$has_security_incident_occurred) return false;

                if ($reach_of_dataloss_minor) return false;
            }

            if ($region =='us'){
                $information_was_leaked = cmplz_get_value('what-information-was-involved-us', $post_id)!=='none';
                $reach_large = cmplz_get_value('reach-of-dataloss-large-us', $post_id) == 'yes';
                return $information_was_leaked && $reach_large;
            }

	        if ($region=='ca') {
		        $has_security_incident_occurred = cmplz_get_value('security-incident-occurred-ca', $post_id) === 'yes' ? true : false;
		        $type_of_dataloss_not_serious = cmplz_get_value('type-of-dataloss-ca', $post_id) == '3' ? true : false;
		        $reach_of_dataloss_minor = (cmplz_get_value('reach-of-dataloss-ca', $post_id) == '3' || cmplz_get_value('reach-of-dataloss-ca', $post_id) == '4') ? true : false;

		        if ($type_of_dataloss_not_serious || !$has_security_incident_occurred) return false;

		        if ($reach_of_dataloss_minor) return false;
	        }

            return true;
        }

        public function dataleak_page($region)
        {
            $label = COMPLIANZ::$config->regions[$region]['label'];
            ?>
            <div class="wrap">
                <div class="cmplz-wizard-title"><h1><?php printf(__("Dataleak (%s)", 'complianz-gdpr'),$label) ?></h1></div>
                <?php if (COMPLIANZ::$license->license_is_valid()) { ?>
                    <?php
                    COMPLIANZ::$wizard->wizard("dataleak-".$region); ?>
                <?php } else {
                    cmplz_notice(__('Your license needs to be activated to unlock the wizard', 'complianz-gdpr'), 'warning');
                } ?>
            </div>
            <?php
        }


        public function security_incident_has_occurred($post_id=false, $region=false)
        {
            $security_incident_has_occurred = false;

            if (!$region) $region = $this->get_region($post_id);
            if ($region == 'eu') {
                $security_incident_has_occurred = cmplz_get_value('security-incident-occurred', $post_id) === 'yes' ? true : false;
            }

            if ($region == 'uk') {
                $security_incident_has_occurred = cmplz_get_value('security-incident-occurred-uk', $post_id) === 'yes' ? true : false;
            }

            if ($region == 'us') {
                $security_incident_has_occurred = cmplz_get_value('security-incident-occurred-us', $post_id) === 'yes' ? true : false;
            }

            if ($region == 'ca') {
                $security_incident_has_occurred = cmplz_get_value('security-incident-occurred-ca', $post_id) === 'yes' ? true : false;
            }

            return $security_incident_has_occurred;
        }


        public function dataleak_after_last_step()
        {
            if (!cmplz_user_can_manage()) return;

            //check if this is an already existing post
            $post_id = COMPLIANZ::$wizard->post_id();
            $region=false;

            if (!$post_id && isset($_GET['page'])){
                $region = substr($_GET['page'], -2);
            }

            //only start saving after second step
            $page = COMPLIANZ::$wizard->get_type($post_id);

            if (COMPLIANZ::$wizard->step($page) <= 2) {
                return;
            }

            //do not save as doc when no incident has occurred.
            if (!$this->security_incident_has_occurred($post_id, $region)) return;

            if (!$this->dataleak_has_to_be_reported(false)) return;

            if (isset($_POST['cmplz-finish']) || isset($_POST['cmplz-previous']) || isset($_POST['cmplz-save']) || isset($_POST['cmplz-next'])) {
                $date = cmplz_localize_date(date(get_option('date_format'), time()));

                $status = isset($_POST['cmplz-finish']) ? 'publish' : 'draft';
                $args = array(
                    'post_status' => $status,
                    'post_title' => sprintf(__("Dataleak %s", 'complianz-gdpr'), $date),
                    'post_type' => 'cmplz-dataleak',
                );
                //create new post type, and add all wizard data as meta fields.
                if (!$post_id) {
                    //create new post type processing, and add all wizard data as meta fields.
                    $post_id = wp_insert_post($args);
                    $_POST['post_id'] = $post_id;
                } else {
                    $args['ID'] = $post_id;
                    wp_update_post($args);
                }

                $this->set_region($post_id);

                //get all fields for this page
                $fields = COMPLIANZ::$config->fields($page);
                foreach ($fields as $fieldname => $field) {
                    update_post_meta($post_id, $fieldname, cmplz_get_value($fieldname));
                }

                //redirect to posts overview
                if ($status == 'publish') {
                    wp_redirect(admin_url("post.php?post=$post_id&action=edit"));
                    delete_option('complianz_options_dataleak');
                    exit();
                }

            }


        }


        public function send_mail_button()
        {
            add_thickbox();
            global $post;
            $complete = $this->get_email_batch_progress($post->ID) >= 100 ? true : false;
            ?>

            <input class="button thickbox" title="" type="button"
                <?php echo $complete ? 'disabled' : ''; ?>
                   alt="#TB_inline?height=400&width=800&inlineId=cmplz_email_users"
                   value="<?php _e('Email your users', 'complianz-gdpr') ?>"/>

            <div id="cmplz_email_users" style="display: none;">
                <h1><?php _e("Inform your users about a dataleak", 'complianz-gdpr') ?></h1>
                <p><?php _e('You can send the notification of a datateak to your website users.','complianz-gdpr')?></p>
                <div id="cmplz-send-data">
                    <p>
                        <label><?php _e('Sender name', 'complianz-gdpr') ?></label><br>
                        <input id="cmplz_sender" type="text" placeholder="<?php _e('Sender name', 'complianz-gdpr') ?>"
                               value="<?php echo get_bloginfo('name') ?>">
                    </p>
                    <p>
                        <label><?php _e('Email subject', 'complianz-gdpr') ?></label><br>
                        <input id="cmplz_subject" type="text" placeholder="<?php _e('Email subject', 'complianz-gdpr') ?>"
                               value="<?php _e('Notification of dataleak', 'complianz-gdpr'); ?>"></p>
                </div>
                <div id="cmplz-scan-progress">
                    <div class="cmplz-progress-bar"></div>
                </div>

                <button class="button" id="cmplz-start-mail">
                    <?php _e("Start sending", 'complianz-gdpr') ?>
                </button>

                <button class="button"  id="cmplz_close_tb_window"><?php _e("Pause sending", 'complianz-gdpr') ?></button>

            </div>

            <p>
                <?php if ($complete) _e('You already have sent this notification to your users.', 'complianz-gdpr') ?>
            </p>

            <?php

        }


    }
} //class closure
