<?php

/*
  MailBeez Automatic Trigger Email Campaigns
  http://www.mailbeez.com

  Copyright (c) 2010 - 2012 MailBeez

  Released under the GNU General Public License
 */

///////////////////////////////////////////////////////////////////////////////
///																			 //
///                 MailBeez Core file - do not edit                         //
///                                                                          //
///////////////////////////////////////////////////////////////////////////////

require_once(MH_DIR_CONFIG . 'config_customer_insight/classes/viewbeez.php');


class view_gdpr extends viewbeez
{

    private $modules;

// class constructor
    function __construct()
    {
        parent::__construct();

        $this->code = 'view_gdpr';
        $this->module = 'view_gdpr';
        $this->version = '1.0';
        $this->title = mh_lng('MAILBEEZ_VIEW_GDPR_TITLE');
        $this->description = mh_lng('MAILBEEZ_VIEW_GDPR_DESCRIPTION');

//        $this->sort_order = 1000;
        $this->enabled = mh_cfg('MAILBEEZ_CONFIG_GDPR_EXPORT_STATUS') == 'True';
        $this->set_template();
        $this->has_dashboard_view = false;

        //$this->hidden = !$this->enabled;

        $this->viewpage = mh_get('view_page', 'aggregated');


        $this->icon = 'UI_203.png';
        $this->exclude_params = array('app_action');

        if (isset($this->customer)) {
//            $this->sort_order = 0;
        }
        $this->sort_order = 1.1;
        $this->is_prospect_enabled = true;
    }

    function get_view_content($template)
    {
        $smarty = $this->init_view_content($template);
        if (mh_get('app_action') == 'gdpr_export') {
            $this->gdpr_export();
        } else {
            $active_modules = $this->_load_all_modules();
            $modules = array();
            foreach ($active_modules as $module) {
                $modules[$module] = array(
                    'title' => $GLOBALS[$module]->title,
                    'description' => $GLOBALS[$module]->description,
                );
            }

            $smarty->assign('modules', $modules);
        }

        return $this->parse_view_content($smarty, $template);
    }


    function _load_all_modules()
    {
        if ($this->modules) {
            return $this->modules;
        }

        $directories = $this->_get_module_directory_array();
        $active_modules = array();
        foreach ($directories as $dir) {
            $start_time = microtime(true);
            $active_modules = $this->_load_module($dir, $active_modules);
            $end_time = microtime(true);
            mh_log("_load_modules $dir load time: %s", $end_time - $start_time);
        }

        $sort_order = array();
        foreach ($active_modules as $key => $row) {
            $sort_order[$key] = $row['sort_order'];
        }
        array_multisort($sort_order, SORT_ASC, $active_modules);
        $active_modules = array_column($active_modules, 'module');
        $this->modules = $active_modules;
        return $active_modules;
    }

    function _load_module($directory, $active_modules)
    {
        $path = MH_DIR_FS_CATALOG . $directory;
        $modules = mh_read_module_directory($path);

        foreach ($modules as $m_file) {

            $class = substr($m_file, 0, strrpos($m_file, '.'));

            if (isset($GLOBALS[$class]) && is_object($GLOBALS[$class])) {
                continue;
            }

            // include class
            if (file_exists($path . $m_file) && !class_exists($class)) {
                include_once($path . $m_file);
                mh_load_modules_language_files($path, $class, MH_FILE_EXTENSION);
            }
            if (class_exists($class)) {
                if (!isset($GLOBALS[$class]) || !is_object($GLOBALS[$class])) {
                    mh_log("creating object: %s", $class);
                    $GLOBALS[$class] = new $class; // new object

                    if (mh_cfg('MAILBEEZ_CONFIG_GDPR_EXPORT_INCLUDE_STORE_DATA') == 'False') {
                        if ($GLOBALS[$class]->storedata) {
                            unset($GLOBALS[$class]);
                            continue;
                        }
                    }

                    if (!$GLOBALS[$class]->enabled) {
                        unset($GLOBALS[$class]);
                        continue;
                    }
                    if (($this->customer->is_prospect && !$GLOBALS[$class]->prospect_enabled) || (!$this->customer->is_prospect && !$GLOBALS[$class]->customer_enabled)) {

                        unset($GLOBALS[$class]);
                        continue;
                    }
                    $active_modules[] = array('module' => $class, 'sort_order' => $GLOBALS[$class]->sort_order);
                }
            }
        }
        return $active_modules;
    }


    function _get_module_directory_array()
    {
        $gdpr_module_directory_array = glob(MH_DIR_FS_CATALOG . MH_ROOT_PATH . '*/*/gdprbeez', GLOB_ONLYDIR);
        $push_to_end_dir = '';

        if (is_array($gdpr_module_directory_array) && sizeof($gdpr_module_directory_array) > 0) {

            foreach ($gdpr_module_directory_array as $idx => $gdpr_module_directory) {

                $gdpr_module_directory_array[$idx] .= '/';
                $gdpr_module_directory_array[$idx] = str_replace(MH_DIR_FS_CATALOG, '', $gdpr_module_directory_array[$idx]);
//                if (stristr($gdpr_module_directory_array[$idx], 'configbeez/config_customer_insight')) {
//                    $push_to_end_dir = $gdpr_module_directory_array[$idx];
//                    unset($gdpr_module_directory_array[$idx]);
//                }
            }
        }

//        $gdpr_module_directory_array[] = $push_to_end_dir;
        return $gdpr_module_directory_array;
    }

    private function _output($data)
    {
        $csv = fopen("php://output", 'w') or die("Can't open php://output");
        header("Content-Type:text/csv");
        header("Content-Disposition:attachment; filename=gdpr_" . $this->customer->id . ".csv");
        foreach ($data as $section => $section_data_array) {

            fputcsv($csv, array('DATA SECTION', strtoupper($section)), ';');
            foreach ($section_data_array as $section_data) {
                foreach ($section_data as $key => $value) {
                    fputcsv($csv, array(($key), $value), ';');
                }
            }

            fputcsv($csv, array('', ''), ';');
        }


        fclose($csv) or die("Can't close php://output");
    }


    function gdpr_export()
    {
        // perform export

        $active_modules = $this->_load_all_modules();

        $data = array();
        foreach ($active_modules as $module) {
            $GLOBALS[$module]->setContactId($this->customer->id);
            $data[$GLOBALS[$module]->getCode()] = $GLOBALS[$module]->getData();
        }


        $this->_output($data);
        exit();


        if ($this->is_prospect) {


        } else {


            if (mh_cfg('MAILBEEZ_CONFIG_GDPR_EXPORT_INCLUDE_STORE_DATA') == 'True') {

                // TABLE_CUSTOMERS
                // TABLE_ADDRESS_BOOK
                // TABLE_COUNTRIES
                // TABLE_REVIEWS
                // TABLE_REVIEWS_DESCRIPTION
                // TABLE_ORDERS
                // TABLE_ORDERS_PRODUCTS
                // TABLE_ORDERS_TOTAL
                // TABLE_ORDERS_STATUS_HISTORY

            }

            // MailBeez Core
            // MAILBEEZ_TRACKING
            // MAILBEEZ_TRACKING_CLICKS
            // MAILBEEZ_TRACKING_ORDERS
            // MAILBEEZ_BLOCK
            // MAILBEEZ_BOUNCES
            // MAILBEEZ_OPENS_LOG
            //


            // MailBeez Pro
            // MAILBEEZ_TRACKING_COUPONS

            // MailBeez Email Archive
            // MAILBEEZ_EMAIL_ARCHIVE
            // MAILBEEZ_EMAIL_RATING


            // MAILBEEZ_IDEALO_REVIEWS


            // Shopper Approved


            // MailBeez Tagging


            // Referral Honey if installed
            // TABLE_MAILBEEZ_TRACKING_REFERRAL_HONEY_INVITE_COUPONS
            // TABLE_MAILBEEZ_TRACKING_REFERRAL_HONEY_REDEEMS_CAPTURED
            // TABLE_MAILBEEZ_TRACKING_REFERRAL_HONEY_VIEWS


            // Account aggregation if installed


            // BeezDesk if installed

        }

        $output = fopen("php://output", 'w') or die("Can't open php://output");
        header("Content-Type:text/csv");
        header("Content-Disposition:attachment; filename=customer_data_" . mh_get('csID') . ".csv");

        $dsgvo_export_query = xtc_db_query("SELECT 
        											c.customers_date_added, 
        											c.customers_gender, 
        											c.customers_firstname, 
        											c.customers_lastname, 
        											c.customers_email_address, 
        											ab.entry_company, 
        											c.customers_vat_id, 
        											ab.entry_street_address, 
        											ab.entry_postcode, 
        											ab.entry_city, 
        											tc.countries_name, 
        											c.customers_telephone, 
        											c.customers_fax 
        											FROM " . TABLE_CUSTOMERS . " c 
        											JOIN " . TABLE_ADDRESS_BOOK . " ab 
        											ON c.customers_id = ab.customers_id 
        											JOIN " . TABLE_COUNTRIES . " tc 
        											ON tc.countries_id = ab.entry_country_id 
        											WHERE c.customers_id = " . mh_get('csID'));
        $dsgvo_export_array = xtc_db_fetch_array($dsgvo_export_query);

        foreach ($dsgvo_export_array as $key => $value) {
            if ($key == 'customers_gender') {
                if ($value == 'm') {
                    $value = mh_lng('MALE');
                } else {
                    $value = mh_lng('FEMALE');
                }
            }
            fputcsv($output, array(constant('GDPR_' . strtoupper($key)), $value), ';');
        }
        fputcsv($output, array(''), ';');

        $dsgvo_export_reviews = xtc_db_query("SELECT 
        											r.date_added, 
        											rd.reviews_text, 
        											pd.products_name 
        											FROM " . TABLE_REVIEWS . " r 
        											JOIN " . TABLE_REVIEWS_DESCRIPTION . " rd 
        											ON r.reviews_id = rd.reviews_id 
        											JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd 
        											ON pd.products_id = r.products_id 
        											WHERE customers_id =" . mh_get('csID') . " 
        											AND pd.language_id = " . $_SESSION['languages_id']);

        if (xtc_db_num_rows($dsgvo_export_reviews) > 0) {
            $rNum = 1;
            fputcsv($output, array(mh_lng('DSGVO_REVIEWS_HEADING')), ';');
            fputcsv($output, array(''), ';');

            while ($dsgvo_export_reviews_array = xtc_db_fetch_array($dsgvo_export_reviews)) {
                fputcsv($output, array(mh_lng('DSGVO_REVIEW_HEADING') . " " . $rNum,), ';');
                fputcsv($output, array(mh_lng('DSGVO_DATE'), date('d.m.Y', strtotime($dsgvo_export_reviews_array['date_added']))), ';');
                fputcsv($output, array(mh_lng('DSGVO_PRODUCT_NAME'), $dsgvo_export_reviews_array['products_name']), ';');
                fputcsv($output, array(mh_lng('DSGVO_REVIEWS_TEXT'), $dsgvo_export_reviews_array['reviews_text']), ';');
                fputcsv($output, array(''), ';');

                $rNum++;
            }
        }

        $dsgvo_orders_query = xtc_db_query("SELECT *
        										FROM " . TABLE_ORDERS . " o 
        										WHERE customers_id = " . mh_get('csID'));

        if (xtc_db_num_rows($dsgvo_orders_query) > 0) {

            fputcsv($output, array(mh_lng('DSGVO_ORDERS_HEADING')), ';');
            fputcsv($output, array(''), ';');

            $oNum = 1;

            while ($dsgvo_orders_array = xtc_db_fetch_array($dsgvo_orders_query)) {

                fputcsv($output, array(mh_lng('DSGVO_ORDER_HEADING') . " " . $oNum), ';');
                fputcsv($output, array(mh_lng('DSGVO_ORDER_ID'), $dsgvo_orders_array['orders_id']), ';');
                fputcsv($output, array(mh_lng('DSGVO_ORDER_DATE'), $dsgvo_orders_array['date_purchased']), ';');
                fputcsv($output, array(mh_lng('DSGVO_ORDER_IP_ADDRESS'), $dsgvo_orders_array['customers_ip']), ';');
                fputcsv($output, array(mh_lng('DSGVO_ORDER_COMMENT'), $dsgvo_orders_array['comments']), ';');
                fputcsv($output, array(mh_lng('DSGVO_CUSTOMER_ADDRESS'), $dsgvo_orders_array['customers_name'], $dsgvo_orders_array['customers_street_address'], $dsgvo_orders_array['customers_postcode'] . ' ' . $dsgvo_orders_array['customers_city'], $dsgvo_orders_array['customers_country']), ';');
                fputcsv($output, array(mh_lng('DSGVO_SHIPPING_ADDRESS'), $dsgvo_orders_array['delivery_name'], $dsgvo_orders_array['delivery_street_address'], $dsgvo_orders_array['delivery_postcode'] . ' ' . $dsgvo_orders_array['delivery_city'], $dsgvo_orders_array['delivery_country']), ';');
                fputcsv($output, array(mh_lng('DSGVO_BILLING_ADDRESS'), $dsgvo_orders_array['billing_name'], $dsgvo_orders_array['billing_street_address'], $dsgvo_orders_array['billing_postcode'] . ' ' . $dsgvo_orders_array['billing_city'], $dsgvo_orders_array['billing_country']), ';');
                fputcsv($output, array(mh_lng('DSGVO_CUSTOMER_LANGUAGE'), $dsgvo_orders_array['language']), ';');
                fputcsv($output, array(mh_lng('DSGVO_PAYMENT_METHOD'), $dsgvo_orders_array['payment_method']), ';');

                $dsgvo_product_query = xtc_db_query("SELECT op.orders_id, op.orders_products_id, op.products_quantity, op.products_name, op.products_price, op.products_model, op.products_tax, op.final_price, op.products_id, op.allow_tax FROM " . TABLE_ORDERS_PRODUCTS . " op WHERE op.orders_id = " . $dsgvo_orders_array['orders_id']);

                $first_product = true;

                while ($dsgvo_product_array = xtc_db_fetch_array($dsgvo_product_query)) {
                    $products_price = format_price($dsgvo_product_array['products_price'], 0, $dsgvo_orders_array['currency'], $dsgvo_product_array['allow_tax'], $dsgvo_product_array['products_tax']);
                    $attribute_query = xtc_db_query("SELECT opa.products_options, opa.products_options_values FROM " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " opa WHERE opa.orders_id = " . $dsgvo_product_array['orders_id'] . " AND opa.orders_products_id = " . $dsgvo_product_array['orders_products_id']);

                    $attr_string = '';

                    if (xtc_db_num_rows($attribute_query) > 0) {

                        while ($attribute_fetch_array = xtc_db_fetch_array($attribute_query)) {
                            // Attribute in gleicher Zeile
                            //$attr_string.= ' / '.$attribute_fetch_array['products_options'].': '.$attribute_fetch_array['products_options_values'];
                            // Attribute in neuer Zeile
                            $attr_string .= " \n" . $attribute_fetch_array['products_options'] . ': ' . $attribute_fetch_array['products_options_values'];
                        }
                    }

                    if ($first_product) {
                        fputcsv($output, array(mh_lng('DSGVO_ORDER_HEADING'), $dsgvo_product_array['products_quantity'] . " x " . $dsgvo_product_array['products_name'] . " " . $attr_string, mh_lng('DSGVO_PRODUCT_NUMBER') . ": " . $dsgvo_product_array['products_model'], mh_lng('DSGVO_PRICE_EXKL') . ": " . $products_price, mh_lng('DSGVO_TAX') . ": " . (int)$dsgvo_product_array['products_tax'] . "%", mh_lng('DSGVO_PRICE_INKL') . ": " . xtc_format_price($dsgvo_product_array['products_price'], 1, false), mh_lng('DSGVO_TOTAL_PRICE') . ": " . xtc_format_price($dsgvo_product_array['final_price'], 1, false)), ';');
                        $first_product = false;
                    } else {
                        fputcsv($output, array('', $dsgvo_product_array['products_quantity'] . " x " . $dsgvo_product_array['products_name'] . " " . $attr_string, mh_lng('DSGVO_PRODUCT_NUMBER') . ": " . $dsgvo_product_array['products_model'], mh_lng('DSGVO_PRICE_EXKL') . ": " . $products_price, mh_lng('DSGVO_TAX') . ": " . (int)$dsgvo_product_array['products_tax'] . "%", mh_lng('DSGVO_PRICE_INKL') . ": " . xtc_format_price($dsgvo_product_array['products_price'], 1, false), mh_lng('DSGVO_TOTAL_PRICE') . ": " . xtc_format_price($dsgvo_product_array['final_price'], 1, false)), ';');
                    }
                }

                $dsgvo_order_total_query = xtc_db_query("SELECT ot.text, ot.value, ot.title FROM " . TABLE_ORDERS_TOTAL . " ot WHERE ot.orders_id = " . $dsgvo_orders_array['orders_id'] . " ORDER BY ot.sort_order ASC");

                while ($dsgvo_order_total_array = xtc_db_fetch_array($dsgvo_order_total_query)) {
                    fputcsv($output, array('', '', '', '', '', '', '', strip_tags(html_entity_decode($dsgvo_order_total_array['title'])) . strip_tags($dsgvo_order_total_array['text'])), ';');
                }
                fputcsv($output, array(''), ';');
                $oNum++;
            }
        }
        fclose($output) or die("Can't close php://output");
        exit();


    }

}

