<?php

class ControllerPaymentPaymentInfo extends Controller
{

    public $order_info;
    public $discount = 0;
    public $increase = 0;
    public $paymentInfo;

    public function setPaymentInfo()
    {

        if (isset($this->request->post['isHolder']) && !$this->request->post['isHolder']) {
            $customer_info = $this->request->post;
        } else {
            $this->load->dmodel('account/customer');
            $customer_info = $this->dmodel_account_customer->getCustomer($this->order_info['customer_id']);
        }
        $nome = isset($customer_info['firstname']) ? $customer_info['firstname'] . ' ' . $customer_info['lastname'] : $customer_info['creditcard_name'];
        $this->paymentInfo->setId($customer_info['customer_id']);
        $this->paymentInfo->setNome($nome);
        $this->paymentInfo->setPrimeiroNome($customer_info['firstname']);
        $this->paymentInfo->setUltimoNome($customer_info['lastname']);

        $this->paymentInfo->setEmail($customer_info['email']);

        if (!empty($customer_info['cpf'])) {
            $this->paymentInfo->setDocumento(Type_Document::Tp_Fisico, $customer_info['cpf']);
        } else if (!empty($customer_info['cnpj'])) {
            $this->paymentInfo->setDocumento(Type_Document::Tp_Juridico, $customer_info['cnpj']);

            if (isset($customer_info['razao_social']) && !empty($customer_info['razao_social'])) {
                $this->paymentInfo->setRazaoSocial($customer_info['razao_social']);
            }
        }

        if (!empty($customer_info['data_nascimento'])) {
            $this->paymentInfo->setDataNascimento($customer_info['data_nascimento']);
        }

        if (isset($customer_info['celular']) && !empty(trim($customer_info['celular']))) {
            $this->paymentInfo->setTelefone(Type_PaymentPhone::Tp_Celular, substr($customer_info['celular'], 0, 2), substr($customer_info['celular'], 2));
        } else if (isset($customer_info['telephone']) && !empty(trim($customer_info['telephone']))) {
            $this->paymentInfo->setTelefone(Type_PaymentPhone::Tp_Telefone, substr($customer_info['telephone'], 0, 2), substr($customer_info['telephone'], 2));
        } else if (isset($customer_info['fax']) && !empty(trim($customer_info['fax']))) {
            $this->paymentInfo->setTelefone(Type_PaymentPhone::Tp_Fax, substr($customer_info['fax'], 0, 2), substr($customer_info['fax'], 2));
        }

        if (isset($customer_info['numero_telefone']) && !empty(trim($customer_info['numero_telefone']))) {
            $numero = preg_replace("/[^0-9]/", "", $this->request->post['numero_telefone']);
            $this->paymentInfo->setTelefone($this->request->post['tipo_telefone'], substr($numero, 0, 2), substr($numero, 2));
        }

        $this->load->model('account/order');
        $order_total = $this->model_account_order->getOrderTotalsByCode($this->order_info['order_id'], 'shipping');
        $this->paymentInfo->setFrete($order_total['value']);

        $shippingAddress = new PaymentInfoAdress();
        if (!empty($this->order_info['shipping_postcode'])) {
            $shippingAddress->setPostcode($this->order_info['shipping_postcode']);
        }

        if (!empty($this->order_info['shipping_address_1'])) {
            $shippingAddress->setRua($this->order_info['shipping_address_1']);
        }

        if (!empty($this->order_info['shipping_numero'])) {
            $shippingAddress->setNumero($this->order_info['shipping_numero']);
        }

        if (!empty($this->order_info['shipping_complemento']) && (!empty($this->order_info['shipping_complemento']))) {
            $shippingAddress->setComplemento($this->order_info['shipping_complemento']);
        }

        if (!empty($this->order_info['shipping_address_2'])) {
            $shippingAddress->setBairro($this->order_info['shipping_address_2']);
        }

        if (!empty($this->order_info['shipping_city'])) {
            $shippingAddress->setCidade($this->order_info['shipping_city']);
        }

        if (!empty($this->order_info['shipping_zone_code'])) {
            $shippingAddress->setUf($this->order_info['shipping_zone_code']);
        }

        if (!empty($this->order_info['shipping_zone'])) {
            $shippingAddress->setUfName($this->order_info['shipping_zone']);
        }

        $this->paymentInfo->setShippingAddress($shippingAddress);

        if (isset($this->request->post['isHolder']) && !$this->request->post['isHolder'] && isset($this->request->post['postcode'])) {

            $paymentInfoAdress = new PaymentInfoAdress();
            if (isset($this->request->post['postcode'])) {
                $paymentInfoAdress->setPostcode($this->request->post['postcode']);
            }

            if (isset($this->request->post['address_1'])) {
                $paymentInfoAdress->setRua($this->request->post['address_1']);
            }

            if (isset($this->request->post['numero'])) {
                $paymentInfoAdress->setNumero($this->request->post['numero']);
            }

            if (isset($this->request->post['complemento']) && (!empty($this->request->post['complemento']))) {
                $paymentInfoAdress->setComplemento($this->request->post['complemento']);
            }

            if (isset($this->request->post['address_2'])) {
                $paymentInfoAdress->setBairro($this->request->post['address_2']);
            }

            if (isset($this->request->post['zone_id'])) {
                $paymentInfoAdress->setUf($this->getEstado($this->request->post['zone_id']));
            }

            if (isset($this->request->post['cidade'])) {
                $paymentInfoAdress->setCidade($this->request->post['cidade']);
            }

            $this->paymentInfo->setPaymentAddress($paymentInfoAdress);
        } else {
            $this->paymentInfo->setPaymentAddress($shippingAddress);
        }
    }

    public function setPaymentCreditCard()
    {

        $paymentCreditCard = new PaymentCreditCard();

        if (isset($this->request->post['creditcard_name'])) {
            $paymentCreditCard->setNome($this->request->post['creditcard_name']);
        }

        if (isset($this->request->post['creditcard_cctype'])) {
            $paymentCreditCard->setBandeira($this->request->post['creditcard_cctype']);
        }

        if (isset($this->request->post['expire'])) {
            $dataExpire = explode('/', $this->request->post['expire']);
            $paymentCreditCard->setDataExp($dataExpire[0], $dataExpire[1]);
        }

        if (isset($this->request->post['creditcard_ccno'])) {
            $paymentCreditCard->setNumero($this->request->post['creditcard_ccno']);
        }

        if (isset($this->request->post['creditcard_cccvd'])) {
            $paymentCreditCard->setCodigo($this->request->post['creditcard_cccvd']);
        }

        if (isset($this->request->post['qtd_parcela'])) {
            $paymentCreditCard->setParcelas($this->request->post['qtd_parcela']);
        }

        $this->paymentInfo->setCreditCard($paymentCreditCard);
    }

    public function setPaymentProducts()
    {

        $this->load->dmodel('account/order');
        $order_products = $this->dmodel_account_order->getOrderProducts($this->order_info['order_id']);
        foreach ($order_products as $order_product) {
            $paymentProduct = new PaymentProduct();
            $paymentProduct->setId($order_product['product_id']);
            $paymentProduct->setDescricao($order_product['name']);
            $paymentProduct->setQuantity($order_product['quantity']);
            $paymentProduct->setPrice($order_product['price']);
            $paymentProduct->setModel($order_product['model']);
            $this->paymentInfo->setProducts($paymentProduct);
        }
    }


    public function getEstado($zone_id)
    {

        $zone_query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "zone` WHERE zone_id = '" . (int)$zone_id . "'");

        if ($zone_query->num_rows) {
            return $zone_query->row['code'];
        } else {
            return '';
        }
    }

    public function getOrderDiscountValue()
    {
        return $this->discount;
    }


    public function setOrderDiscount($order_id)
    {

        $this->load->model('account/order');
        $order_totals = $this->model_account_order->getOrderTotals($order_id);

        foreach ($order_totals as $order_total) {
            if ($order_total['value'] < 0) {
                $this->discount += (float)$order_total['value'] * (-1);
            }
        }

        return $this->discount;
    }

    public function getOrderIncreaseValue()
    {
        return $this->increase;
    }

    public function setOrderIncrease($order_id)
    {

        $this->load->model('account/order');
        $order_totals2 = $this->model_account_order->getOrderTotals($order_id);

        $retorno = array();
        $desconto = 0;

        foreach ($order_totals2 as $key => $order_total2) {
            if ($order_total2['value'] < 0) {
                $desconto += (float)$order_total2['value'] * (-1);
            } else {
                $retorno[$order_total2['code']] = (float)$order_total2['value'];
            }
        }

        $increase = (float)(($retorno['total']) - ($retorno['sub_total'] + $retorno['shipping'] - $desconto));

        if ($increase > 0) {
            $this->increase = $increase;
        }

        return $this->increase;
    }

    public function saveRequiedCustomerInfos()
    {

        $infos = array();
        if (isset($this->request->post['customer_data_nascimento']) && !empty($this->request->post['customer_data_nascimento'])) {
            $infos['data_nascimento'] = ftr_geral::formatDate($this->request->post['customer_data_nascimento'], 'en');
        }

        //tratamento feito porque o campo telefone na base tem outro nome
        if (isset($this->request->post['customer_numero_telefone']) && !empty($this->request->post['customer_numero_telefone'])) {
            if ($this->request->post['customer_tipo_telefone'] == Type_PaymentPhone::Tp_Telefone) {
                $indice = 'telephone';
            } else {
                $indice = strtolower(Type_PaymentPhone::getNickFromConstValue($this->request->post['customer_tipo_telefone']));
            }
            $infos[$indice] = preg_replace('/([^0-9])/i', '', $this->request->post['customer_numero_telefone']);
        }

        if ($infos) {
            $sqlInfos = Ftr_sql::generateUpdate('oc_customer', array_keys($infos), 'customer_id = ' . (int)$this->customer->getId());

            $this->db->executeSql($sqlInfos, array_values($infos));
        }
    }

    public function validate()
    {
        $this->load->dmodel('checkout/order');

        $error = array();

        $data_atual = new DateTime($this->db->dataAtual(), new DateTimeZone('America/Sao_Paulo'));
        $data_atual = $data_atual->format("Y-m-d");
        $count_customer_orders_day = $this->dmodel_checkout_order->getOrdersByCustommer($this->customer->getId(),$data_atual,$data_atual);
        $count_ip_orders_day = $this->dmodel_checkout_order->getOrdersByIP($this->request->server['REMOTE_ADDR'],$data_atual,$data_atual);

        if (!isset($this->request->post['creditcard_cctype'])) {
            $error['creditcard_cctype'] = $this->language->get('error_bandeira');
        }

        if (!isset($this->request->post['creditcard_name']) || strlen($this->request->post['creditcard_name']) == '') {
            $error['creditcard_name'] = $this->language->get('error_nomecartao');
        }

        if (!isset($this->request->post['creditcard_ccno']) || strlen($this->request->post['creditcard_ccno']) == '') {
            $error['creditcard_ccno'] = $this->language->get('error_numerocartao');
        }

        if (!isset($this->request->post['creditcard_cccvd']) || strlen($this->request->post['creditcard_cccvd']) == '') {
            $error['creditcard_cccvd'] = $this->language->get('error_csv');
        }

        if (!isset($this->request->post['expire']) || (strlen($this->request->post['expire']) == '') || (strlen($this->request->post['expire']) != 7/*99/9999*/)) {
            $error['expire'] = $this->language->get('error_validade');
        }

        if (!$this->debug && ((count($count_customer_orders_day) > 1) || (count($count_ip_orders_day) > 1))) {
            $this->language->load('payment/captcha');

            $google_captcha = $this->config->get('google_recaptcha_site_key') && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status');
            $valid_captcha = $this->ftrgeralregistry->validateCaptcha($google_captcha ? $this->request->post['g-recaptcha-response'] : $this->request->post['captcha']);

            if (!$valid_captcha){
                $google_captcha ? $error['g-recaptcha'] = $this->language->get('t_e_google_captcha') : $error['captcha'] = $this->language->get('t_e_captcha');
            }
        }

        $route = $this->request->get['route'];
        $controller = substr($route, 0, strrpos($route, '/'));

        if (file_exists(DIR_APPLICATION . 'controller/' . $controller . '_payment_address.php')) {
            $controller = $controller . '_payment_address';
        } else {
            $controller = 'payment/payment_address';
        }

        $controllerName = str_replace('/', '', strrchr($controller, '/'));
        $controllerName = preg_replace_callback('/_([a-z])/', function ($match) {
            return str_replace('_', '', strtoupper($match[0]));
        }, $controllerName);
        $controllerName = ucfirst($controllerName);

        if ($this->hasAction($controller . '/validate')) {
            $this->load->controller($controller);
            $className = 'ControllerPayment' . $controllerName;
            $controllerPayment = new $className($this->registry);
            $validate = $controllerPayment->validate();
        }

        $error = (is_array($validate)) ? array_merge($validate, $error) : $error;

        if (count($error)>0) {
            return $error;
        } else {
            return false;
        }
    }


    public function parcelamento($module, $html = true, $flag_params = array())
    {
        $json = array();

        $this->load->dmodel('checkout/order');
        $total = 0;
        $order_info = $this->dmodel_checkout_order->getOrderTotals($this->session->data['order_id']);
        $descontokit = 0;
        foreach ($order_info as $order_total) {
            switch ($order_total['code']) {
                case 'sub_total':
                    $sub_total = (float)$order_total['value'];
                    break;
                case 'total':
                    $total = (float)$order_total['value'];
                    break;
                case 'descontoacrescimokit':
                    $descontokit = (float)$order_total['value'] * -1;
                    break;
            }
        }
        /*Caso cliente tenha kit, o subtotal estará levando em conta o total dos produtos que compoem o kit
          mas ele deve levar em conta o valor do kit pai, por isso precisa remover o desconto->*/
        $sub_total = (float)$sub_total - (float)$descontokit;

        if (count($flag_params) > 1) {
            /* Parametros por bandeira Yapay/Wirecard */
            $parametros_parcelamento = array(
                'parcela_maxima_qtd' => (int)$flag_params['parcela_maxima_qtd'],
                'parcela_minima_val' => (float)$flag_params['parcela_minima_val'],
                'parcela_sem_juros' => (int)$flag_params['parcela_sem_juros'],
                'parcela_com_desconto' => 0,
                'desconto' => 0,
                'juros' => (float)$flag_params['juros']
            );
        } else {
            $pminima = in_array($module,
                array(Type_CreditCardModule::getNickFromConstValue(Type_CreditCardModule::Cielo),
                      Type_CreditCardModule::getNickFromConstValue(Type_CreditCardModule::Rede)))
                        ? $this->config->get($module . '_parcela_minimo')
                        : $this->config->get($module . '_parcela_minima');
            $parametros_parcelamento = array(
                'parcela_maxima_qtd' => (int)$this->config->get($module . '_parcela_qtdmax'),
                'parcela_minima_val' => (float)str_replace(',', '.', $pminima),
                'parcela_sem_juros' => (int)$this->config->get($module . '_parcela_semjuros'),
                'parcela_com_desconto' => (int)$this->config->get($module . '_parcela_comdesconto'),
                'desconto' => (float)str_replace(',', '.', $this->config->get($module . '_parcela_desconto')),
                'juros' => (float)str_replace(',', '.', $this->config->get($module . '_parcela_juros'))
            );
        }

        if ($this->config->get($module . '_config_parcelamento') == Type_ConfigParcelamento::PorParcela) {
            $parametros_parcela = $this->config->get($module . '_parcelamento_configs');
            $parcelas = ftr_geral::getParcelamento($total, $sub_total, $parametros_parcelamento['parcela_minima_val'], $parametros_parcela);
        } else {
            $parcelas = ftr_geral::getParcelamentoPadrao($total, $sub_total, $parametros_parcelamento);
        }

        if (count($parcelas) > 0) {
            if ($html) {
                $this->data['Type_CalculoParcelamento'] = $this->load->typeForTwig('Type_CalculoParcelamento');
                $this->data['parcela_minima'] = ($parametros_parcelamento['parcela_minima_val']) ? $this->currency->format($parametros_parcelamento['parcela_minima_val']) : false;

                if ($this->config->get($module . '_config_parcelamento') == Type_ConfigParcelamento::Padrao) {
                    $this->data['juros'] = $parametros_parcelamento['juros'];
                    $this->data['desconto'] = $parametros_parcelamento['desconto'];
                }

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

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

                $this->response->setOutput($this->render());
            } else {
                return $parcelas;
            }
        } else {
            $error = '<span class="visible-block top-margin-medium">Não é possível finalizar a compra, nenhuma parcela atingiu o valor mínimo ('
                . $this->currency->format($pminima) . ' considerando os descontos) </span>';
            $this->response->setOutput($error);
        }
    }
}
