<?php

class ControllerSaleContact extends Controller
{
    private $error = array();

    public function index()
    {

        $this->load->type('tipocomum');

        $this->language->load('sale/contact');

        $this->document->setTitle($this->language->get('heading_title'));

        $this->data['heading_title'] = $this->language->get('heading_title');

        $this->document->addScript(array(
            'view/javascript/page.contact.js',
            'view/javascript/ckeditor/ckeditor.js'
        ));

        $this->data['text_default'] = $this->language->get('text_default');
        $this->data['text_newsletter'] = $this->language->get('text_newsletter');
        $this->data['text_customer_all'] = $this->language->get('text_customer_all');
        $this->data['text_customer'] = $this->language->get('text_customer');
        $this->data['text_customer_group'] = $this->language->get('text_customer_group');
        $this->data['text_product'] = $this->language->get('text_product');
        $this->data['text_module_newsletter'] = $this->language->get('text_module_newsletter');

        $this->data['entry_store'] = $this->language->get('entry_store');
        $this->data['entry_to'] = $this->language->get('entry_to');
        $this->data['entry_customer_group'] = $this->language->get('entry_customer_group');
        $this->data['entry_customer'] = $this->language->get('entry_customer');
        $this->data['entry_affiliate'] = $this->language->get('entry_affiliate');
        $this->data['entry_product'] = $this->language->get('entry_product');
        $this->data['entry_subject'] = $this->language->get('entry_subject');
        $this->data['entry_message'] = $this->language->get('entry_message');

        $this->data['button_send'] = $this->language->get('button_send');
        $this->data['button_cancel'] = $this->language->get('button_cancel');
        $this->data['button_csv'] = $this->language->get('button_csv');

        $this->data['token'] = $this->session->data['token'];

        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('sale/contact', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => ' :: '
        );

        $this->data['cancel'] = $this->url->link('sale/contact', 'token=' . $this->session->data['token'], 'SSL');

        $this->load->model('setting/store');

        $this->data['stores'] = $this->model_setting_store->getStores();

        $this->load->dmodel('sale/customer_group');

        $this->data['customer_groups'] = $this->dmodel_sale_customer_group->getCustomerGroups(0);

        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->data['type_contacts'] = ftr_Geral::setTypeInArray([
            'type' => Type_ContactTo::getEnumList(),
            'compare_type' => 'selected'
        ]);

        $this->response->setOutput($this->render('sale/contact'));
    }

    public function send()
    {
        $this->language->load('sale/contact');

        $json = array();

        if ($this->request->server['REQUEST_METHOD'] == 'POST') {
            if (!$this->user->hasPermission('modify', 'sale/contact')) {
                $json['error']['warning'] = $this->language->get('error_permission');
            }

            if (!$this->request->post['subject']) {
                $json['error']['subject'] = $this->language->get('error_subject');
            }

            if (!$this->request->post['message']) {
                $json['error']['message'] = $this->language->get('error_message');
            }

            if (!$json) {
                $this->load->model('setting/store');

                $store_info = $this->model_setting_store->getStore($this->request->post['store_id']);

                if ($store_info) {
                    $store_name = $store_info['name'];
                } else {
                    $store_name = $this->config->get('config_name');
                }

                $this->load->model('sale/customer');

                $this->load->dmodel('sale/customer_group');

                $this->load->model('sale/affiliate');

                $this->load->model('sale/order');

                if (isset($this->request->get['page'])) {
                    $page = $this->request->get['page'];
                } else {
                    $page = 1;
                }

                $email_total = 0;

                $emails = array();

                switch ($this->request->post['to']) {
                    case 'newsletter':
                        $customer_data = array(
                            'filter_newsletter' => 1,
                            'start' => ($page - 1) * 10,
                            'limit' => 10
                        );

                        $email_total = $this->model_sale_customer->getTotalCustomers($customer_data);

                        $results = $this->model_sale_customer->getCustomers($customer_data);

                        foreach ($results as $result) {
                            $emails[] = $result['email'];
                        }
                        break;
                    case 'customer_all':
                        $customer_data = array(
                            'start' => ($page - 1) * 10,
                            'limit' => 10
                        );

                        $email_total = $this->model_sale_customer->getTotalCustomers($customer_data);

                        $results = $this->model_sale_customer->getCustomers($customer_data);

                        foreach ($results as $result) {
                            $emails[] = $result['email'];
                        }
                        break;
                    case 'customer_group':
                        $customer_data = array(
                            'filter_customer_group_id' => $this->request->post['customer_group_id'],
                            'start' => ($page - 1) * 10,
                            'limit' => 10
                        );

                        $email_total = $this->model_sale_customer->getTotalCustomers($customer_data);

                        $results = $this->model_sale_customer->getCustomers($customer_data);

                        foreach ($results as $result) {
                            $emails[$result['customer_id']] = $result['email'];
                        }
                        break;
                    case 'customer':
                        if (!empty($this->request->post['customer'])) {
                            foreach ($this->request->post['customer'] as $customer_id) {
                                $customer_info = $this->model_sale_customer->getCustomer($customer_id);

                                if ($customer_info) {
                                    $emails[] = $customer_info['email'];
                                }
                            }
                        }
                        break;
                    case 'product':
                        if (isset($this->request->post['product'])) {
                            $email_total = $this->model_sale_order->getTotalEmailsByProductsOrdered($this->request->post['product']);

                            $results = $this->model_sale_order->getEmailsByProductsOrdered($this->request->post['product'], ($page - 1) * 10, 10);

                            foreach ($results as $result) {
                                $emails[] = $result['email'];
                            }
                        }
                        break;
                    case 'module_newsletter':
                        $results = $this->model_sale_order->getNewsletterByEmail();

                        foreach ($results as $result) {
                            $emails[] = $result['email'];
                        }

                        break;
                }

                if ($emails) {
                    $start = ($page - 1) * 10;
                    $end = $start + 10;

                    if ($end < $email_total) {
                        $json['success'] = sprintf($this->language->get('text_sent'), $start, $email_total);
                    } else {
                        $json['success'] = $this->language->get('text_success');
                    }

                    if ($end < $email_total) {
                        $json['next'] = str_replace('&amp;', '&', $this->url->link('sale/contact/send', 'token=' . $this->session->data['token'] . '&page=' . ($page + 1), 'SSL'));
                    } else {
                        $json['next'] = '';
                    }

                    $message = '<html dir="ltr" lang="en">' . "\n";
                    $message .= '  <head>' . "\n";
                    $message .= '    <title>' . $this->request->post['subject'] . '</title>' . "\n";
                    $message .= '    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' . "\n";
                    $message .= '  </head>' . "\n";
                    $message .= '  <body>' . html_entity_decode($this->request->post['message'], ENT_QUOTES, 'UTF-8');
                    $message .= '({unsubscribe_link})';
                    $message .= '  </body>' . "\n";
                    $message .= '</html>' . "\n";

                    foreach ($emails as $email) {
                        if (in_array($this->request->post['to'], [Type_ContactTo::Tp_Newsletter, Type_ContactTo::Tp_ModuleNewsletter])) {
                            $unsubscribe_link = $this->urlloja->link('newsletter/unsubscribe', 'email=' . base64_encode($email), 'SSL');
                            $unsubscribe_element = '
                                <span style="font-size: 11px;">
                                    Caso não queira mais receber esses emails, voce pode se descadastrar no link a seguir:
                                    <a href="' . $unsubscribe_link . '">Descadastrar Email</a>
                                </span>';
                            $messageSend = str_replace('({unsubscribe_link})', "\n" . $unsubscribe_element, $message);
                        } else {
                            $messageSend = str_replace('({unsubscribe_link})', '', $message);
                        }

                        $mail = new Mail();
                        $mail->protocol = $this->config->get('config_mail_protocol');
                        $mail->parameter = $this->config->get('config_mail_parameter');
                        $mail->hostname = $this->config->get('config_smtp_host');
                        $mail->username = $this->config->get('config_smtp_username');
                        $mail->password = $this->config->get('config_smtp_password');
                        $mail->port = $this->config->get('config_smtp_port');
                        $mail->timeout = $this->config->get('config_smtp_timeout');
                        $mail->setTo($email);
                        $mail->setFrom($this->config->get('config_email'));
                        $mail->setSender($store_name);
                        $mail->setSubject(html_entity_decode($this->request->post['subject'], ENT_QUOTES, 'UTF-8'));
                        $mail->setHtml($messageSend);
                        $mail->send();
                    }
                } else {
                    $json['error']['warning'] = $this->language->get('error_send_newsletter_email');
                }
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function gerarCsv()
    {

        $to = 0;

        $json = array();
        $arrayCsv = array();

        $this->language->load('sale/contact');

        $this->load->type('tipocomum');

        $this->load->model('sale/customer');
        $this->load->dmodel('sale/customer_group');
        $this->load->model('sale/affiliate');
        $this->load->model('sale/order');

        if (isset($this->request->get['to'])) {

            $to = $this->request->get['to'];

            switch ($this->request->get['to']) {
                case Type_ContactTo::Tp_Newsletter :
                    $customer_data = array(
                        'filter_newsletter' => 1
                    );

                    $results = $this->model_sale_customer->getCustomers($customer_data);
                    $arrayCsv = $this->getArrayCsv($results);
                    break;
                case Type_ContactTo::Tp_CustomerAll :
                    $results = $this->model_sale_customer->getCustomers();
                    $arrayCsv = $this->getArrayCsv($results);
                    break;
                case Type_ContactTo::Tp_CustomerGroup :
                    $customer_data = array(
                        'filter_customer_group_id' => $this->request->get['customer_group_id']
                    );
                    $results = $this->model_sale_customer->getCustomers($customer_data);
                    $arrayCsv = $this->getArrayCsv($results);
                    break;
                case Type_ContactTo::Tp_Customer :
                    if (!empty($this->request->get['customer'])) {
                        foreach ($this->request->get['customer'] as $customer_id) {

                            $results = $this->model_sale_customer->getCustomer($customer_id);

                            foreach ($results as $key => $value) {

                                if ($key == 'firstname') {
                                    $arrayCsv[$customer_id]['firstname'] = ucwords(strtolower(utf8_decode($results['firstname'] . ' ' . $results['lastname'])));
                                }

                                if ($key == 'email') {
                                    $arrayCsv[$customer_id]['email'] = $value;
                                }
                            }
                        }
                    }
                    break;
                case Type_ContactTo::Tp_Product :
                    if (isset($this->request->get['product'])) {
                        $results = $this->model_sale_order->getEmailsByProductsOrdered($this->request->get['product'], 1 * 10, 10);
                        $arrayCsv = $this->getArrayCsv($results);
                    }
                    break;
                case Type_ContactTo::Tp_ModuleNewsletter :
                    $this->load->model('sale/order');
                    $results = $this->model_sale_order->getNewsletterByEmail();
                    foreach ($results as $key => $value) {
                        $arrayCsv[] = array(
                            'email' => $value['email']
                        );
                    }
                    break;
            }
        }

        ini_set('memory_limit', '128M');
        ini_set('max_execution_time', '900');

        if (count($arrayCsv) > 0) {
            //caso tenha um ou mais csv's gerados esta função apaga todos os csv's antes de gerar um novo
            foreach (Type_ContactTo::getenumlist() as $key => $value) {
                if (file_exists($key . '.csv')) {
                    unlink($key . '.csv');
                }
            }

            $output = fopen($to . ".csv", "wb");
            foreach ($arrayCsv as $key => $value) {
                fputcsv($output, $value);
            }
            fclose($output);

            $json['success'] = $this->language->get('success_csv');
        } else {
            $json['error'] = $this->language->get('error_csv_newsletter_email');
        }

        $this->response->setOutputJson($json);

    }

    public function downloadCsv()
    {

        //caso tenha um ou mais csv's gerados esta função apaga todos os csv's antes de gerar um novo
        foreach (Type_ContactTo::getenumlist() as $key => $value) {
            if (file_exists($key . '.csv')) {
                header('Content-Description: File Transfer');
                header('Content-Disposition: attachment; filename="' . $key . '.csv"');
                header('Content-Type: application/octet-stream');
                header('Content-Transfer-Encoding: binary');
                header('Content-Length: ' . filesize($key . ".csv"));
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Expires: 0');
                readfile($key . ".csv");
                unlink($key . ".csv");
            }
        }
    }


    public function getArrayCsv($array, $customer_id = null)
    {

        $arrayReturn = array();
        foreach ($array as $key => $value) {
            $arrayReturn[] = array(
                'firstname' => ucwords(strtolower(utf8_decode($value['firstname'] . ' ' . $value['lastname']))),
                'email' => $value['email']
            );
        }
        return $arrayReturn;
    }

}
