<?php
class DModelSettingSetting extends Model
{
    public function getSetting($group, $store_id = 0)
    {
        $data = array();

        $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `group` = '" . $this->db->escape($group) . "'");

        foreach ($query->rows as $result) {
            switch ($result['serialized']) {
                case Type_SettingValue::Tp_Serialized:
                    $data[$result['key']] = unserialize($result['value']);
                    break;
                case Type_SettingValue::Tp_Json:
                    $data[$result['key']] = json_decode($result['value'], true);
                    break;
                default:
                    $data[$result['key']] = $result['value'];
            }
        }

        return $data;
    }

    public function editSetting($group, $data, $store_id = 0, $arrayJson = array())
    {

        $this->db->startTransaction();
        try {
            $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `group` = '" . $this->db->escape($group) . "'");

            foreach ($data as $key => $value) {

                if (!is_array($value)) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "', serialized = '" . Type_SettingValue::Tp_Text . "'");
                } else {

                    if (in_array($key, $arrayJson)) {
                        $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value)) . "', serialized = '" . Type_SettingValue::Tp_Json . "'");
                    } else if ($key == 'processo_venda') {
                        $this->load->type('tipocomum');
                        $this->db->query("Delete from " . DB_PREFIX . "proccess_to_status");
                        //Salvando ao processos de venda
                        foreach ($value as $key_process =>  $process) {
                            foreach ($process as $process_tipo =>  $process_ids) {
                                foreach ($process_ids as $key_process_id =>  $process_id) {
                                    $prioridade = ($key_process_id == Type_ProcessoVendaStatusPrior::TpPrVnStPrincipal) ? Type_ProcessoVendaStatusPrior::TpPrVnStPrincipal : Type_ProcessoVendaStatusPrior::TpPrVnStSecundario;
                                    $this->db->query(
                                        "INSERT INTO " . DB_PREFIX . "proccess_to_status
                                SET proccess_control_item_id = '" . (int)$key_process . "',
                                order_status_id = '" . (int)$process_id .  "',
                                tipo_status = '" . (int)$process_tipo .  "',
                                tipo_status_prioridade = '" . $prioridade . "'"
                                    );
                                }
                            }
                        }
                    } else {
                        $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(serialize($value)) . "', serialized = '" . Type_SettingValue::Tp_Serialized . "'");
                    }
                }
            }
            //função criada para salvar o titulo dos modulos de pagamento, envio e modulos normais
            //sempre que ele for salvo - by Dionis Mendanha 18/07/2017
            $this->InsertTitleSetting($group);
            $this->db->commit();
        } catch (Exception $e) {
            $this->db->rollback();
        }
    }

    public function editSettingForKey($group, $data, $store_id = 0)
    {
        foreach ($data as $key => $value) {
            if (!is_array($value)) {
                $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `key` = '" . $this->db->escape($key) . "'");

                $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
            } else {
                $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `key` = '" . $this->db->escape($key) . "'");

                $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(serialize($value)) . "', serialized = '1'");
            }
        }
    }

    public function deleteSetting($group, $store_id = 0)
    {
        $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `group` = '" . $this->db->escape($group) . "'");
    }

    public function editSettingValue($group = '', $key = '', $value = '', $store_id = 0)
    {
        if (!is_array($value)) {
            $this->db->query("UPDATE " . DB_PREFIX . "setting SET `value` = '" . $this->db->escape($value) . "' WHERE `group` = '" . $this->db->escape($group) . "' AND `key` = '" . $this->db->escape($key) . "' AND store_id = '" . (int)$store_id . "'");
        } else {
            $this->db->query("UPDATE " . DB_PREFIX . "setting SET `value` = '" . $this->db->escape(serialize($value)) . "' WHERE `group` = '" . $this->db->escape($group) . "' AND `key` = '" . $this->db->escape($key) . "' AND store_id = '" . (int)$store_id . "'");
        }
    }

    public function insertSettingValue($group = '', $key = '', $value = '', $store_id = 0, $arrayJson = array())
    {
      if (!is_array($value)) {
        $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
      } else {
        if (in_array($key, $arrayJson)) {
          $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(json_encode($value)) . "', serialized = '" . Type_SettingValue::Tp_Json . "'");
        }else{
          $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(serialize($value)) . "', serialized = '1'");
        }
      }
    }

    public function deleteSettingValue($group, $key, $store_id = 0)
    {
        $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE `group` = '" . $this->db->escape($group) . "' AND `key` = '" . $this->db->escape($key) . "' AND store_id = '" . (int)$store_id . "'");
    }

    public function editSettingModuloFutura($group, $data, $store_id = 0)
    {

        $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE store_id = '" . (int)$store_id . "' AND `group` = '" . $this->db->escape($group) . "'");

        foreach ($data as $key => $value) {
            if (!is_array($value)) {
                $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(htmlspecialchars_decode($value)) . "'");
            } else {
                $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET store_id = '" . (int)$store_id . "', `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape(serialize(htmlspecialchars_decode($value))) . "', serialized = '1'");
            }
        }

        //função criada para salvar o titulo dos modulos de pagamento, envio e modulos normais
        //sempre que ele for salvo - by Dionis Mendanha 18/07/2017
        $this->InsertTitleSetting($group);
    }

    public function InsertTitleSetting($group)
    {

        $arrayTypes = array('module', 'payment', 'shipping');
        $directory = $this->language->getDirectory();

        foreach ($arrayTypes as $key => $value) {
            $path = DIR_LANGUAGE . $directory . '/' . $value . '/' . $group . '.php';
            $file = $value . '/' . $group;
            if (file_exists($path)) {
                $this->load->language($file);
                $this->insertSettingValue($group, $group . '_titlefutura', strip_tags($this->language->get('heading_title')));
            }
        }
    }

    public function AlterSettingsforSerialize($group)
    {

        $query = $this->db->query("SELECT setting_id FROM " . DB_PREFIX . "setting WHERE  `group` = '" . $this->db->escape($group) . "' and `key` = '" . $group . "_module' ");

        if (!$query->rows) {

            $this->load->helper('ftr_geral');

            $arrayQuery = array();

            $query = $this->db->query("SELECT `key`, value FROM " . DB_PREFIX . "setting WHERE  `group` = '" . $this->db->escape($group) . "'");

            foreach ($query->rows as $key => $value) {
                $arrayQuery[0][$value['key']] = $value['value'];
            }

            $this->insertSettingValue($group, $group . '_module', $arrayQuery);

            $this->config->set($group . '_module', $arrayQuery);
        }
    }

    public function getSalesByPayment($payment)
    {

        $sql = "SELECT COUNT(o.order_id) AS total FROM oc_order o WHERE o.payment_code = '" . $payment . "'";
        $query = $this->db->query($sql);
        return $query->row['total'];
    }
}