<?php

class ControllerMelhorenvioMelhorenvio extends Controller
{

    public function index()
    {
        // Language
        $language = $this->language->load('module/melhorenvio');
        $this->data = array_merge($this->data, $language);

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

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

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_title'),
            'href' => $this->url->link('melhorenvio/melhorenvio'),
            'separator' => $this->language->get('text_separator')
        );

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

        // Title
        $this->document->setTitle($this->language->get('text_title'));

        $this->data['continue'] = $this->url->link('common/home');

        $this->data['auth_done'] = '' ;

        if ($this->config->get('melhorenvio_refresh_token')) {
            if( $this->melhorenvio->getAppSetting() ) {
                $this->data['auth_done'] = '1';
                $this->data['text_auth'] = $this->language->get('text_reauth');
            } else {
                $this->data['text_auth'] = $this->language->get('text_auth');
            }
        }

        $environment = $this->request->get['environment'] ?? null;

        $this->data['login_url'] = $this->melhorenvio->getLoginUrl($environment);

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/melhorenvio/auth.twig')) {
            $this->template = $this->config->get('config_template') . '/template/melhorenvio/auth.twig';
        } else {
            $this->template = 'default/template/melhorenvio/auth.twig';
        }

        $this->children = array(
            'common/breadcrumbs',
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header'
        );

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

    public function callback()
    {
        $this->data['error'] = '';
        if (isset($this->request->get['error'])) {
            $this->data['error'] = 'Error: ' . $this->request->get['error'] . (($this->request->get['error_description']) ? ' - ' . $this->request->get['error_description'] : '');
        }

        if (isset($this->request->get['code'])) {
            $this->melhorenvio->getRefreshToken($this->request->get['code']);
        }

        $urlAuth = $this->urlloja->link('', '', 'NONSSL', false) . 'melhorenvioauth';
        $this->redirect($urlAuth);
    }
}
