<?php
class ModelModuleLogo extends Model {
    public function getOrder($order_id) {
        $order_query = $this->db->query("SELECT *, (SELECT os.name FROM ps_order_status os WHERE os.order_status_id = o.order_status_id AND os.language_id = o.language_id) AS order_status FROM ps_order o WHERE o.order_id = '" . (int) $order_id . "'");

        if ($order_query->num_rows) {
            $country_query = $this->db->query("SELECT * FROM ps_country WHERE country_id = '" . (int) $order_query->row['payment_country_id'] . "'");
            if ($country_query->num_rows) {
                $payment_iso_code_2 = $country_query->row['iso_code_2'];
                $payment_iso_code_3 = $country_query->row['iso_code_3'];
            } else {
                $payment_iso_code_2 = '';
                $payment_iso_code_3 = '';
            }

            $zone_query = $this->db->query("SELECT * FROM ps_zone WHERE zone_id = '" . (int) $order_query->row['payment_zone_id'] . "'");

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

            $country_query = $this->db->query("SELECT * FROM ps_country WHERE country_id = '" . (int) $order_query->row['shipping_country_id'] . "'");

            if ($country_query->num_rows) {
                $shipping_iso_code_2 = $country_query->row['iso_code_2'];
                $shipping_iso_code_3 = $country_query->row['iso_code_3'];
            } else {
                $shipping_iso_code_2 = '';
                $shipping_iso_code_3 = '';
            }

            $zone_query = $this->db->query("SELECT * FROM ps_zone WHERE zone_id = '" . (int) $order_query->row['shipping_zone_id'] . "'");

            if ($zone_query->num_rows) {
                $shipping_zone_code = $zone_query->row['code'];
            } else {
                $shipping_zone_code = '';
            }
            $this->load->model('localisation/language');

            $language_info = $this->model_localisation_language->getLanguage($order_query->row['language_id']);

            if ($language_info) {
                $language_code = $language_info['code'];
            } else {
                $language_code = $this->config->get('config_language');
            }

            return array(
                'order_id' => $order_query->row['order_id'],
                'invoice_no' => $order_query->row['invoice_no'],
                'invoice_prefix' => $order_query->row['invoice_prefix'],
                'store_id' => $order_query->row['store_id'],
                'store_name' => $order_query->row['store_name'],
                'store_url' => $order_query->row['store_url'],
                'customer_id' => $order_query->row['customer_id'],
                'firstname' => $order_query->row['firstname'],
                'lastname' => $order_query->row['lastname'],
                'tc' => $order_query->row['tc'],
                'email' => $order_query->row['email'],
                'telephone' => $order_query->row['telephone'],
                'fax' => $order_query->row['fax'],
                'custom_field' => json_decode($order_query->row['custom_field'], true),
                'payment_firstname' => $order_query->row['payment_firstname'],
                'payment_lastname' => $order_query->row['payment_lastname'],
                'payment_company' => $order_query->row['payment_company'],
                'payment_address_1' => $order_query->row['payment_address_1'],
                'payment_address_2' => $order_query->row['payment_address_2'],
                'payment_postcode' => $order_query->row['payment_postcode'],
                'payment_city' => $order_query->row['payment_city'],
                'payment_zone_id' => $order_query->row['payment_zone_id'],
                'payment_zone' => $order_query->row['payment_zone'],
                'payment_zone_code' => $payment_zone_code,
                'payment_country_id' => $order_query->row['payment_country_id'],
                'payment_country' => $order_query->row['payment_country'],
                'payment_company_taxno' => $order_query->row['payment_company_taxno'],
                'payment_company_taxadmin' => $order_query->row['payment_company_taxadmin'],
                'payment_iso_code_2' => $payment_iso_code_2,
                'payment_iso_code_3' => $payment_iso_code_3,
                'payment_address_format' => $order_query->row['payment_address_format'],
                'payment_custom_field' => json_decode($order_query->row['payment_custom_field'], true),
                'payment_method' => $order_query->row['payment_method'],
                'payment_code' => $order_query->row['payment_code'],
                'shipping_firstname' => $order_query->row['shipping_firstname'],
                'shipping_lastname' => $order_query->row['shipping_lastname'],
                'shipping_company' => $order_query->row['shipping_company'],
                'shipping_address_1' => $order_query->row['shipping_address_1'],
                'shipping_address_2' => $order_query->row['shipping_address_2'],
                'shipping_postcode' => $order_query->row['shipping_postcode'],
                'shipping_city' => $order_query->row['shipping_city'],
                'shipping_zone_id' => $order_query->row['shipping_zone_id'],
                'shipping_zone' => $order_query->row['shipping_zone'],
                'shipping_zone_code' => $shipping_zone_code,
                'shipping_country_id' => $order_query->row['shipping_country_id'],
                'shipping_country' => $order_query->row['shipping_country'],
                'shipping_iso_code_2' => $shipping_iso_code_2,
                'shipping_iso_code_3' => $shipping_iso_code_3,
                'shipping_address_format' => $order_query->row['shipping_address_format'],
                'shipping_custom_field' => json_decode($order_query->row['shipping_custom_field'], true),
                'shipping_method' => $order_query->row['shipping_method'],
                'shipping_code' => $order_query->row['shipping_code'],
                'comment' => $order_query->row['comment'],
                'total' => $order_query->row['total'],
                'order_status_id' => $order_query->row['order_status_id'],
                'order_status' => $order_query->row['order_status'],
                'affiliate_id' => $order_query->row['affiliate_id'],
                'commission' => $order_query->row['commission'],
                'language_id' => $order_query->row['language_id'],
                'language_code' => $language_code,
                'currency_id' => $order_query->row['currency_id'],
                'currency_code' => $order_query->row['currency_code'],
                'currency_value' => $order_query->row['currency_value'],
                'ip' => $order_query->row['ip'],
                'forwarded_ip' => $order_query->row['forwarded_ip'],
                'user_agent' => $order_query->row['user_agent'],
                'accept_language' => $order_query->row['accept_language'],
                'date_added' => $order_query->row['date_added'],
                'date_modified' => $order_query->row['date_modified'],
                'logo_reference' => $order_query->row['logo_reference'],
                'logo_message' => $order_query->row['logo_message'],
                'logo_is_cancelled' => $order_query->row['logo_is_cancelled'],
                'logo_customer_code' => $order_query->row['logo_customer_code']
            );
        } else {
            return false;
        }
    }

    public function getOrderShipmentDate($order_id) {
        $date = $this->db->query("SELECT
            oh.order_id, 
            oh.order_status_id, 
            oh.date_added
            FROM " . DB_PREFIX . "order_history oh 
            WHERE
                oh.order_status_id = 17 AND
                oh.order_id = " . $order_id 
            )->row;

        if(!empty($date)) {
            return $date['date_added'];
        } else {
            return false;
        }
    }

    public function getOrderProducts($order_id) {
        $query = $this->db->query("
            SELECT
                op.*,
                ps.barcode, 
                ps.product_stock_id,
                ps.`name` AS material_name,
                ps.logo_reference, 
                ps.logo_code, 
                ps.logo_message
            FROM " . DB_PREFIX ."order_product AS op
            INNER JOIN " . DB_PREFIX ."product AS p ON op.product_id = p.product_id 
            LEFT JOIN " . DB_PREFIX ."product_stock AS ps ON p.product_stock_id = ps.product_stock_id 
            WHERE op.order_id = " . (int)$order_id  . "
        ");

		return $query->rows;
	}

    public function getOrderProductsIds($order_id) {
        $query = $this->db->query("SELECT order_product_id
            FROM " . DB_PREFIX ."order_product 
            WHERE order_id = " . (int)$order_id
        );
        return $query->rows;
    }

    public function getOrderProduct($order_product_id) {
        $query = $this->db->query("
                SELECT
                op.*,
                ps.barcode, 
                ps.product_stock_id,
                ps.`name` AS material_name,
                ps.logo_reference, 
                ps.logo_code, 
                ps.logo_message
            FROM 
                " . DB_PREFIX ."order_product AS op
                LEFT JOIN
                " . DB_PREFIX ."product AS p
                ON 
                    op.product_id = p.product_id
                LEFT JOIN
                " . DB_PREFIX ."product_stock AS ps
                ON  
                    p.product_stock_id = ps.product_stock_id
            WHERE op.order_product_id = " . (int)$order_product_id
        );

        return $query->row;
    }
	public function updateCustomerLogoData($customer_id, $data) {
        if(!empty($customer_id) && $customer_id!==0) {
            $this->db->query("UPDATE " . DB_PREFIX ."customer
                SET logo_reference = '" . $data['INTERNAL_REFERENCE'] . "',
                logo_code = '" . $data['CODE'] . "'
                WHERE customer_id=" . $customer_id
            );            
        }
    }

    public function updateOrderLogoReference($order_id, $data) {
        $this->db->query("UPDATE " . DB_PREFIX ."order
            SET logo_reference = '" . $data['INTERNAL_REFERENCE'] . "',
            logo_customer_code = '" . $data['ARP_CODE'] ."',
            logo_message = NULL
            WHERE order_id =" . $order_id
        );
    }

    public function updateOrderLogoMessage($order_id, $message) {
        $this->db->query("UPDATE " . DB_PREFIX ."order
            SET logo_message = '" . $message . "'  
            WHERE order_id = '" . (int)$order_id ."'"
        );  
    }
    public function updateOrderLogoCancelStatus($order_id, $status = NULL) {
        $sql = "UPDATE " . DB_PREFIX ."order
            SET logo_is_cancelled = ";
        $sql .= $status == null ? 'NULL' : $status;
        $sql .= " WHERE order_id = '" . (int)$order_id ."'";

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

    public function saveMaterial($product_stock_id, $data) {
        $this->db->query("UPDATE " . DB_PREFIX . "product_stock 
            SET logo_reference = '" . $data['INTERNAL_REFERENCE'] . "', 
            logo_code = '" . $data['CODE'] . "' 
            WHERE product_stock_id = " . $product_stock_id
        );
    }    
    public function saveMaterialToProduct($product_id, $product_stock_id, $barcode) {
        $this->db->query("UPDATE " . DB_PREFIX . "product 
            SET product_stock_id = '" . $product_stock_id . "', 
            barcode = '" . $barcode . "' 
            WHERE product_id = " . $product_id
        );
    }

    public function getOrderTotals($order_id){
        $result = [
            "tax_amount" => 0,
            "total_amount" => 0,
            "sub_total_amount" => 0,
            "shipping_amount" => 0,
            "coupon" => 0,
            "total_campaign" => 0,
            "iyzico_checkout_form_fee" => 0,
            "reward" => 0,
            "extra_discount" => 0,
        ];

        $order_totals = $this->db->query("SELECT * FROM " . DB_PREFIX . "order_total 
            WHERE order_id = '" . (int)$order_id . "'"
        )->rows; 

        foreach ($order_totals as $total) {
            switch ($total['code']) {
                case 'tax':
                $result['tax_amount'] = str_replace(",",".",$total['value']);
                break;
                case 'total':
                $result['total_amount'] = str_replace(",",".",$total['value']);
                break;
                case 'sub_total':
                $result['sub_total_amount'] = str_replace(",",".",$total['value']);
                break;                   
                case 'shipping':
                $result['shipping_amount'] = str_replace(",",".",$total['value']);   
                break;                        
                case 'campaign_price_total':
                $result['total_campaign'] = str_replace(",",".",$total['value']);     
                break;           
                case 'iyzico_checkout_form_fee':
                $result['iyzico_checkout_form_fee'] = str_replace(",",".",$total['value']);
                break;
                case 'coupon':
                $result['coupon'] = abs(str_replace(",",".",$total['value']));                  
                break;
                case 'reward':
                $result['reward'] = abs(str_replace(",",".",$total['value']));                  
                case 'extra_discount':
                $result['extra_discount'] = abs(str_replace(",",".",$total['value']));  
                break;
            }            
        }

        return $result;
    }

    public function getUnReferencedMaterials() {
        $query = $this->db->query("SELECT product_stock_id, barcode, name FROM " . DB_PREFIX ."product_stock 
            WHERE logo_reference IS NULL" 
        )->rows;

        return $query;
    }

    public function getMaterial($product_stock_id) {
        $material = $this->db->query("SELECT ps_product_stock.* 
            FROM ps_product_stock
            WHERE product_stock_id = '"  . (int)$product_stock_id . "'"
        )->row;

        return $material;
    }

    /**
     * order_return.php dosyası içinde çağrılır. Müşteri iade formunu doldurduktan sonra iadeler Logo'ya aktarılır.
     */
    public function returnOrder($product_ids, $post_data = []) {
        $order_products = $this->db->query("SELECT op.*, o.customer_id, o.campaign, CONCAT( o.firstname, ' ', o.lastname ) AS customer_name, ps.logo_code
            FROM ps_order_product AS op
            LEFT JOIN ps_order AS o ON op.order_id = o.order_id
            LEFT JOIN ps_product AS p ON op.product_id = p.product_id
            LEFT JOIN ps_product_stock AS ps ON p.product_stock_id = ps.product_stock_id
            WHERE op.order_product_id IN ( ".  $product_ids .")"
        )->rows;
 
        $amount = 0;
        foreach($order_products as $product) {

            if(empty($product['logo_return_info'])){
                if(!empty($product['campaign']) && strpos($product['name'], '(Hediye)')) {
                    $amount = 0;
                } else {
                    $amount = $product['total'] + $product['tax'];
                }

                $bank_slip = [];
                if($amount!==0) {
                    $logo_data = [
                        "INTERNAL_REFERENCE" => "~",
                        "DATE" => date('Y-m-d'),
                        "TIME" => 0,
                        "NUMBER" => "~",
                        "DIVISION" => 0,
                        "DEPARTMENT" => 0,
                        "TYPE" => "20",
                        "SIGN" => 1,
                        "TOTAL_CREDIT" => $amount,
                        "CURRSEL_TOTALS" => 1,
                        "TRANSACTIONS" => [
                            "items" =>  [
                                [
                                    "INTERNAL_REFERENCE" => "~",
                                    "TYPE" => "1",
                                    "BANKACC_CODE" => "1     1",
                                    "ARP_CODE" => isset($product['logo_customer_code']) ? $product['logo_customer_code'] : "",
                                    "DATE" => date('Y-m-d'), 
                                    "CUST_TITLE" => $post_data['firstname'] . '' . $post_data['lastname'],
                                    "BN_CRDTYPE" => "1",
                                    "SIGN" => 1,
                                    "TR_CODE" => "20",
                                    "MODULENR" => "7",
                                    "DESCRIPTION" => "Sipariş No: ".$product['order_id'],
                                    "CREDIT" => $amount,
                                    "AMOUNT" => $amount,
                                    "TC_AMOUNT" => $amount,
                                    "AFFECT_RISK" => 0,
                                    "BN_CRDTYPE" => 1,
                                    "DIVISION" => 0
                                ]
                            ]
                        ]
                    ];
    
                    $logo = new Logo;
                    $bank_slip = $logo->postLogo('/api/v1/bankSlips', json_encode($logo_data));
                }

                $material_slip = [];
                # material_slip işlemi, İade edilen ürünlerin stok fazlası fişi ile stoka geri eklenmesi.
                $logo_data = [
                    "INTERNAL_REFERENCE" => "~",
                    "GROUP" => "3",
                    "TYPE" => "50",
                    "DATE" => date('Y-m-d'),
                    "NUMBER" => "~",
                    "TOTAL_DISCOUNTED" => $amount,
                    "TOTAL_GROSS" => $amount,
                    "TOTAL_NET" => $amount,
                    "FOOTNOTE2" => "Sipariş No: ".$product['order_id'],
                    "CURRSEL_TOTALS" => 1,
                    "TRANSACTIONS" => [
                        "items" =>  [
                            [
                                "ITEM_CODE" => $product['logo_code'], 
                                "LINE_TYPE" => "0",
                                "QUANTITY" => "1",
                                "PRICE" => $product['total'] + $product['tax'],
                                "TOTAL" => $product['total'] + $product['tax'],
                                "UNIT_CODE" => "ADET",
                                "VAT_BASE" => $product['total'], #MATRAH
                                "EU_VAT_STATUS" => "4"
                            ]
                        ]                 
                    ]
                ];
                $logo = new Logo;
                $material_slip = $logo->postLogo('/api/v1/itemSlips', json_encode($logo_data));

                $logo_return_info = [
                    "bank_slip" => isset($bank_slip['INTERNAL_REFERENCE']) ? $bank_slip['INTERNAL_REFERENCE'] : "", # Bankadan gider pusulası referans numarası
                    "material_slip" => isset($material_slip['INTERNAL_REFERENCE']) ? $material_slip['INTERNAL_REFERENCE'] : "" # satış fazlası fişi referans numarası
                ];

                $this->db->query("UPDATE " .DB_PREFIX ."order_product 
                    SET logo_return_info =  ('" . json_encode($logo_return_info, true) . "') 
                    WHERE order_product_id = ".  $product['order_product_id']
                );
            }
        }
    }
}

?>