<?php
class ControllerAccountGuestOrder extends Controller {
	private $error = array();

	public function index() {


		$this->load->language('account/guestorder');
        $this->load->model('account/guestorder');
		if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			if (!empty($this->request->post['email']) && !empty($this->request->post['order_id'])) {
				$order_email = $this->request->post['email'];
				$order_id = $this->request->post['order_id'];

				$order_info = $this->model_account_guestorder->getOrder($order_id);

				if ($order_email != $order_info['email']) {	
					$this->session->data['error'] = $this->language->get('text_error');	
				} else {
					if (!empty($order_info)) {
						$this->response->redirect($this->url->link('account/guestorder/info', '&order_email=' . $order_email . '&order_id=' . $order_id, 'SSL'));
					}
				}
			}
		}else if($this->request->server['REQUEST_METHOD'] == 'GET'){
            if (!empty($this->request->get['email']) && !empty($this->request->get['order_id'])) {
                $order_email = $this->request->get['email'];
                $order_id = $this->request->get['order_id'];

                $order_info = $this->model_account_guestorder->getOrder($order_id);

                if ($order_email != $order_info['email']) {
                    $this->session->data['error'] = $this->language->get('text_error');
                } else {
                    if (!empty($order_info)) {
                        $this->response->redirect($this->url->link('account/guestorder/info', '&order_email=' . $order_email . '&order_id=' . $order_id, 'SSL'));
                    }
                }
            }
        }

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

		$this->load->language('account/order');
		

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

		$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_account'),
			'href' => $this->url->link('account/account', '', 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('guest_order_view'),
			'href' => $this->url->link('account/guestorder', '', 'SSL')
		);

		$data['heading_title'] = $this->language->get('heading_title');
		$data['order_field'] = $this->language->get('order_field');
		$data['email_field'] = $this->language->get('email_field');
		$data['button_continue'] = $this->language->get('button_continue');
		$data['view_order'] = $this->language->get('view_order');
	
		$data['action']	= $this->url->link('account/guestorder', '', 'SSL');
		$data['continue'] = $this->url->link('common/home', '', 'SSL');

		$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');

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


	}

    public function edit()
    {

        $this->load->language('account/order');

        if (isset($this->request->post['order_id']) && isset($this->request->post['email'])) {
            $order_id = (int)$this->request->post['order_id'];
            $email = $this->request->post['email'];
        } else if (isset($this->request->get['order_id']) && isset($this->request->get['order_email'])) {
            $order_id = (int)$this->request->get['order_id'];
            $email = $this->request->get['order_email'];
        } else {
            $order_id = 0;
            $email = '';
        }

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

        $order_info = $this->model_account_guestorder->getOrder($order_id);

        if ($order_info && isset($order_info['email']) && $order_info['email'] == $email) {

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

            if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
                $this->model_account_order->editOrderAddress($this->request->post, $order_id);
                $this->response->redirect($this->url->link('account/guestorder/info', 'order_email=' . $email .'&order_id=' . $order_id, true));
            }

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

            $url = '';

            if (isset($this->request->get['page'])) {
                $url .= '&page=' . $this->request->get['page'];
            }

            $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_account'),
                'href' => $this->url->link('account/account', '', true)
            );

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

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_order'),
                'href' => $this->url->link('account/order/info', 'order_id=' . $this->request->get['order_id'] . $url, true)
            );

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

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

            $data['action'] = $this->url->link('account/guestorder/edit', 'order_email='. $email .'&order_id=' . $this->request->get['order_id'], true);

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

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

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

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

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

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

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

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

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

            if($order_info['telephone']){
                $data['telephone'] = $order_info['telephone'];
            }else{
                $data['telephone'] = '';
            }

            $this->load->model('localisation/country');

            $data['countries'] = $this->model_localisation_country->getCountries();

            //Shipping Adress
            if($order_info['shipping_firstname']){
                $data['shipping_firstname'] = $order_info['shipping_firstname'];
            }else{
                $data['shipping_firstname'] = '';
            }

            if($order_info['shipping_lastname']){
                $data['shipping_lastname'] = $order_info['shipping_lastname'];
            }else{
                $data['shipping_lastname'] = '';
            }

            if($order_info['shipping_address_1']){
                $data['shipping_address_1'] = $order_info['shipping_address_1'];
            }else{
                $data['shipping_address_1'] = '';
            }

            if($order_info['shipping_city']){
                $data['shipping_city'] = $order_info['shipping_city'];
            }else{
                $data['shipping_city'] = '';
            }

            if($order_info['shipping_zone_id']){
                $data['shipping_zone_id'] = $order_info['shipping_zone_id'];
            }else{
                $data['shipping_zone_id'] = '';
            }

            if($order_info['shipping_country_id']){
                $data['shipping_country_id'] = $order_info['shipping_country_id'];
            }else{
                $data['shipping_country_id'] = '';
            }
            //Shipping Adress

            $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');

            if (file_exists(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/account/order_edit.tpl')) {
                $this->response->setOutput($this->load->view(DIR_LOCAL_TEMPLATE . $this->config->get('theme_default_directory') . '/template/account/order_edit', $data));
            } else {
                $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'default/template/account/order_edit', $data));
            }
        }else {
            $this->document->setTitle($this->language->get('text_order'));

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

            $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_account'),
                'href' => $this->url->link('account/account', '', true)
            );

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

            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_order'),
                'href' => $this->url->link('account/order/info', 'order_id=' . $order_id, true)
            );

            $data['continue'] = $this->url->link('account/order', '', true);

            $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');

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

    }

	public function info() {

		$this->load->language('account/order');
		$this->load->language('account/guestorder');
		$this->load->model('account/guestorder');

		if (isset($this->request->post['order_id']) && isset($this->request->post['email'])) {
			$order_id = (int)$this->request->post['order_id'];
			$email = $this->request->post['email'];
		} else if (isset($this->request->get['order_id']) && isset($this->request->get['order_email'])) {
			$order_id = (int)$this->request->get['order_id'];
			$email = $this->request->get['order_email'];
		} else {
			$order_id = 0;
			$email = '';
		}

		
		$order_info = $this->model_account_guestorder->getOrder($order_id);

		if ($order_info && isset($order_info['email']) && $order_info['email'] == $email) {

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

			$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_account'),
				'href' => $this->url->link('account/account', '', 'SSL')
			);
			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('guest_order_view'),
				'href' => $this->url->link('account/guestorder', '', 'SSL')
			);

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

			$data['text_order_detail'] = $this->language->get('text_order_detail');
			$data['text_invoice_no'] = $this->language->get('text_invoice_no');
			$data['text_order_id'] = $this->language->get('text_order_id');
			$data['text_date_added'] = $this->language->get('text_date_added');
			$data['text_shipping_method'] = $this->language->get('text_shipping_method');
			$data['text_shipping_address'] = $this->language->get('text_shipping_address');
			$data['text_payment_method'] = $this->language->get('text_payment_method');
			$data['text_payment_address'] = $this->language->get('text_payment_address');
			$data['text_history'] = $this->language->get('text_history');
			$data['text_comment'] = $this->language->get('text_comment');

			$data['column_name'] = $this->language->get('column_name');
			$data['column_model'] = $this->language->get('column_model');
			$data['column_quantity'] = $this->language->get('column_quantity');
			$data['column_price'] = $this->language->get('column_price');
			$data['column_total'] = $this->language->get('column_total');
			$data['column_action'] = $this->language->get('column_action');
			$data['column_date_added'] = $this->language->get('column_date_added');
			$data['column_status'] = $this->language->get('column_status');
			$data['column_comment'] = $this->language->get('column_comment');

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

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

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

			if ($order_info['invoice_no']) {
				$data['invoice_no'] = $order_info['invoice_prefix'] . $order_info['invoice_no'];
			} else {
				$data['invoice_no'] = '';
			}

            $data['action_return'] = $this->url->link('account/order_return/return_product', '&order_id=' . $order_id, true);

            $data['edit_shipping_address'] = $this->url->link('account/guestorder/edit', 'order_email='. $email .'&order_id=' . $order_id, true);


            $data['order_id'] = $order_id;
			$data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));

			if ($order_info['payment_address_format']) {
				$format = $order_info['payment_address_format'];
			} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

			$find = array(
				'{firstname}',
				'{lastname}',
				'{company}',
				'{address_1}',
				'{address_2}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}',
                '{payment_company}',
                '{payment_company_taxno}',
                '{payment_company_taxadmin}'
			);

			$replace = array(
				'firstname' => $order_info['payment_firstname'],
				'lastname'  => $order_info['payment_lastname'],
				'company'   => $order_info['payment_company'],
				'address_1' => $order_info['payment_address_1'],
				'address_2' => $order_info['payment_address_2'],
				'city'      => $order_info['payment_city'],
				'postcode'  => $order_info['payment_postcode'],
				'zone'      => $order_info['payment_zone'],
				'zone_code' => $order_info['payment_zone_code'],
				'country'   => $order_info['payment_country']
			);

			$data['payment_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

			$data['payment_method'] = $order_info['payment_method'];

			if ($order_info['shipping_address_format']) {
				$format = $order_info['shipping_address_format'];
			} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

			$find = array(
				'{firstname}',
				'{lastname}',
				'{company}',
				'{address_1}',
				'{address_2}',
				'{city}',
				'{postcode}',
				'{zone}',
				'{zone_code}',
				'{country}',
                '{payment_company}',
                '{payment_company_taxno}',
                '{payment_company_taxadmin}'
			);

			$replace = array(
				'firstname' => $order_info['shipping_firstname'],
				'lastname'  => $order_info['shipping_lastname'],
				'company'   => $order_info['shipping_company'],
				'address_1' => $order_info['shipping_address_1'],
				'address_2' => $order_info['shipping_address_2'],
				'city'      => $order_info['shipping_city'],
				'postcode'  => $order_info['shipping_postcode'],
				'zone'      => $order_info['shipping_zone'],
				'zone_code' => $order_info['shipping_zone_code'],
				'country'   => $order_info['shipping_country']
			);

			$data['shipping_address'] = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

			$data['shipping_method'] = $order_info['shipping_method'];

			$this->load->model('catalog/product');
			$this->load->model('tool/upload');
            $this->load->model('tool/image');


            $data['payment_code'] = $order_info['payment_code'];
            $data['payment_cod'] = false;
            if($data['payment_code'] == 'cod'){
                $data['payment_cod'] = true;
            }

			// Products
			$data['products'] = array();

			$products = $this->model_account_guestorder->getOrderProducts($order_id);

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


			    $pattern_text_control = json_decode($product['customer_pattern_data'], true);

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

                if ($product_info) {
                    $reorder = $this->url->link('account/order/reorder', 'order_id=' . $order_id . '&order_product_id=' . $product['order_product_id'], true);
                } else {
                    $reorder = '';
                }

                if ($product_info['image']) {
                    $image = $this->model_tool_image->resize($product_info['image'], $this->config->get($this->config->get('config_theme') . '_image_additional_width'), $this->config->get($this->config->get('config_theme') . '_image_additional_height'));
                    $case_image = $product_info['image'];
                } else {
                    $case_image = '';
                    $image = '';
                }

				$option_data = array();

				$options = $this->model_account_guestorder->getOrderOptions($order_id, $product['order_product_id']);

				foreach ($options as $option) {
					if ($option['type'] != 'file') {
						$value = $option['value'];
					} else {
						$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

						if ($upload_info) {
							$value = $upload_info['name'];
						} else {
							$value = '';
						}
					}

					$option_data[] = array(
						'name'  => $option['name'],
						'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
					);
				}

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

				if ($product_info) {
					$reorder = $this->url->link('account/guestorder/reorder', 'order_id=' . $order_id . '&order_product_id=' . $product['order_product_id'], 'SSL');
				} else {
					$reorder = '';
				}

                /* İşlenmiş Fotoğraf - @toturkmen - Başlangıç */
                $CasePatternImage = $this -> model_tool_image -> resize ($product ['case_order_image'], 100, 100);
                /* İşlenmiş Fotoğraf - @toturkmen - Bitiş */

                $customcase_image =  '';

                if ($product['customcase_image'] != '') {
                    $str = explode('***', $product['customcase_image']);
                    $customcase_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/' . $str[1];

                    if($case_image != '' &&  file_exists(DIR_IMAGE.$case_image))
                        $case_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/'.$case_image;
                    else
                        $case_image = ($this->request->server['HTTPS'] ? HTTPS_SERVER : HTTP_SERVER) . 'image/personal/' . $str[0];

                }

                //ToolTip Message #Bilal 21/09/2020
                $tooltip_message = 'Tüketicinin Korunması Hakkındaki Kanun \'Tüketicinin özel istek ve talepleri uyarınca üretilen veya üzerinde değişiklik ya da ilaveler yapılarak kişiye özel hale getirilen mallarda tüketici ürün iade hakkını kullanamaz.';
                if(in_array($order_info['order_status_id'], array(19,18,17,))){
                    $tooltip_message = 'Siparişiniz kargo sürecinde olduğudan, iptal-iade veya değişim işlemleri yapılamaz.';
                }
                if($product['return_status']){
                    $tooltip_message = 'Bu ürün için daha önce işlem yapılmıştır.';
                }
                //ToolTip Message #Bilal 21/09/2020


                $data['products'][] = array(
                    'name' => $product['name'],
                    'product_type' => $product_info['product_type'],
                    'personality' => $pattern_text_control['pattern_text'] ? true : false,
                    'image' => $image,
                    'customcase_image' => $customcase_image,
                    'case_image' => $case_image,
                    'case_pattern_image' => $CasePatternImage,
                    'model' => $product['model'],
                    'tooltip_message' => $tooltip_message,
                    'option' => $option_data,
                    'quantity' => $product['quantity'],
                    'price' => $this->currency->format($product['price'] + ($this->config->get('config_tax') ? $product['tax'] : 0), $order_info['currency_code'], $order_info['currency_value']),
                    'total' => $this->currency->format($product['total'] + ($this->config->get('config_tax') ? ($product['tax'] * $product['quantity']) : 0), $order_info['currency_code'], $order_info['currency_value']),
                    'reorder' => $reorder,
                    'order_detail' => $this->url->link('account/customerpartner/order_detail', 'order_id=' . $order_info['order_id'] . '&product_id=' . $product['product_id'], 'SSL'),
                    'order_id' => $product['order_id'],
                    'return_status' => $product['return_status'],
                    'product_id' => $product['product_id'],
                    'order_product_id' => $product['order_product_id'],
                    'return' => $this->url->link('account/order_return/return_product', 'order_id=' . $order_info['order_id'] . '&order_product_id=' . $product['order_product_id'] . '&return_type=change' . '&quantity=' . $product['quantity'], true)
                );

                $product_count += $product['quantity'];
			}

			// Voucher
			$data['vouchers'] = array();

			$vouchers = $this->model_account_guestorder->getOrderVouchers($order_id);

			foreach ($vouchers as $voucher) {
				$data['vouchers'][] = array(
					'description' => $voucher['description'],
					'amount'      => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
				);
			}

            $data['promotion_total'] = false;

			// Totals
			$data['totals'] = array();

			$totals = $this->model_account_guestorder->getOrderTotals($order_id);

            foreach ($totals as $total) {

                if($total['code'] == 'coupon'){
                    $c_title = explode(' ', $total['title']);
                    $data['totals'][] = array(
                        'title' => $c_title[0],
                        'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
                    );
                }else{
                    $data['totals'][] = array(
                        'title' => $total['title'],
                        'text' => $this->currency->format($total['value'], $order_info['currency_code'], $order_info['currency_value']),
                    );
                }


                if($total['code'] == 'promotion_total' OR $total['code'] == 'campaign_price_total'){
                    $data['promotion_total'] = true;
                }


            }

            $data['order_status_id'] = $order_info['order_status_id'];

            // Sipariş iptal İşlemi #Bilal 10/06/2020
            $data['order_cancel_status'] = false;
            if(in_array($order_info['order_status_id'], array(1,3))){
                $data['order_cancel_status'] = true;
            }

            // Sipariş iptal İşlemi #Bilal 10/06/2020

            //$order_check_query = $this->db->query("SELECT order_id FROM `ps_order` WHERE `date_added` > '2021-07-19 00:00:00' AND `date_added` < '2021-07-23 23:59:00' AND order_id = '". $order_id ."' ")->row;
            $order_check_query = $this->db->query("SELECT order_id, campaign FROM `ps_order` WHERE order_id = '". $order_id ."' ")->row;
            //$order_check_query = $this->db->query("SELECT order_id FROM `ps_order` WHERE `date_added` > '2021-07-19 00:00:00' AND order_id = '". $order_id ."' ")->row;

            if($order_check_query['campaign'] == '4al2ode'){
                $data['product_return_limit'] = 0;
                if($data['promotion_total']){
                    if($product_count > 3 AND $product_count < 7){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 4);
                    }else if($product_count > 6 AND $product_count < 8){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 6);
                    }else if($product_count > 9 AND $product_count < 11){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 9);
                    }else if($product_count > 12 AND $product_count < 14){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 10);
                    }
                }else{
                    $data['product_return_limit'] = 1;
                }

            }else if($order_check_query['campaign'] == '3al2ode'){
                $data['product_return_limit'] = 0;

                if($data['promotion_total']){
                    if($product_count > 2 AND $product_count < 6){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 2);
                    }else if($product_count > 5 AND $product_count < 9){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 4);
                    }else if($product_count > 8 AND $product_count < 12){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 6);
                    }else if($product_count > 12 AND $product_count < 15){
                        $data['product_return_limit'] = $this->cancelCheck($data['products'], 8);
                    }
                }else{
                    $data['product_return_limit'] = 1;
                }
            }

            $this->returnCheck($data['products'], $order_info['order_status_id'], $data['product_return_limit']);

			$data['comment'] = nl2br($order_info['comment']);

			// History
			$data['histories'] = array();

			$results = $this->model_account_guestorder->getOrderHistories($order_id);

			foreach ($results as $result) {
				$data['histories'][] = array(
					'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
					'status'     => $result['status'],
					'comment'    => $result['notify'] ? nl2br($result['comment']) : ''
				);
			}

            //14 Workdays return control #Bilal 30/11/2020

            $data['workdays_return_control'] = true;

            $order_complate_status = $this->config->get('config_complete_status')[0];

            if($order_info['order_status_id'] == $order_complate_status){
                $date_modified = $order_info['date_modified'];


                $orderDate = strtotime('18 day',strtotime($date_modified));
                $orderDate = date('Ymd' ,$orderDate );

                $nowDate = date('Ymd');

                $orderDate = strtotime($orderDate);
                $nowDate = strtotime($nowDate);

                if($nowDate > $orderDate){
                    $data['workdays_return_control'] = false;
                }

            }


            //14 Workdays return control #Bilal 30/11/2020

			$data['continue'] = $this->url->link('account/guestorder', '', 'SSL');

			$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');


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


		} else {
			$this->document->setTitle($this->language->get('text_order'));

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

			$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_account'),
				'href' => $this->url->link('account/account', '', 'SSL')
			);
			$data['breadcrumbs'][] = array(
				'text' => $this->language->get('guest_order_view'),
				'href' => $this->url->link('account/guestorder', '', 'SSL')
			);

			$data['continue'] = $this->url->link('account/guestorder', '', 'SSL');

			$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');

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


		}
	}

    private function returnCheck(&$products, $order_status_id, $product_return_limit)
    {


        foreach ($products as $key => $product){
            $return_check = false;
            $change_check = false;

            if(in_array($order_status_id,array(1))){
                $return_check = true;
            }else if(in_array($order_status_id,array(3))){
                $return_check = true;

                if(strpos($product['model'], 'cst00') !== false OR $product['personality']){
                    $return_check = false;
                }
            }else if(in_array($order_status_id,array(17,19,18))){
                $return_check = false;
                $change_check = false;
            }else if(in_array($order_status_id,array(20))){
                //$return_check = true;
                //$change_check = false;
            }else if(in_array($order_status_id,array(5,20))){
                if(isset($this->session->data['user_id'])){

                }
                if(strpos($product['model'], 'cst00') !== false OR $product['personality']){
                    $change_check = true;
                }else{
                    $return_check = true;
                    $change_check = true;
                }
            }

            if(in_array($order_status_id,array(1)) AND $product['return_status'] == 2){
                $return_check = false;
            }

            $products[$key]['return_check'] = $return_check;
            $products[$key]['change_check'] = $change_check;

        }

        if(in_array($order_status_id,array(5))){
            $flag = 1;
            foreach ($products as $key => $product){
                if(strpos($product['model'], 'cst00') !== false OR $product['personality']){
                    $products[$key]['change_check'] = true;
                }else{
                    if($flag >= $product_return_limit) {
                        $flag++;
                        $products[$key]['return_check'] = true;
                        $products[$key]['change_check'] = true;
                    }
                }
            }
        }


        if(in_array($order_status_id,array(20))){
            foreach ($products as $key => $product){
                if($product['return_status']){
                    $products[$key]['return_check'] = false;
                    $products[$key]['change_check'] = false;
                    $products[$key]['name'] .= '<span style="color: red"> (İade Sürecinde)</span>';
                }

            }
        }




    }

    private function cancelCheck(&$products, $product_return_limit)
    {

        //if(isset($this->session->data['user_id']) AND $this->session->data['user_id'] == 3){
            $product_count = count($products);

            foreach ($products as $product){
                if($product['return_status']){
                    $product_count--;
                }
            }

            if($product_return_limit < $product_count){
                return $product_return_limit;
            }else{
                return $product_count;
            }



            // $this->product->dump($product_count);
        //}

    }
	
	public function reorder() {

		$this->load->language('account/order');
		$this->load->language('account/guestorder');

		if (isset($this->request->get['order_id'])) {
			$order_id = $this->request->get['order_id'];
		} else {
			$order_id = 0;
		}

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

		$order_info = $this->model_account_guestorder->getOrder($order_id);

		if ($order_info) {
			if (isset($this->request->get['order_product_id'])) {
				$order_product_id = $this->request->get['order_product_id'];
			} else {
				$order_product_id = 0;
			}

			$order_product_info = $this->model_account_guestorder->getOrderProduct($order_id, $order_product_id);

			if ($order_product_info) {
				$this->load->model('catalog/product');

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

				if ($product_info) {
					$option_data = array();

					$order_options = $this->model_account_guestorder->getOrderOptions($order_product_info['order_id'], $order_product_id);

					foreach ($order_options as $order_option) {
						if ($order_option['type'] == 'select' || $order_option['type'] == 'radio' || $order_option['type'] == 'image') {
							$option_data[$order_option['product_option_id']] = $order_option['product_option_value_id'];
						} elseif ($order_option['type'] == 'checkbox') {
							$option_data[$order_option['product_option_id']][] = $order_option['product_option_value_id'];
						} elseif ($order_option['type'] == 'text' || $order_option['type'] == 'textarea' || $order_option['type'] == 'date' || $order_option['type'] == 'datetime' || $order_option['type'] == 'time') {
							$option_data[$order_option['product_option_id']] = $order_option['value'];
						} elseif ($order_option['type'] == 'file') {
							$option_data[$order_option['product_option_id']] = $this->encryption->encrypt($order_option['value']);
						}
					}

					$this->cart->add($order_product_info['product_id'], $order_product_info['quantity'], $option_data);

					$this->session->data['success'] = sprintf($this->language->get('text_success'), $this->url->link('product/product', 'product_id=' . $product_info['product_id']), $product_info['name'], $this->url->link('checkout/cart'));

					unset($this->session->data['shipping_method']);
					unset($this->session->data['shipping_methods']);
					unset($this->session->data['payment_method']);
					unset($this->session->data['payment_methods']);
				} else {
					$this->session->data['error'] = sprintf($this->language->get('error_reorder'), $order_product_info['name']);
				}
			}
		}

		$this->response->redirect($this->url->link('account/guestorder/info', 'order_id=' . $order_id . '&order_email=' . $order_info['email'] . '&order_code=' . $this->order_code($order_info['email'], $order_id)));
	}
	
	private function order_code($order_email = '', $order_id = '') {
		if (!empty($this->session->data['cookie'])) {
			$cookie = $this->session->data['cookie'];
		} else {
			$cookie = '';
		}

		$order_code = substr(md5($order_email . $order_id . $cookie . '_guestorderview'), 0, 10);
		return $order_code;
	}

	private function confirm_order_email($order_email = '', $order_id = '') {
		$this->load->language('account/order');
		$this->load->language('account/guestorder');

		if (!empty($order_email) && !empty($order_id)) {
			$order_info = $this->model_account_guestorder->getOrder($order_id);

			if (!empty($order_info)) {
				$subject 	= sprintf($this->language->get('text_subject'), $this->config->get('config_name'));
				$order_code = $this->order_code($order_info['email'], $order_id);

				$link = $this->url->link('account/guestorder/info', 'order_id=' . $order_id . '&order_email=' . $order_info['email'] . '&order_code=' . $order_code);

				$message = $this->language->get('text_email') . "\n";
				$message .= $link . "\n\n";
				
				if (VERSION < '2.0.2.0' || VERSION == '2.0.3.1') {
					$mail = new Mail($this->config->get('config_mail'));
				} else {
					$mail = new SendgridMail($this->config->get('sendgrid_api_key'));
					$mail->protocol = $this->config->get('config_mail_protocol');
					$mail->parameter = $this->config->get('config_mail_parameter');
					$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
					$mail->smtp_username = $this->config->get('config_mail_smtp_username');
					$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
					$mail->smtp_port = $this->config->get('config_mail_smtp_port');
					$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
				}
				$mail->setTo($order_email);
				$mail->setFrom($this->config->get('config_email'));
				$mail->setSender($this->config->get('config_name'));
				$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
				$mail->setText(html_entity_decode($message, ENT_QUOTES, 'UTF-8'));
				$mail->send();


				
			}
		}
	}

    protected function validateForm(){

        if(!isset($this->request->post['telephone']) OR empty($this->request->post['telephone'])){
            $this->error['error_telephone'] = "Cep telefon numarasını girmelisiniz!";
        }

        if(!isset($this->request->post['shipping_firstname']) OR empty($this->request->post['shipping_firstname'])){
            $this->error['error_shipping_firstname'] = "İsim yazmalısınız!";
        }

        if(!isset($this->request->post['shipping_lastname']) OR empty($this->request->post['shipping_firstname'])){
            $this->error['error_shipping_lastname'] = "Soyisim yazmalısınız!";
        }

        if(!isset($this->request->post['shipping_address_1']) OR empty($this->request->post['shipping_address_1'])){
            $this->error['error_shipping_address_1'] = "Açık adres yazmalısınız!";
        }

        if(!isset($this->request->post['shipping_city']) OR empty($this->request->post['shipping_city'])){
            $this->error['error_shipping_city'] = "İlçe/Semt girmelisiniz!";
        }

        if(!isset($this->request->post['zone_id']) OR empty($this->request->post['zone_id'])){
            $this->error['error_zone_id'] = "Şehir seçmelisiniz!";
        }

        if(!isset($this->request->post['country_id']) OR empty($this->request->post['country_id'])){
            $this->error['error_country_id'] = "Ülke seçmelisiniz!";
        }

        return !$this->error;

    }

}