<?php
class ModelPaymentCieloApiPix extends Model
{
    public function getMethod($address, $total)
    {
        $this->load->language('payment/cielo_api_pix');

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE geo_zone_id = '" . (int)$this->config->get('cielo_api_pix_geo_zone_id') . "' AND country_id = '" . (int)$address['country_id'] . "' AND (zone_id = '" . (int)$address['zone_id'] . "' OR zone_id = '0')");

        if (((float)$this->config->get('cielo_api_pix_total') > 0 && (float)$this->config->get('cielo_api_pix_total') > $total) ||
            ((float)$this->config->get('cielo_api_pix_parcela_minimo') > 0 && (float)$this->config->get('cielo_api_pix_parcela_minimo') > $total)
        ) {
            $status = false;
        } elseif (!$this->config->get('cielo_api_pix_geo_zone_id')) {
            $status = true;
        } elseif ($query->num_rows) {
            $status = true;
        } else {
            $status = false;
        }

        if (ftr_geral::isIsset($this->config->get('cielo_api_pix_display')) && (!$this->ftrgeralregistry->exibeMuduloLayout($this->config->get('cielo_api_pix_display')))) {
            $status = false;
        }

        $method_data = array();

        if ($status) {
            $quote_data[Type_PaymentOption::Tp_Pix] = array(
                'code'       => 'cielo_api_pix',
                'code_type'  => Type_PaymentOption::Tp_Pix,
                'title'      => ($this->config->get('cielo_api_pix_descricao')) ? $this->config->get('cielo_api_pix_descricao') : $this->language->get('text_title'),
                'sort_order' => $this->config->get('cielo_api_pix_sort_order')
            );

            $method_data = array(
                'code'       => 'cielo_api_pix',
                'quote'      => $quote_data,
                'title'      => ($this->config->get('cielo_api_pix_descricao')) ? $this->config->get('cielo_api_pix_descricao') : $this->language->get('text_title'),
                'terms'      => '',
                'sort_order' => $this->config->get('cielo_api_pix_sort_order')
            );
        }

        if (ftr_geral::isIsset($this->config->get('cielo_api_pix_client_teste')) && (strlen($this->config->get('cielo_api_pix_client_teste')) > 0)) {
            if ($this->customer->getId() == $this->config->get('cielo_api_pix_client_teste')) {
                return $method_data;
            }
        } else {
            return $method_data;
        }
    }

    public function getStatusPayment($status): bool {
        return match ($status) {
            $this->config->get('cielo_api_pix_order_status_approved') => true,
            default => false,
        };
    }

    public function getLastQueryPixStatus($codigo_integracao) {
        $query = $this->db->query("SELECT * FROM oc_payment_pix WHERE payment_id = '$codigo_integracao' LIMIT 1");
        
        if ($query->num_rows) {
        return $query->row;
        }
        
        return false;
    }

    public function getOrderIdByIntegracao($codigo_integracao){
        $query = $this->db->query("SELECT order_id FROM oc_order WHERE codigo_integracao_pagamento = '$codigo_integracao'")->row;
    
        return (int)$query['order_id'] ?? false;
    }

    public function setStatusOrder($order_id, $status_id, $return = false){

        $this->load->dmodel('checkout/order');

        switch ($status_id) {
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Open):
                $order_status_id = $this->config->get('cielo_api_pix_order_status_open');
                break;
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Created):
                $order_status_id = $this->config->get('cielo_api_pix_order_status_created');
                break;
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Approved):
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Authorized):
                $order_status_id = $this->config->get('cielo_api_pix_order_status_approved');
                break;
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Rejected):
                $order_status_id = $this->config->get('cielo_api_pix_order_status_rejected');
                break;
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Canceled):
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Canceling):
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Expired):
                $order_status_id = $this->config->get('cielo_api_pix_order_status_canceled');
                break;
            case mb_strtoupper(Type_CieloApiPixPaymentStatus::Tp_Error):
                $order_status_id = $this->config->get('cielo_api_pix_order_status_error');
                break;  
            default:
                $order_status_id = $this->config->get('cielo_api_pix_order_status_open');
        }
        
        if ($return) {
            return $order_status_id;
        }
        $this->load->dmodel('checkout/order');
        $this->dmodel_checkout_order->update($order_id, $order_status_id, '', true);
    }

    public function setPaymentPix($id, $data){

        $data->Payment->Status = $this->setStatusOrder($id, $data->Payment->Status, true);

        $sql = "UPDATE `oc_order` SET `codigo_integracao_pagamento` = '" . ($data->Payment->PaymentId ?? $data->Payment->Tid) . "'
                WHERE `order_id` = $id";

        $this->db->query($sql);

        // Verifica se já existe um registro para o order_id, caso contrário, insere um novo registro para o caso de ter gerado o pedido, mas não o qrcode
        $sql = "SELECT * FROM `oc_payment_pix` WHERE `order_id` = '" . $id . "'";
        $query = $this->db->query($sql);
        if (!$query->num_rows) {
            $sql = "INSERT INTO `oc_payment_pix` (`order_id`) VALUES ('" . $id . "')";
            $this->db->query($sql);
        }

        $sql = "UPDATE `oc_payment_pix` SET `payment_id`       = '" . ($data->Payment->PaymentId ?? $data->Payment->Tid) . "',
                                            `data_criacao`     = '" . date('Y-m-d H:i:s', strtotime($data->Payment->ReceivedDate ?? date('Y-m-d H:i:s'))) . "',
                                            `data_vencimento`  = '" . (date('Y-m-d H:i:s', strtotime('+' . ($data->Payment->QrCode->Expiration ?? 8600) . ' seconds'))) . "',
                                            `status_pagamento` = " . $data->Payment->Status . ",
                                            `link_qrcodeurl`   = '" . $data->Payment->QrCodeBase64Image . "',
                                            `link_qrcode`      = '" . $data->Payment->QrCodeString . "' WHERE `order_id` = '" . $id . "'";

        $query = $this->db->query($sql);
        return $query;
    }
}
