<?php
class ControllerCheckoutPaymentMethod extends Controller
{
    public function index()
    {
        $this->language->load('checkout/checkout');
        $this->load->model('account/address');
        $this->load->type('tipocomum');

        if ($this->customer->isLogged() && isset($this->session->data['payment_address_id'])) {
            $payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
        } elseif (isset($this->session->data['guest'])) {
            $payment_address = $this->session->data['guest']['payment'];
        }

        if (!empty($payment_address)) {
            // Totals
            $total_data = array();
            $total = 0;

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

            $sort_order = array();

            $results = $this->model_setting_extension->getExtensions('total');

            foreach ($results as $key => $value) {
                $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
            }

            array_multisort($sort_order, SORT_ASC, $results);

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('total/' . $result['code']);

                    $this->{'model_total_' . $result['code']}->getTotal($total_data, $total);
                }
            }

            // Payment Methods
            $method_data = array();

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

            $results = $this->model_setting_extension->getExtensions('payment');
            $cart_has_recurring = $this->cart->hasRecurringProducts();
            $shipping_methods = $this->config->get('cod_shipping_methods') ?? [];
            $shipping = $this->session->data['shipping_method']['code'];
            $shipping = preg_replace('/\..*/', '', $shipping);

            foreach ($results as $result) {
                if ($result['code'] == 'cod' && !in_array($shipping, $shipping_methods)) {
                    continue;
                }

                if ($result['code'] == 'matera') {
                    $this->config->set('matera_status', 0);
                }

                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('payment/' . $result['code']);

                    $method = $this->{'model_payment_' . $result['code']}->getMethod($payment_address, $total);

                    if ($method) {
                        if ($cart_has_recurring > 0) {
                            if (method_exists($this->{'model_payment_' . $result['code']}, 'recurringPayments')) {
                                if ($this->{'model_payment_' . $result['code']}->recurringPayments() == true) {
                                    $method_data[$result['code']] = $method;
                                }
                            }
                        } else {
                            $method_data[$result['code']] = $method;
                        }
                    }
                }
            }

            $sort_order = array();

            foreach ($method_data as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }

            array_multisort($sort_order, SORT_ASC, $method_data);

            $this->session->data['payment_methods'] = $method_data;
        }

        $this->data['text_payment_method']            = $this->language->get('text_payment_method');
        $this->data['text_comments']                  = $this->language->get('text_comments');
        $this->data['button_continue']                = $this->language->get('button_continue');
        $this->data['text_feedback_order_status']     = $this->language->get('text_feedback_order_status');
        $this->data['text_whatsapp_number']           = $this->language->get('text_whatsapp_number');
        $this->data['text_checkout_payment_method']   = $this->language->get('text_checkout_payment_method');

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

        $this->data['feedback_order_status'] = $this->feedback->isEnabled();
        $this->data['customer_celular'] = (trim($this->customer->getCelular()) != '') ? $this->customer->getCelular() : $this->customer->getFeedbackWhatsappNumber();

        $this->document->addScriptApp(array(
            'public/js/page.payment_method.js',
        ));

        $this->data['scriptsApp'] = json_encode($this->document->getScriptsApp());

        if (empty($this->session->data['payment_methods'])) {
            $this->data['error_warning'] = sprintf($this->language->get('error_no_payment'), $this->url->link('information/contact'));
        } else {
            $this->data['error_warning'] = '';
        }

        if (isset($this->session->data['payment_method']['code'])) {
            $this->data['code'] = $this->session->data['payment_method']['code'];
        } else {
            $this->data['code'] = '';
        }

        if (isset($this->session->data['payment_method']['code_type'])) {
            $this->data['code_type'] = $this->session->data['payment_method']['code_type'];
        } else {
            $this->data['code_type'] = '';
        }

        if (isset($this->session->data['payment_methods']) && !empty($this->session->data['payment_methods'])) {
            if (!empty($this->data['code'])
                && !empty($this->data['code_type']) && (array_key_exists($this->data['code'], $this->session->data['payment_methods']))
                && (array_key_exists($this->data['code_type'], $this->session->data['payment_methods'][$this->data['code']]['quote']))) {
                $this->session->data['payment_methods'][$this->data['code']]['quote'][$this->data['code_type']] = array_merge($this->session->data['payment_methods'][$this->data['code']]['quote'][$this->data['code_type']],  ['selected' => true]);
            } else if (!empty($this->data['code']) && (array_key_exists($this->data['code'], $this->session->data['payment_methods']))) {
                $this->session->data['payment_methods'][$this->data['code']] = array_merge($this->session->data['payment_methods'][$this->data['code']], ['selected' => true]);
            } else {
                if (isset(current($this->session->data['payment_methods'])['quote']) && (!empty(current($this->session->data['payment_methods'])['quote']))) {
                    $code = current(array_keys($this->session->data['payment_methods']));
                    $code_type = current(array_keys($this->session->data['payment_methods'][$code]['quote']));
                    $this->session->data['payment_methods'][$code]['quote'][$code_type] = array_merge($this->session->data['payment_methods'][$code]['quote'][$code_type], ['selected' => true]);
                } else {
                    $code = current(array_keys($this->session->data['payment_methods']));
                    $this->session->data['payment_methods'][$code] = array_merge($this->session->data['payment_methods'][$code], ['selected' => true]);
                };
            }

            $this->data['payment_methods'] = $this->session->data['payment_methods'];
        } else {
            $this->data['payment_methods'] = array();
        }


        if (isset($this->session->data['comment'])) {
            $this->data['comment'] = $this->session->data['comment'];
        } else {
            $this->data['comment'] = '';
        }

        if ($this->config->get('config_checkout_id')) {

            $this->load->model('catalog/information');

            $information_info = $this->model_catalog_information->getInformation($this->config->get('config_checkout_id'));
            if ($information_info) {

                $this->data['text_agree'] = sprintf(
                    $this->language->get('text_agree'), 
                    $this->url->link('information/information', 'information_id=' . $this->config->get('config_checkout_id'), 'SSL'), 
                    $information_info['title'], 
                    $information_info['title']
                );

                $this->data['agree_title'] = $information_info['title'];
                $this->data['agree_link'] = $this->url->link('information/information', 'information_id=' . $this->config->get('config_checkout_id'), 'SSL');

            } else {

                $this->data['text_agree'] = '';
            }
            
        } else {

            $this->data['text_agree'] = '';
        }

        if (isset($this->session->data['agree'])) {
            $this->data['agree'] = $this->session->data['agree'];
        } else {
            $this->data['agree'] = '';
        }

        $this->data['wg24_seo_fer_facebook_status'] = $this->config->get('wg24_seo_fer_facebook_status');
        $this->data['wg24_seo_fer_facebook_pixel'] = $this->config->get('wg24_seo_fer_facebook_pixel');

        $this->response->setOutput($this->render('checkout/payment_method'));
    }

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

        $json = array();

        // Validate if payment address has been set.
        $this->load->model('account/address');

        if ($this->customer->isLogged() && isset($this->session->data['payment_address_id'])) {
            $payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
        } elseif (isset($this->session->data['guest'])) {
            $payment_address = $this->session->data['guest']['payment'];
        }

        if (empty($payment_address)) {
            $json['redirect'] = $this->url->link('checkout/checkout', '', 'SSL');
        }

        // Validate cart has products and has stock.
        if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
            $json['redirect'] = $this->url->link('checkout/cart');
        }

        // Validate minimum quantity requirments.
        $products = $this->cart->getProducts();

        foreach ($products as $product) {
            $product_total = 0;

            foreach ($products as $product_2) {
                if ($product_2['product_id'] == $product['product_id']) {
                    $product_total += $product_2['quantity'];
                }
            }

            if ($product['minimum'] > $product_total) {
                $json['redirect'] = $this->url->link('checkout/cart');

                break;
            }
        }

        if (!$json) {
            if (isset($this->request->post['payment_method']) && ($this->request->post['payment_method'] == 'pp_express')) {
                $this->load->controller('payment/pp_express');
                $paypal = new ControllerPaymentPPExpress($this->registry);
                $retorno = $paypal->validainfo();
                if ($retorno != 'success') {
                    $json['error']['payment'] = $retorno;
                }
            }

            if (isset($this->request->post['feedback_order']) && ($this->request->post['feedback_order_whatsapp'] == '')) {
                $json['error']['warning'] = $this->language->get('error_feedback_order');
            }

            if (!isset($this->request->post['payment_method'])) {
                $json['error']['warning'] = $this->language->get('error_payment');
            } elseif (!isset($this->session->data['payment_methods'][$this->request->post['payment_method']])) {
                $json['error']['warning'] = $this->language->get('error_payment');
            }

            if ($this->config->get('config_checkout_id')) {
                $this->load->model('catalog/information');

                $information_info = $this->model_catalog_information->getInformation($this->config->get('config_checkout_id'));
                
                if ($information_info && !isset($this->request->post['agree'])) {
                    $json['error']['warning'] = sprintf(
                        $this->language->get('error_agree'), 
                        $this->url->link('information/information', 'information_id=' . $this->config->get('config_checkout_id'), 'SSL'), 
                        $information_info['title'], 
                        $information_info['title']
                    );    
                }
            }

            if (!$json) {
                if (isset($this->request->post['payment_method_type'])) {
                    $this->session->data['payment_method'] = $this->session->data['payment_methods'][$this->request->post['payment_method']]['quote'][$this->request->post['payment_method_type']];
                } else {
                    $this->session->data['payment_method'] = $this->session->data['payment_methods'][$this->request->post['payment_method']];
                }

                if (isset($this->request->post['feedback_order']) && $this->request->post['feedback_order'] == Type_Status::Tp_Habilitado && $this->request->post['feedback_order_whatsapp'] != '') {
                    $this->session->data['feedback_order'] = Type_Status::Tp_Habilitado;
                    $this->session->data['feedback_order_whatsapp'] = $this->request->post['feedback_order_whatsapp'];
                } else {
                    $this->session->data['feedback_order'] = Type_Status::Tp_Desabilitado;
                    $this->session->data['feedback_order_whatsapp'] = '';
                }

                $this->session->data['comment'] = strip_tags($this->request->post['comment']);
            }
        }

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