<?php
/*
 ************************************************************************
 Copyright [2013] [PagSeguro Internet Ltda.]

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 ************************************************************************
 */

/**
 * Controller Payment PagSeguro.
 * Class responsible for the configuration data of the user of PagSeguro (adm)
 */
class ControllerPaymentPagSeguro extends Controller
{

    /**
     * Array Error
     * @var array
     */
    private $error = array();

    /**
     *Regex validate e-mail
     * @var regex
     */
    private $pattern = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';

    /**
     * Array of extensions
     * @var string
     */
    private $array_extension = array(".txt", ".log");

    public function index()
    {
        $this->_addPagSeguroLibrary();
        $language = $this->language->load('payment/pagseguro');
        $this->data = array_merge($this->data, $language);

        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('setting/setting');
        $this->load->helper('ftr_geral');
        $this->load->type('tipopagseguro');

        $this->document->addScript(array(
            'public/js/payment/pagseguro.js'
        ));
        $this->data['ftr_geral'] = new ftr_geral();

        $this->data['Type_Environment'] = $this->load->typeForTwig('Type_Environment');
        $this->data['Type_DisplayModuleOption'] = $this->load->typeForTwig('Type_DisplayModuleOption');

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
            $this->_removeMasks();
            $this->model_setting_setting->editSetting('pagseguro', $this->request->post);
            $this->session->data['success'] = $this->language->get('text_success');
            $this->_setPagSeguroConfiguration();
            $this->redirect($this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'));
        }

        $this->data['url_validate_credentials'] = $this->url->link('payment/pagseguro/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');

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

        $this->load->model("localisation/order_status");
        $this->data["order_statuses"] = $this->model_localisation_order_status->getOrderStatuses();

        $this->_createInput();
        $this->_createBreadcrumbs();
        $this->_createLink();
        $this->_createError();

        $this->children = array(
            'common/header',
            'common/footer'
        );
        $this->response->setOutput($this->render('payment/pagseguro'));
    }

    /**
     * Remove mask from fields to post'em by marcolas
     */
    private function _removeMasks(){
        $this->_removeMask('pagseguro_total');
        $this->_removeMask('pagseguro_boleto_desconto');
        $this->_removeMask('pagseguro_cartao_credito_desconto');
        $this->_removeMask('pagseguro_debito_desconto');
        $this->_removeMask('pagseguro_deposito_desconto');
    }

    private function _removeMask($fieldName){
        if(isset($this->request->post[$fieldName]) && $this->request->post[$fieldName]){
            $this->request->post[$fieldName] = ftr_geral::removeMaskToDouble($this->request->post[$fieldName]);
        }
    }

    /**
     * Add PagSeguro Libary
     */
    private function _addPagSeguroLibrary()
    {
        include_once DIR_CATALOG . 'controller/payment/PagSeguroLibrary/PagSeguroLibrary.php';
    }

    /**
     * Create Input
     */
    private function _createInput()
    {

        if (isset($this->request->post['pagseguro_status']))
            $this->data['pagseguro_status'] = $this->request->post['pagseguro_status'];
        else
            $this->data['pagseguro_status'] = $this->config->get('pagseguro_status');

        if (isset($this->request->post['pagseguro_sort_order']))
            $this->data['pagseguro_sort_order'] = $this->request->post['pagseguro_sort_order'];
        else
            $this->data['pagseguro_sort_order'] = $this->config->get('pagseguro_sort_order');

        if (isset($this->request->post['pagseguro_email']))
            $this->data['pagseguro_email'] = $this->request->post['pagseguro_email'];
        else
            $this->data['pagseguro_email'] = $this->config->get('pagseguro_email');

        if (isset($this->request->post['pagseguro_token']))
            $this->data['pagseguro_token'] = $this->request->post['pagseguro_token'];
        else
            $this->data['pagseguro_token'] = $this->config->get('pagseguro_token');

        if (isset($this->request->post['pagseguro_forwarding']))
            $this->data['pagseguro_forwarding'] = $this->request->post['pagseguro_forwarding'];
        else
            $this->data['pagseguro_forwarding'] = $this->validateRedirectUrl();

        if (isset($this->request->post['pagseguro_url_notification']))
            $this->data['pagseguro_url_notification'] = $this->request->post['pagseguro_url_notification'];
        else
            $this->data['pagseguro_url_notification'] = $this->validateNotificationUrl();

        if (isset($this->request->post['pagseguro_charset']))
            $this->data['pagseguro_charset'] = $this->request->post['pagseguro_charset'];
        else
            $this->data['pagseguro_charset'] = $this->config->get('pagseguro_charset');

        if (isset($this->request->post['pagseguro_log']))
            $this->data['pagseguro_log'] = $this->request->post['pagseguro_log'];
        else
            $this->data['pagseguro_log'] = $this->config->get('pagseguro_log');

        if (isset($this->request->post['pagseguro_directory']))
            $this->data['pagseguro_directory'] = $this->request->post['pagseguro_directory'];
        else
            $this->data['pagseguro_directory'] = $this->config->get('pagseguro_directory');

        if (isset($this->request->post['pagseguro_parcela']))
            $this->data['pagseguro_parcela'] = $this->request->post['pagseguro_parcela'];
        else
            $this->data['pagseguro_parcela'] = $this->config->get('pagseguro_parcela');

        if (isset($this->request->post['pagseguro_title_name']))
            $this->data['pagseguro_title_name'] = $this->request->post['pagseguro_title_name'];
        else
            $this->data['pagseguro_title_name'] = $this->config->get('pagseguro_title_name');

        if (isset($this->request->post['pagseguro_boleto_desconto']))
            $this->data['pagseguro_boleto_desconto'] = $this->request->post['pagseguro_boleto_desconto'];
        else
            $this->data['pagseguro_boleto_desconto'] = $this->config->get('pagseguro_boleto_desconto');

        if (isset($this->request->post['pagseguro_environment_status']))
            $this->data['pagseguro_environment_status'] = $this->request->post['pagseguro_environment_status'];
        else
            $this->data['pagseguro_environment_status'] = $this->config->get('pagseguro_environment_status');

        if (isset($this->request->post['pagseguro_cartao_credito_desconto']))
            $this->data['pagseguro_cartao_credito_desconto'] = $this->request->post['pagseguro_cartao_credito_desconto'];
        else
            $this->data['pagseguro_cartao_credito_desconto'] = $this->config->get('pagseguro_cartao_credito_desconto');

        if (isset($this->request->post['pagseguro_debito_desconto']))
            $this->data['pagseguro_debito_desconto'] = $this->request->post['pagseguro_debito_desconto'];
        else
            $this->data['pagseguro_debito_desconto'] = $this->config->get('pagseguro_debito_desconto');

        if (isset($this->request->post['pagseguro_deposito_desconto']))
            $this->data['pagseguro_deposito_desconto'] = $this->request->post['pagseguro_deposito_desconto'];
        else
            $this->data['pagseguro_deposito_desconto'] = $this->config->get('pagseguro_deposito_desconto');

        if (isset($this->request->post['pagseguro_order_abandoned']))
            $this->data['pagseguro_order_abandoned'] = $this->request->post['pagseguro_order_abandoned'];
        else
            $this->data['pagseguro_order_abandoned'] = $this->config->get('pagseguro_order_abandoned');

        if (isset($this->request->post['pagseguro_abandoned_order_id']))
            $this->data['pagseguro_abandoned_order_id'] = $this->request->post['pagseguro_abandoned_order_id'];
        else
            $this->data['pagseguro_abandoned_order_id'] = $this->config->get('pagseguro_abandoned_order_id');

        if (isset($this->request->post['pagseguro_awaiting_order_id']))
            $this->data['pagseguro_awaiting_order_id'] = $this->request->post['pagseguro_awaiting_order_id'];
        else
            $this->data['pagseguro_awaiting_order_id'] = $this->config->get('pagseguro_awaiting_order_id');

        if (isset($this->request->post['pagseguro_processing_order_id']))
            $this->data['pagseguro_processing_order_id'] = $this->request->post['pagseguro_processing_order_id'];
        else
            $this->data['pagseguro_processing_order_id'] = $this->config->get('pagseguro_processing_order_id');

        if (isset($this->request->post['pagseguro_processed_order_id']))
            $this->data['pagseguro_processed_order_id'] = $this->request->post['pagseguro_processed_order_id'];
        else
            $this->data['pagseguro_processed_order_id'] = $this->config->get('pagseguro_processed_order_id');

        if (isset($this->request->post['pagseguro_complete_order_id']))
            $this->data['pagseguro_complete_order_id'] = $this->request->post['pagseguro_complete_order_id'];
        else
            $this->data['pagseguro_complete_order_id'] = $this->config->get('pagseguro_complete_order_id');

        if (isset($this->request->post['pagseguro_dispute_order_id']))
            $this->data['pagseguro_dispute_order_id'] = $this->request->post['pagseguro_dispute_order_id'];
        else
            $this->data['pagseguro_dispute_order_id'] = $this->config->get('pagseguro_dispute_order_id');

        if (isset($this->request->post['pagseguro_refunded_order_id']))
            $this->data['pagseguro_refunded_order_id'] = $this->request->post['pagseguro_refunded_order_id'];
        else
            $this->data['pagseguro_refunded_order_id'] = $this->config->get('pagseguro_refunded_order_id');

        if (isset($this->request->post['pagseguro_cancelado_order_id']))
            $this->data['pagseguro_cancelado_order_id'] = $this->request->post['pagseguro_cancelado_order_id'];
        else
            $this->data['pagseguro_cancelado_order_id'] = $this->config->get('pagseguro_cancelado_order_id');

        if (isset($this->request->post['pagseguro_debitado_order_id']))
            $this->data['pagseguro_debitado_order_id'] = $this->request->post['pagseguro_debitado_order_id'];
        else
            $this->data['pagseguro_debitado_order_id'] = $this->config->get('pagseguro_debitado_order_id');

        if (isset($this->request->post['pagseguro_retencao_order_id']))
            $this->data['pagseguro_retencao_order_id'] = $this->request->post['pagseguro_retencao_order_id'];
        else
            $this->data['pagseguro_retencao_order_id'] = $this->config->get('pagseguro_retencao_order_id');

        if (isset($this->request->post['pagseguro_display']))
            $this->data['pagseguro_display'] = $this->request->post['pagseguro_display'];
        else
            $this->data['pagseguro_display'] = $this->config->get('pagseguro_display');

        if (isset($this->request->post['pagseguro_total']))
            $this->data['pagseguro_total'] = $this->request->post['pagseguro_total'];
        else
            $this->data['pagseguro_total'] = $this->config->get('pagseguro_total');
    }

    /**
     * Create Breadcrumbs to view.
     */
    private function _createBreadcrumbs()
    {

        $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('text_payment'),
            'href' => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
            'separator' => ' :: '
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('payment/pagseguro', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
            'separator' => ' :: '
        );
    }

    /**
     * Create Link's
     */
    private function _createLink()
    {
        $this->data['action'] = $this->url->link('payment/pagseguro', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL');
        $this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');
    }

    /**
     * Create Error
     */
    private function _createError()
    {

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        if (isset($this->error['email'])) {
            $this->data['error_email'] = $this->error['email'];
        } else {
            $this->data['error_email'] = '';
        }

        if (isset($this->error['token'])) {
            $this->data['error_token'] = $this->error['token'];
        } else {
            $this->data['error_token'] = '';
        }
    }

    /**
     * Validate
     * @return boolean
     */
    protected function validate()
    {
        $this->_permission();
        $this->_validateEmail();
        $this->_validateToken();
        $this->_notificationUrl();
        $this->_redirectUrl();

        return (empty($this->error)) ? true : false;
    }

    /**
     * Validate Permisson
     */
    private function _permission()
    {
        if (!$this->user->hasPermission('modify', 'payment/pagseguro'))
            $this->error['warning'] = $this->language->get('error_permission');
    }

    /**
     * Validate E-mail
     */
    private function _validateEmail()
    {
        if (empty($this->request->post['pagseguro_email']))
            $this->error['email'] = $this->language->get('error_email_required');

        if (!empty($this->request->post['pagseguro_email'])) {
            $valid = preg_match($this->pattern, $this->request->post['pagseguro_email']);

            if ($valid != 1) {
                $this->error['email'] = $this->language->get('error_email_invalid');
            }
        }
    }

    /**
     * Validate Token
     */
    private function _validateToken()
    {
        if (empty($this->request->post['pagseguro_token'])) {
            $this->error['token'] = $this->language->get('error_token_required');
        }

        if (empty($this->request->post['pagseguro_token'])
            && $this->request->post['pagseguro_environment_status'] == Type_Environment::Tp_Production) {
            $this->error['token'] = $this->language->get('error_token_invalid');
        }
    }

    /**
     * Retrieve PagSeguro data configuration from database
     */
    private function _setPagSeguroConfiguration()
    {
        $charset = ($this->request->post['pagseguro_charset'] == 1) ? $this->language->get('iso') : $this->language->get('utf');

        // setting configurated default charset
        PagSeguroConfig::setApplicationCharset($charset);

        $activeLog = ($this->request->post['pagseguro_log'] == 1) ? TRUE : FALSE;

        // setting configurated default log info
        if ($activeLog) {
            $directory = $this->_getDirectoryLog();
            $this->_verifyLogFile($directory);
            PagSeguroConfig::activeLog($directory);
        }
    }

    /**
     * Verify if PagSeguro log file exists.
     * Case log file not exists, try create
     * else, log will be created as name as PagSeguro.log as name into PagseguroLibrary folder into module
     */
    private function _verifyLogFile($file)
    {

        try {
            $f = fopen($file, "a");
            fclose($f);
        } catch (Exception $e) {
            die($e);
        }
    }

    /**
     * Validate Notification Url
     * @return url
     */
    private function validateNotificationUrl()
    {

        $value = $this->config->get('pagseguro_url_notification');

        if (empty($value))
            return $this->_generateNotificationUrl();

        return $value;
    }

    /**
     * Validate Redirect Url
     * @return url
     */
    private function validateRedirectUrl()
    {

        $value = $this->config->get('pagseguro_forwarding');

        if (empty($value))
            return $this->_generationRedirectUrl();

        return $value;
    }

    /**
     * Notification Url
     */
    private function _notificationUrl()
    {

        if (empty($this->request->post['pagseguro_url_notification']))
            $this->data['pagseguro_url_notification'] = $this->_generateNotificationUrl();
    }

    /**
     * Redirect Url
     */
    private function _redirectUrl()
    {

        if (empty($this->request->post['pagseguro_forwarding']))
            $this->data['pagseguro_forwarding'] = $this->_generationRedirectUrl();
    }

    /**
     * Url Notification
     * @return url notification
     */
    private function _generateNotificationUrl()
    {
        return $this->urlloja->link('payment/pagseguro_notification');
    }

    /**
     * Redirect Url
     * @return url redirect
     */
    private function _generationRedirectUrl()
    {
        return $this->urlloja->link('checkout/success');
    }

    /**
     * Validate if value is not null
     * @param type $value
     * @return boolean
     */
    private function _isNotNull($value)
    {

        if ($value != null && $value != "")
            return TRUE;

        return false;
    }

    /**
     * Return directory log
     */
    private function _getDirectoryLog()
    {
        $_dir = str_replace('catalog/', '', DIR_CATALOG);
        $directory = NULL;
        $validate_extension = FALSE;

        if ($this->_isNotNull($this->request->post['pagseguro_directory'])) {
            $directory = $this->request->post['pagseguro_directory'];

            foreach ($this->array_extension as $extension) {
                if (stripos($directory, $extension))
                    $validate_extension = TRUE;
            }
        }

        if ($directory != NULL && $validate_extension == FALSE)
            $directory = $this->_createFileDirectory($directory);

        return ($directory != NULL) ? $_dir . $directory : null;
    }

    /**
     * Create file
     * @param type $directory
     * @return string
     */
    private function _createFileDirectory($directory)
    {

        $directory = explode('/', $directory);
        $path = '';

        foreach ($directory as $char) {
            $path = $path . $char . DIRECTORY_SEPARATOR;
        }

        return $path . 'PagSeguro.log';
    }

    public function validateCredentials() {
        $this->load->language('payment/pagseguro');

        $pagseguro_email = $this->request->get['pagseguro_email'];
        $pagseguro_token = $this->request->get['pagseguro_token'];

        $requestPagseguro = new pagseguro($this->registry);

        $bandeira = 'visa';
        $vlProduto = '1000.00';
        $request = 'https://ws.pagseguro.uol.com.br/v2/installments?email=' . $pagseguro_email . '&token=' . $pagseguro_token . '&amount=' . $vlProduto . '&cardBrand=' . $bandeira;

        $resultado = $requestPagseguro->ConsultaParcela($request);

        if (!empty($resultado)) {
            $this->response->setOutputJson([
                'type' => 'success',
                'message' => $this->language->get('text_success_validate')
            ]);
        } else {
            $this->response->setOutputJson([
                'type' => 'error',
                'message' => $this->language->get('text_error_validate')
            ]);
        }
    }
}
