<?php
class ControllerCheckoutSuccess extends Controller {


	public function index() {

        if (!isset($this->session->data['order_id'])) {
            $this->response->redirect($this->url->link('common/home', '', true));
        }


        $log = new Log("order_success_log/".$this->session->data['order_id'] . "_SuccessLog.txt");

        $log->write("-------------");

        #FaceBook Pixel
        $this->facebookcommonutils = new FacebookCommonUtils();
        $log->write("-------------");
        $products = $this->cart->getProducts();
        if (sizeof($products)) {
            // update the product availability on Facebook
            $this->facebookcommonutils->updateProductAvailability($this->registry, $products);
        }
        #FaceBook Pixel
        $log->write("-------------");

		$this->load->language('checkout/success');

        $log->write("-------------");
		$config_conversion_text = '';
		if($this->config->get('config_conversion')){
			$this->load->model('checkout/order');
			
			$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
            $price = str_replace('.', '',$order_info['total']);
            $price = number_format($price, 2,'.', '');
			$config_conversion_text = "<script> gtag('event', 'conversion', { 'send_to': '". $this->config->get('config_conversion') ."', 'value': " . $price . ", 'currency': '".  $order_info['currency_code'] ."', 'transaction_id': '' }); </script>";
			
		}


        // order_total tablosundan shipping bilgisini çekiyoruz

        $shipping_query = $this->db->query("SELECT * FROM ps_order_total WHERE order_id=" . $this->session->data['order_id'] . " AND code='shipping' ");
     
        $order_info_shipping       = $shipping_query->row;
        $order_info_shipping       = $order_info_shipping['value'];
        $tax_query      = $this->db->query("SELECT * FROM ps_order_total WHERE order_id=" . $this->session->data['order_id'] . "  AND code='tax' ");
        if ($tax_query->num_rows) {
            $order_info_tax       = $tax_query->row;
            $order_info_tax       = $order_info_tax['value'];
        } else {
            $order_info_tax = 0;
        }
        $this->load->model('checkout/order');
        $order_info     = $this->model_checkout_order->getOrder($this->session->data['order_id']);
        $ga4_price      = $order_info['total'];
    
 
        $ga4_tax        = round($order_info_tax,2); 
        
        $ga4_shipping   =  round($order_info_shipping,2);

        $ga4_coupon    = (isset($this->session->data['coupon'])) ? $this->session->data['coupon']:'';

        //current currency
        $ga4_currency   =   $order_info['currency_code'];
 
        $this->load->model('catalog/product');
        $items = array();
        foreach ($products as $product){

            $product_info = $this->model_catalog_product->getProduct($product['product_id']);

            // get category breadcrumb
            $category_name = "";
            $category_info = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_to_category WHERE product_id = " . (int)$product['product_id'] . " LIMIT 1")->row;

            if ($category_info) {
                $category_id = $category_info['category_id'];
            
                $category_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "category_description WHERE category_id = " . (int)$category_id . " AND language_id = " . (int)$this->config->get('config_language_id') . " LIMIT 1")->row;
            
                if ($category_query) {
                    $category_name = $category_query['name'];
                  
                }   
            }
             

          
           
            $product_ga4_price = number_format(round($product['price'], 2), 2, '.', '');
 
            $items[] = array(
                'item_id' => $product['product_id'],
                'item_name' => $product['name'],
                'item_brand' => $product_info['manufacturer'],
                'item_category' => "$category_name",
                'item_variant' => $product['model'],
                'price' =>  $product_ga4_price,
                'quantity' => $product['quantity'],
                'item_coupon' => '',
            );

        }

        $ga4_price = number_format(round($ga4_price, 2), 2, '.', '');
        $ga4_shipping = number_format(round($ga4_shipping, 2), 2, '.', '');
        $ga4_tax = number_format(round($ga4_tax, 2), 2, '.', '');
      

        $ga4 = '
        <script>
        gtag("event", "purchase", {
            transaction_id:  "'.$this->session->data['order_id'].'",
            value:  '.$ga4_price.',
           
            tax:   '.$ga4_tax.',
            shipping:  '.$ga4_shipping.',
            currency:  "'. $ga4_currency.'" , 
            coupon: "'.$ga4_coupon.'",
            items: [
                '.json_encode($items).'
            ]
        });

        console.log("GA4 Purchase Event");
        </script>
        
        ';

        $data['ga4'] = $ga4;

        $log->write("-------------");

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

		$order_id = $this->session->data['order_id'];
        $this->session->data['fb_conversion_order_id']=$order_id;

        $log->write("-------------");
		if (isset($this->session->data['order_id'])) {

            $dataLayerArray['event'] = "purchase";
            $dataLayerArray['ecommerce']['purchase']['transaction_id'] = $this->session->data['order_id'];
            $dataLayerArray['ecommerce']['purchase']['affiliation'] = 'www.deercase.com';
            $dataLayerArray['ecommerce']['purchase']['currency'] = 'TRY';
            $dataLayerArray['ecommerce']['purchase']['coupon'] = (isset($this->session->data['coupon'])) ? $this->session->data['coupon']:'';
            $dataLayerArray['ecommerce']['purchase']['shipping'] = 0;

			$this->cart->clear();

            #NetGSM 2020/06/08 BILAL

            $this->load->model('setting/setting');
            $netgsm_ayarlari = $this->model_setting_setting->getSetting('netgsm');

            $this->load->model('account/order');
            $urunler = $this->model_account_order->getOrderProducts($this->session->data['order_id']);
            $urun_adlari     = "";
            $urun_kodlari    = "";
            $urun_adetleri = "";
            //$_price_total = $_tax_total = 0;
            foreach ($urunler as $key => $value) {
                if ($key==0){ $ayrac = ''; }else{ $ayrac = ','; }
                $urun_adlari     .= $ayrac.$value['name'];
                $urun_kodlari    .= $ayrac.$value['model'];
                $urun_adetleri .= $ayrac.$value['quantity'];

                //dataLayer
                $dataLayerArray['ecommerce']['purchase']['items'][] = [
                    'item_name' => $value['name'],
                    'item_id' => $value['product_id'],
                    'price' => number_format($value['price'],2),
                    'item_brand' => $value['name'],
                    'item_category' => $value['name'],
                    'item_variant' => $value['model'],
                    'quantity' => $value['quantity'],
                    'item_coupon' => '',
                ];
                //$_price_total += $value['total'];
                //$_tax_total += $value['tax'];
                $this->model_checkout_order->set_cost_price($value['product_id'], $value['quantity'], $order_id);
            }

            $log->write("-------------");
            //dataLayer
            $orderTotals = $this->db->query("SELECT * FROM ps_order_total WHERE order_id=" . $order_id)->rows;
            foreach ($orderTotals as $orderTotal) {
                if ($orderTotal['code']=='total') {
                    $dataLayerArray['ecommerce']['purchase']['value'] = number_format($orderTotal['value'],2);
                }
                else if ($orderTotal['code']=='tax') {
                    $dataLayerArray['ecommerce']['purchase']['tax'] = number_format($orderTotal['value'],2);
                }
            }
            //$dataLayerArray['ecommerce']['purchase']['value'] = round($_price_total,2);
            //$dataLayerArray['ecommerce']['purchase']['tax'] = round($_tax_total,2);
            $data['dataLayerJson'] = json_encode($dataLayerArray);

            $log->write("-------------");


            if($netgsm_ayarlari['netgsm_status']==1 and isset($netgsm_ayarlari['netgsm_neworder_to_admin_control']) and $netgsm_ayarlari['netgsm_neworder_to_admin_control']==1 and $netgsm_ayarlari['netgsm_neworder_to_admin_text']!=''){
                $mesaj = str_replace(array('[siparis_no]','[urun_adlari]','[urun_kodlari]','[urun_adetleri]'),array($this->session->data['order_id'],$urun_adlari,$urun_kodlari,$urun_adetleri),$netgsm_ayarlari['netgsm_neworder_to_admin_text']);
                $netgsmsms = new Netgsmsms($netgsm_ayarlari['netgsm_user'],$netgsm_ayarlari['netgsm_pass'],$netgsm_ayarlari['netgsm_input_smstitle'],$netgsm_ayarlari['netgsm_turkishChar']);
                $smsgonder = $netgsmsms->sendSMS($netgsm_ayarlari['netgsm_neworder_to_admin_no'],$mesaj);
            }

            if($netgsm_ayarlari['netgsm_status']==1 and isset($netgsm_ayarlari['netgsm_neworder_to_customer_control']) and $netgsm_ayarlari['netgsm_neworder_to_customer_control']==1 and $netgsm_ayarlari['netgsm_neworder_to_customer_text']!=''){
                $this->load->model('account/customer');
                if ($this->customer->isLogged())  {
                    $customer_info = $this->model_account_customer->getCustomer($this->session->data['customer_id']);
                    $telefon = $customer_info['telephone'];
                } else {
                    $telefon = $this->session->data['guest']['telephone'];
                }
                $mesaj = str_replace(array('[siparis_no]','[urun_adlari]','[urun_kodlari]','[urun_adetleri]'),array($this->session->data['order_id'],$urun_adlari,$urun_kodlari,$urun_adetleri),$netgsm_ayarlari['netgsm_neworder_to_customer_text']);
                $netgsmsms = new Netgsmsms($netgsm_ayarlari['netgsm_user'],$netgsm_ayarlari['netgsm_pass'],$netgsm_ayarlari['netgsm_input_smstitle'],1);
                $smsgonder = $netgsmsms->sendSMS($telefon,$mesaj);
            }

            $log->write("-------------");
            #NetGSM 2020/06/08 BILAL
			$this->load->model('account/order');
			$data['order_detail'] =$this->model_account_order->getOrderProducts($order_id);
				$this->load->model('checkout/order');
			$order_info = $this->model_checkout_order->getOrder($order_id);
			
			$order_total = $this->db->query("SELECT * FROM ps_order_total WHERE   order_id=" . $order_id . " AND code='shipping' ")->row;
		
				$data['shipping_cost']=$order_total['value'];
			
			$data['payment_method']=strip_tags($order_info['payment_method']);
			$data['shipping_city']=$order_info['shipping_city'];
				$data['shipping_country']=$order_info['shipping_iso_code_2'];
				$data['shipping_zone']=$order_info['shipping_zone'];
				
			$data['total_amt']=$order_info['total'];
			$this->load->model('catalog/product');
			foreach ($data['order_detail'] as $detail) {
			    
			    $categorti_id_info = $this->model_catalog_product->getCategoryByProductId($detail['product_id']);
                $product_info = $this->model_catalog_product->getProduct($detail['product_id']);
                $color= !empty($product_info['attribute_groups'][1]['attribute'][0]['name']) ? $product_info['attribute_groups'][1]['attribute'][0]['name'] : "";
                $collection= !empty($product_info['attribute_groups'][0]['attribute'][0]['name']) ? $product_info['attribute_groups'][0]['attribute'][0]['name'] : "";
                $p_stock=$product_info['quantity'];
                        
                /*
                $breadcrumb1 = $categorti_id_info[0]['name'];
                $breadcrumb2 = $categorti_id_info[1]['name'];
                $breadcrumb3 = $categorti_id_info[2]['name'];
			    */

                for($i = 1; $i <= 3; $i++) {
                    $breadcrumb = "breadcrumb{$i}";
                    $$breadcrumb = !empty($categorti_id_info[$i]['name']) ? $categorti_id_info[$i]['name'] : "";
                }
			    
			    
			$data['products'][] = array(
                    'product_id' => $product_info['product_id'],
                    'image' => $product_info['image'],
                    'name' => $product_info['name'],
                    'model' => $product_info['model'],
                    'quantity' => $detail['quantity'],
                    'stock' => $product_info['quantity'],
                    'price' => str_replace(',','.',$detail['price']),
                    'p_price'=>str_replace(',','.',str_replace('₺','',$product_info['price'])),
                    'total' => $detail['total'],
                    'href' => $this->url->link('product/product', 'product_id=' . $product_info['product_id']),
                    'currency'=>$this->session->data['currency'],
                    'breadcrumb1'=>$breadcrumb1,
                    'breadcrumb2'=>$breadcrumb2,
                    'breadcrumb3'=>$breadcrumb3,
                    'p_stock'=>$p_stock,
                    'color'=>$color,
                    'collection'=>$collection
                    
                );
			}

            $data['currency']=$this->session->data['currency'];
            $this->session->data['gaecmadwconv_order_id'] = $this->session->data['order_id'];
            $this->session->data['gaecmadwconv_coupon'] = isset($this->session->data['coupon']) ? $this->session->data['coupon'] : false;

            $log->write("-------------");

            $this->unsetOrder();
            //$this->fixReward(); # Ürün puanlarını toplayarak müşteriye puan  verme kapatıldı -Can

		}

		$this->document->setTitle($this->language->get('heading_title'));

        $log->write("-------------");

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/home')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_basket'),
			'href' => $this->url->link('checkout/cart')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_checkout'),
			'href' => $this->url->link('checkout/checkout', '', true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_success'),
			'href' => $this->url->link('checkout/success')
		);

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

		if ($this->customer->isLogged()) {
			$data['text_message'] = sprintf($this->language->get('text_customer'), $this->url->link('account/account', '', true), $this->url->link('account/order', '', true), $this->url->link('information/contact', '', true), $this->url->link('information/contact'));
		} else {
			$data['text_message'] = sprintf($this->language->get('text_guest'), $this->url->link('information/contact'));
		}

		$data['text_message'] .= $config_conversion_text;

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

		$data['text_order_id'] = sprintf($this->language->get('text_order_id'), $order_id);
		$data['order_id'] = $order_id;

		$data['continue'] = $this->url->link('common/home');

		$data['column_left'] = $this->load->controller('common/column_left');
		$data['column_right'] = $this->load->controller('common/column_right');
		$data['content_top'] = $this->load->controller('common/content_top');
		$data['content_bottom'] = $this->load->controller('common/content_bottom');
		$data['footer'] = $this->load->controller('common/footer');
		$data['header'] = $this->load->controller('common/header');
		$data['CretioOneTag_status']=	$this->config->get('CretioOneTag_status');
        $data['CretioOneTag_id']=	$this->config->get('CretioOneTag_id');


        $log->write("-------------");

        //dataLayer
        if (isset($this->session->data['customer_id']) && !empty($this->session->data['customer_id'])) {
            $data['dataLayer']['customer_id'] = $this->session->data['customer_id'];
            $data['dataLayer']['userType'] = 'member';

            $this->load->model('account/customer');

            $customerData = $this->model_account_customer->getCustomer($data['dataLayer']['customer_id']);
            $data['dataLayer']['emailHash'] = sha1($customerData['email']);

        }
        else {
            if (isset($_COOKIE['guest_id']) && !empty($_COOKIE['guest_id'])) {
                $guestId = $_COOKIE['guest_id'];
            }
            else {
                $guestId = rand(500000,999999);
                setcookie('guest_id', $guestId,time()+60*60*24*30, '/');
            }

            $data['dataLayer']['customer_id'] = $guestId;
            $data['dataLayer']['userType'] = 'guest';
            $data['dataLayer']['emailHash'] = '';
        }
        //dataLayer End

        $log->write("-------------");

        //Campaign Control
        if(isset($this->session->data['campaign'])){
            $this->session->data['campaign']['status'] = false;
        }
        //Campaign Control

        $log->write("--------Son-----");

        $log = new Log("order_success/". $order_id ."_success.txt");
        $log->write($this->load->view( DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/common/success', $data));

		if(file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/common/success.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') .'/template/common/success', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/common/success', $data));
		}
	
	}

    private function unsetOrder() {
        unset($this->session->data['shipping_method']);
        unset($this->session->data['shipping_methods']);
        unset($this->session->data['payment_method']);
        unset($this->session->data['payment_methods']);
        unset($this->session->data['guest']);
        unset($this->session->data['order_comment']);
        unset($this->session->data['delivery_date']);
        unset($this->session->data['delivery_time']);
        unset($this->session->data['survey']);
        unset($this->session->data['shipping_address']);
        unset($this->session->data['payment_address']);
        unset($this->session->data['comment']);
        unset($this->session->data['order_id']);
        unset($this->session->data['coupon']);
        unset($this->session->data['reward']);
        unset($this->session->data['voucher']);
        unset($this->session->data['vouchers']);
        unset($this->session->data['totals']);
        unset($this->session->data['campaign_price_total']);
        unset($this->session->data['ps_guest_firstname']);
        unset($this->session->data['ps_guest_lastname']);
        unset($this->session->data['ps_guest_email']);
        unset($this->session->data['ps_guest_telephone']);
        unset($this->session->data['ps_guest_payment_address_1']);
        unset($this->session->data['ps_guest_payment_city']);
        unset($this->session->data['ps_guest_payment_country_id']);
        unset($this->session->data['ps_guest_payment_zone_id']);
        unset($this->session->data['iyzico_fail_message']);
        unset($this->session->data['cart_count_log']);
    }
}