<?php
$loader = $this->registry->get('load');
$loader->controller('base/base');

class ControllerNewsletterUnsubscribe extends ControllerBaseBase
{
    protected $referencePathFile = 'newsletter/unsubscribe';

    protected function loadStyle()
    {
        $this->document->addStyle("public/css/minimalist.css");
    }

    protected function actionUrls()
    {
    }

    protected function loadModel()
    {
        $this->load->model('account/newsletter');
        $this->load->model('account/customer');

        parent::loadModel();
    }

    protected function loadData()
    {
    }

    protected function childrens()
    {
        $this->children = [
            'common/header_minimalist'
        ];
    }

    public function index()
    {
        parent::index();

        $this->dataVue['errors'] = false;
        $this->dataVue['success'] = false;

        if ($this->request->server['REQUEST_METHOD'] == 'POST') {

            if (!$this->validate()) {
                $this->dataVue['errors'] = $this->errors;
            } else {
                $email = base64_decode($this->request->request['email']);
                // descadastra da lista de emails informativos
                if (isset($this->request->post['newsletter_informative'])) {
                    $customer = $this->model_account_customer->getCustomerByEmail($email);
                    if ($customer) {
                        $customer_id = $customer['customer_id'];
                        $this->model_account_customer->editNewsletterByCustomerId($customer_id, 0);
                    }
                }
                // descadastra da lista de emails de novidades
                if (isset($this->request->post['newsletter_news'])) {
                    $this->model_account_newsletter->deleteNewsletter($email);
                }

                $this->dataVue['success'] = $this->language->get('text_success');;
            }
        }

        $this->response->setOutput($this->render($this->referencePathFile));
    }

    public function validate()
    {
        if (!isset($this->request->request['email']) || (empty($this->request->request['email']))){
            $this->errors[] = $this->language->get('text_warning_email');
        }

        if (!isset($this->request->post['newsletter_informative']) && !isset($this->request->post['newsletter_news'])){
            $this->errors[] = $this->language->get('text_warning_choose_option');
        }

        return !$this->errors;
    }
}
