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

	public function index() {
		$this->load->language('sale/return');

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

		$this->load->model('sale/return');

		$this->getList();
	}

	public function add() {

		$this->load->language('sale/return');

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

		$this->load->model('sale/return');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_sale_return->addReturn($this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

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

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

			if (isset($this->request->get['filter_customer'])) {
				$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_product'])) {
				$url .= '&filter_product=' . urlencode(html_entity_decode($this->request->get['filter_product'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}

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

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

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

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

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

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

			$this->response->redirect($this->url->link('sale/return', 'token=' . $this->session->data['token'] . $url, true));
		}

		$this->getForm();
	}

	public function edit() {

		$this->load->language('sale/return');

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

		$this->load->model('sale/return');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_sale_return->editReturn($this->request->get['return_id'], $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

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

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

			if (isset($this->request->get['filter_customer'])) {
				$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_product'])) {
				$url .= '&filter_product=' . urlencode(html_entity_decode($this->request->get['filter_product'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}

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

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

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

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

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

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

			$this->response->redirect($this->url->link('sale/return', 'token=' . $this->session->data['token'] . $url, true));
		}

		$this->getForm();
	}

	public function delete() {
		$this->load->language('sale/return');

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

		$this->load->model('sale/return');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $return_id) {
				$this->model_sale_return->deleteReturn($return_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

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

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

			if (isset($this->request->get['filter_customer'])) {
				$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_product'])) {
				$url .= '&filter_product=' . urlencode(html_entity_decode($this->request->get['filter_product'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}

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

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

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

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

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

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

			$this->response->redirect($this->url->link('sale/return', 'token=' . $this->session->data['token'] . $url, true));
		}

		$this->getList();
	}

	protected function getList() {

	    $data['return_or_change'] = [
	        'İade' => 'İade',
	        'Değişim' => 'Değişim',
            'İptal' => 'İptal',
        ];

		$url = '';

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

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

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

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

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_product'])) {
			$url .= '&filter_product=' . urlencode(html_entity_decode($this->request->get['filter_product'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

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

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

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

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

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

		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/dashboard', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('sale/return', 'token=' . $this->session->data['token'] . $url, true)
		);

		$data['add'] = $this->url->link('sale/return/add', 'token=' . $this->session->data['token'] . $url, true);
		$data['delete'] = $this->url->link('sale/return/delete', 'token=' . $this->session->data['token'] . $url, true);
	
		$data['filter_by_return'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&filter_by=İade', true);
		$data['filter_by_exchange'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&filter_by=Değişim', true);
		$data['filter_by_cancel'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&filter_by=İptal', true);

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

		$filter_data = $this->getFilters();
		$page = $filter_data['page'];
		$order = $filter_data['order'];
		$sort = $filter_data['sort'];
        $filter_by = $filter_data['filter_by'];

		$return_total = $this->model_sale_return->getTotalReturns($filter_data);

		$results = $this->model_sale_return->getReturns($filter_data);

		

		foreach ($results as $result) {
			$ord = $this->db->query("SELECT payment_firstname, payment_lastname FROM ps_order WHERE order_id = '".(int)$result['order_id']."' ")->row;
			$data['returns'][] = array(
				'return_id'     => $result['return_id'],
				'order_id'      => $result['order_id'],
				'customer'      => $ord['payment_firstname'] . ' ' . $ord['payment_lastname'],
				'product'       => $result['product'],
				'model'         => $result['model'],
				'status'        => $result['status'],
				'return_or_change' => $result['return_or_change'],
				'prefer_pay_coupon' => $result['prefer_pay_coupon'],
				'date_added'    => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
				'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
				'edit'          => $this->url->link('sale/return/edit', 'token=' . $this->session->data['token'] . '&return_id=' . $result['return_id'] . $url, true),
				'order_href'          => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, true)
			);
		}

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

		$data['text_list'] = $this->language->get('text_list');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');

		$data['column_return_id'] = $this->language->get('column_return_id');
		$data['column_order_id'] = $this->language->get('column_order_id');
		$data['column_customer'] = $this->language->get('column_customer');
		$data['column_product'] = $this->language->get('column_product');
		$data['column_model'] = $this->language->get('column_model');
		$data['column_status'] = $this->language->get('column_status');

		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_date_modified'] = $this->language->get('column_date_modified');
		$data['column_action'] = $this->language->get('column_action');

		$data['entry_return_id'] = $this->language->get('entry_return_id');
		$data['entry_order_id'] = $this->language->get('entry_order_id');
		$data['entry_customer'] = $this->language->get('entry_customer');
		$data['entry_product'] = $this->language->get('entry_product');
		$data['entry_model'] = $this->language->get('entry_model');
		$data['entry_return_status'] = $this->language->get('entry_return_status');
		$data['entry_date_added'] = $this->language->get('entry_date_added');
		$data['entry_date_modified'] = $this->language->get('entry_date_modified');

		$data['button_add'] = $this->language->get('button_add');
		$data['button_edit'] = $this->language->get('button_edit');
		$data['button_delete'] = $this->language->get('button_delete');
		$data['button_filter'] = $this->language->get('button_filter');
		
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['button_exchange'] = $this->language->get('button_exchange');
		$data['button_return'] = $this->language->get('button_return');

		$data['token'] = $this->session->data['token'];

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

			unset($this->session->data['error']);
		} elseif (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} 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 (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

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

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

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

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_product'])) {
			$url .= '&filter_product=' . urlencode(html_entity_decode($this->request->get['filter_product'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

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

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

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

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

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

		$data['sort_return_id'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=r.return_id' . $url, true);
		$data['sort_order_id'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=r.order_id' . $url, true);
		$data['sort_customer'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=customer' . $url, true);
		$data['sort_product'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=r.product' . $url, true);
		$data['sort_model'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=r.model' . $url, true);
		$data['sort_status'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=status' . $url, true);
		$data['sort_date_added'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=r.date_added' . $url, true);
		$data['sort_date_modified'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . '&sort=r.date_modified' . $url, true);

		$url = '';

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

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

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

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_product'])) {
			$url .= '&filter_product=' . urlencode(html_entity_decode($this->request->get['filter_product'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

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

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

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

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

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

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

		$data['excelUrl'] = $this->url->link('sale/return/getlistexcel', 'token=' . $this->session->data['token'] . $url , true);

		$pagination = new Pagination();
		$pagination->total = $return_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . $url . '&page={page}', true);

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($return_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($return_total - $this->config->get('config_limit_admin'))) ? $return_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $return_total, ceil($return_total / $this->config->get('config_limit_admin')));

		$data = array_merge($data, $filter_data);
		/*$data['filter_return_id'] = $filter_return_id;
		$data['filter_return_action_id'] = $filter_return_action_id;
		$data['filter_order_id'] = $filter_order_id;
		$data['filter_customer'] = $filter_customer;
		$data['filter_product'] = $filter_product;
		$data['filter_model'] = $filter_model;
		$data['filter_return_status_id'] = $filter_return_status_id;
		$data['filter_date_added'] = $filter_date_added;
		$data['filter_date_modified'] = $filter_date_modified;*/

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

		$data['return_statuses'] = $this->model_localisation_return_status->getReturnStatuses();
		
		$this->load->model('localisation/return_action');

		$data['return_actions'] = $this->model_localisation_return_action->getReturnActions();

		$data['sort'] = $sort;
		$data['order'] = $order;

		$data['filter_time_range'] = null;
		if (isset($this->request->get['filter_time_range'])) {
            $data['filter_time_range'] = $this->request->get['filter_time_range'];
        }

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');

		if(file_exists(DIR_LOCAL_TEMPLATE .'sale/return_list.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'sale/return_list', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'sale/return_list', $data));
		}
		
	}

    /**
     * 09.09.20 get filtered return products excel (ali.a)
     * 13.10.20 [UPDATE] add product category (ali.a)
     */
	public function getListExcel() {
        error_reporting(0);

	    $this->load->model('sale/return');
        $this->load->model('localisation/return_status');
        $this->load->model('localisation/return_action');

	    $filter_data = $this->getFilters();
	    $filter_data['limit'] = 9999999;

        $return_statuses_results = $this->model_localisation_return_status->getReturnStatuses();
        foreach ($return_statuses_results as $return_status) {
            $return_statuses[$return_status['return_status_id']] = $return_status['name'];
        }

        //collect data with id's are keys of array
        $return_actions_results = $this->model_localisation_return_action->getReturnActions();
        foreach ($return_actions_results as $return_action) {
            $return_actions[$return_action['return_action_id']] = $return_action['name'];
        }

        //get return items
        $returns = $this->model_sale_return->getReturns($filter_data); //echo '<pre>';var_dump($returns);exit;

        //prepare ids for order products and return coupon amounts
        foreach ($returns as $return) {
            $return_order_ids[] = $return['order_id'];
            $return_product_ids[] = $return['product_id'];
            $return_ids[] = $return['return_id'];
        }

        //get order products for product price
        $return_order_product = $this->model_sale_return->getReturnOrderProducts($return_order_ids, $return_product_ids);

        //get return coupons for coupon amount
        $return_coupon_amounts = $this->model_sale_return->getReturnCouponAmounts($return_order_ids, $return_ids);

        //get return products attributes
        $return_product_attributes = $this->model_sale_return->getReturnProductAttributes($return_product_ids);

        //get return products categories
        $return_product_categories = $this->model_sale_return->getReturnProductSecondCategoryNames($return_product_ids);

        //get order options
        $order_options = $this->model_sale_return->getReturnOrderOptions($return_order_product);

        //dd($order_options);
        //echo '<pre>';var_dump($return_coupon_amounts);exit;

        $file_name = $this->config->get('config_name') . '-' . @date("Y-m-d-His") . "-returns.xls";

        require_once DIR_SYSTEM . 'PHPExcel/Classes/PHPExcel.php';

        $excel = new PHPExcel();

        $excel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Sipariş No')
            ->setCellValue('B1', 'Ürün')
            ->setCellValue('C1', 'Seçenek')
            ->setCellValue('D1', 'Koleksiyon')
            ->setCellValue('E1', 'Model')
            ->setCellValue('F1', 'Ürün Kodu')
            ->setCellValue('G1', 'Ürün Fiyatı')
            ->setCellValue('H1', 'İade Nedeni')
            ->setCellValue('I1', 'Admin İade Nedeni')
            ->setCellValue('J1', 'Durum')
            ->setCellValue('K1', 'Kupon Tutarı');

        if ($returns) {
            foreach ($returns as $rowNumber => $return) {

                $excel->setActiveSheetIndex(0)
                    ->setCellValue('A'.($rowNumber+2), $return['order_id'])
                    ->setCellValue('B'.($rowNumber+2), $return['product'])
                    ->setCellValue('C'.($rowNumber+2), (isset($order_options[$return['order_id']][$return_order_product[$return['order_id']][$return['product_id']]['order_product_id']])) ? $order_options[$return['order_id']][$return_order_product[$return['order_id']][$return['product_id']]['order_product_id']]:'')
                    ->setCellValue('D'.($rowNumber+2), (isset($return_product_attributes[$return['product_id']])) ? $return_product_attributes[$return['product_id']] : '') //attributes
                    ->setCellValue('E'.($rowNumber+2), (isset($return_product_categories[$return['product_id']])) ? $return_product_categories[$return['product_id']] : '') //categories
                    ->setCellValue('F'.($rowNumber+2), $return['model'])
                    ->setCellValue('G'.($rowNumber+2), (isset($return_order_product[$return['order_id']][$return['product_id']]['price'])) ? $return_order_product[$return['order_id']][$return['product_id']]['price'] : '') //urun fiyat
                    ->setCellValue('H'.($rowNumber+2), $return['return_or_change'])
                    ->setCellValue('I'.($rowNumber+2), (isset($return_actions[$return['return_action_id']])) ? $return_actions[$return['return_action_id']] : '' )
                    ->setCellValue('J'.($rowNumber+2), (isset($return_statuses[$return['return_status_id']])) ? $return_statuses[$return['return_status_id']] : '')
                    ->setCellValue('K'.($rowNumber+2), (isset($return_coupon_amounts[$return['order_id']][$return['return_id']])) ? $return_coupon_amounts[$return['order_id']][$return['return_id']] : ''); //kupon tutari

            }
        }

        $excel->getActiveSheet()->setTitle('Simple');
        $excel->getActiveSheet()->getColumnDimension('B')->setWidth(40);
        $excel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $excel->getActiveSheet()->getColumnDimension('H')->setWidth(15);

        $excel->setActiveSheetIndex(0);

        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel5');
        $objWriter->save('php://output');
        exit;

    }


	protected function getForm() {
		$data['heading_title'] = $this->language->get('heading_title');

		$data['text_form'] = !isset($this->request->get['return_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
		$data['text_select'] = $this->language->get('text_select');
		$data['text_opened'] = $this->language->get('text_opened');
		$data['text_unopened'] = $this->language->get('text_unopened');
		$data['text_order'] = $this->language->get('text_order');
		$data['text_product'] = $this->language->get('text_product');
		$data['text_history'] = $this->language->get('text_history');
		$data['text_loading'] = $this->language->get('text_loading');

		$data['entry_customer'] = $this->language->get('entry_customer');
		$data['entry_order_id'] = $this->language->get('entry_order_id');
		$data['entry_date_ordered'] = $this->language->get('entry_date_ordered');
		$data['entry_firstname'] = $this->language->get('entry_firstname');
		$data['entry_lastname'] = $this->language->get('entry_lastname');
		$data['entry_email'] = $this->language->get('entry_email');
		$data['entry_telephone'] = $this->language->get('entry_telephone');
		$data['entry_product'] = $this->language->get('entry_product');
		$data['entry_model'] = $this->language->get('entry_model');
		$data['entry_quantity'] = $this->language->get('entry_quantity');
		$data['entry_opened'] = $this->language->get('entry_opened');
		$data['entry_return_reason'] = $this->language->get('entry_return_reason');
		$data['entry_return_action'] = $this->language->get('entry_return_action');
		$data['entry_return_status'] = $this->language->get('entry_return_status');
		$data['entry_comment'] = $this->language->get('entry_comment');
		$data['entry_notify'] = $this->language->get('entry_notify');

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

		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['button_history_add'] = $this->language->get('button_history_add');

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

		$data['token'] = $this->session->data['token'];

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

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

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

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

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

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

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

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

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

		$url = '';

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

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

		if (isset($this->request->get['filter_customer'])) {
			$url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_product'])) {
			$url .= '&filter_product=' . urlencode(html_entity_decode($this->request->get['filter_product'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

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

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

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

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

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

		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/dashboard', 'token=' . $this->session->data['token'], true)
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('sale/return', 'token=' . $this->session->data['token'] . $url, true)
		);

		if (!isset($this->request->get['return_id'])) {
			$data['action'] = $this->url->link('sale/return/add', 'token=' . $this->session->data['token'] . $url, true);
		} else {
			$data['action'] = $this->url->link('sale/return/edit', 'token=' . $this->session->data['token'] . '&return_id=' . $this->request->get['return_id'] . $url, true);
		}

		$data['cancel'] = $this->url->link('sale/return', 'token=' . $this->session->data['token'] . $url, true);

		if (isset($this->request->get['return_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$return_info = $this->model_sale_return->getReturn($this->request->get['return_id']);
		}

		if (isset($this->request->post['order_id'])) {
			$data['order_id'] = $this->request->post['order_id'];
		} elseif (!empty($return_info)) {
			$data['order_id'] = $return_info['order_id'];
		} else {
			$data['order_id'] = '';
		}

		if (isset($this->request->post['date_ordered'])) {
			$data['date_ordered'] = $this->request->post['date_ordered'];
		} elseif (!empty($return_info)) {
			$data['date_ordered'] = ($return_info['date_ordered'] != '0000-00-00' ? $return_info['date_ordered'] : '');
		} else {
			$data['date_ordered'] = '';
		}

		if (isset($this->request->post['customer'])) {
			$data['customer'] = $this->request->post['customer'];
		} elseif (!empty($return_info)) {
			$data['customer'] = $return_info['customer'];
		} else {
			$data['customer'] = '';
		}

		if (isset($this->request->post['customer_id'])) {
			$data['customer_id'] = $this->request->post['customer_id'];
		} elseif (!empty($return_info)) {
			$data['customer_id'] = $return_info['customer_id'];
		} else {
			$data['customer_id'] = '';
		}

		if (isset($this->request->post['firstname'])) {
			$data['firstname'] = $this->request->post['firstname'];
		} elseif (!empty($return_info)) {
			$data['firstname'] = $return_info['firstname'];
		} else {
			$data['firstname'] = '';
		}

		if (isset($this->request->post['lastname'])) {
			$data['lastname'] = $this->request->post['lastname'];
		} elseif (!empty($return_info)) {
			$data['lastname'] = $return_info['lastname'];
		} else {
			$data['lastname'] = '';
		}

		if (isset($this->request->post['email'])) {
			$data['email'] = $this->request->post['email'];
		} elseif (!empty($return_info)) {
			$data['email'] = $return_info['email'];
		} else {
			$data['email'] = '';
		}

		if (isset($this->request->post['telephone'])) {
			$data['telephone'] = $this->request->post['telephone'];
		} elseif (!empty($return_info)) {
			$data['telephone'] = $return_info['telephone'];
		} else {
			$data['telephone'] = '';
		}

		if (isset($this->request->post['product'])) {
			$data['product'] = $this->request->post['product'];
		} elseif (!empty($return_info)) {
			$data['product'] = $return_info['product'];
		} else {
			$data['product'] = '';
		}

		if (isset($this->request->post['product_id'])) {
			$data['product_id'] = $this->request->post['product_id'];
		} elseif (!empty($return_info)) {
			$data['product_id'] = $return_info['product_id'];
		} else {
			$data['product_id'] = '';
		}

		if (isset($this->request->post['model'])) {
			$data['model'] = $this->request->post['model'];
		} elseif (!empty($return_info)) {
			$data['model'] = $return_info['model'];
		} else {
			$data['model'] = '';
		}

		if (isset($this->request->post['quantity'])) {
			$data['quantity'] = $this->request->post['quantity'];
		} elseif (!empty($return_info)) {
			$data['quantity'] = $return_info['quantity'];
		} else {
			$data['quantity'] = '';
		}

		if (isset($this->request->post['return_or_change'])) {
			$data['return_or_change'] = $this->request->post['return_or_change'];
		} elseif (!empty($return_info)) {
			$data['return_or_change'] = $return_info['return_or_change'];
		} else {
			$data['return_or_change'] = '';
		}

		if (isset($this->request->post['opened'])) {
			$data['opened'] = $this->request->post['opened'];
		} elseif (!empty($return_info)) {
			$data['opened'] = $return_info['opened'];
		} else {
			$data['opened'] = '';
		}

		if (isset($this->request->post['return_reason_id'])) {
			$data['return_reason_id'] = $this->request->post['return_reason_id'];
		} elseif (!empty($return_info)) {
			$data['return_reason_id'] = $return_info['return_reason_id'];
		} else {
			$data['return_reason_id'] = '';
		}

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

		$data['return_reasons'] = $this->model_localisation_return_reason->getReturnReasons();

		if (isset($this->request->post['return_action_id'])) {
			$data['return_action_id'] = $this->request->post['return_action_id'];
		} elseif (!empty($return_info)) {
			$data['return_action_id'] = $return_info['return_action_id'];
		} else {
			$data['return_action_id'] = '';
		}

		$this->load->model('localisation/return_action');
		$data['return_actions'] = $this->model_localisation_return_action->getReturnActions();
		
		
		if (isset($this->request->post['return_reason_action_id'])) {
			$data['return_action_id'] = $this->request->post['return_reason_action_id'];
		} elseif (!empty($return_info)) {
			$data['return_reason_action_id'] = $return_info['return_reason_action_id'];
		} else {
			$data['return_reason_action_id'] = '';
		}
		
		$this->load->model('localisation/return_reason_action');
		$data['return_reason_actions'] = $this->model_localisation_return_reason_action->getReturnReasonActions();

		if (isset($this->request->post['comment'])) {
			$data['comment'] = $this->request->post['comment'];
		} elseif (!empty($return_info)) {
			$data['comment'] = $return_info['comment'];
		} else {
			$data['comment'] = '';
		}

		if (isset($this->request->post['return_status_id'])) {
			$data['return_status_id'] = $this->request->post['return_status_id'];
		} elseif (!empty($return_info)) {
			$data['return_status_id'] = $return_info['return_status_id'];
		} else {
			$data['return_status_id'] = '';
		}

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

		$data['return_statuses'] = $this->model_localisation_return_status->getReturnStatuses();

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');


		if(file_exists(DIR_LOCAL_TEMPLATE .'sale/return_form.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'sale/return_form', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'sale/return_form', $data));
		}


		
	}

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', 'sale/return')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if (empty($this->request->post['order_id'])) {
			$this->error['order_id'] = $this->language->get('error_order_id');
		}

		if ((utf8_strlen(trim($this->request->post['firstname'])) < 1) || (utf8_strlen(trim($this->request->post['firstname'])) > 32)) {
			$this->error['firstname'] = $this->language->get('error_firstname');
		}

		if ((utf8_strlen(trim($this->request->post['lastname'])) < 1) || (utf8_strlen(trim($this->request->post['lastname'])) > 32)) {
			$this->error['lastname'] = $this->language->get('error_lastname');
		}

		if ((utf8_strlen($this->request->post['email']) > 96) || !filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL)) {
			$this->error['email'] = $this->language->get('error_email');
		}

		if ((utf8_strlen($this->request->post['telephone']) < 3) || (utf8_strlen($this->request->post['telephone']) > 32)) {
			$this->error['telephone'] = $this->language->get('error_telephone');
		}

		if ((utf8_strlen($this->request->post['product']) < 1) || (utf8_strlen($this->request->post['product']) > 255)) {
			$this->error['product'] = $this->language->get('error_product');
		}

		if ((utf8_strlen($this->request->post['model']) < 1) || (utf8_strlen($this->request->post['model']) > 64)) {
			$this->error['model'] = $this->language->get('error_model');
		}

		if (empty($this->request->post['return_reason_id'])) {
			$this->error['reason'] = $this->language->get('error_reason');
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'sale/return')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}

	public function history() {

		$this->load->language('sale/return');

		$data['error'] = '';
		$data['success'] = '';

		$this->load->model('sale/return');

		if ($this->request->server['REQUEST_METHOD'] == 'POST') {
			if (!$this->user->hasPermission('modify', 'sale/return')) {
				$data['error'] = $this->language->get('error_permission');
			}

			if (!$data['error']) {
				$this->model_sale_return->addReturnHistory($this->request->get['return_id'], $this->request->post);

				$data['success'] = $this->language->get('text_success');
			}
		}

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

		$data['column_date_added'] = $this->language->get('column_date_added');
		$data['column_status'] = $this->language->get('column_status');
		$data['column_notify'] = $this->language->get('column_notify');
		$data['column_comment'] = $this->language->get('column_comment');

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

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

		$results = $this->model_sale_return->getReturnHistories($this->request->get['return_id'], ($page - 1) * 10, 10);

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

		$history_total = $this->model_sale_return->getTotalReturnHistories($this->request->get['return_id']);

		$pagination = new Pagination();
		$pagination->total = $history_total;
		$pagination->page = $page;
		$pagination->limit = 10;
		$pagination->url = $this->url->link('sale/return/history', 'token=' . $this->session->data['token'] . '&return_id=' . $this->request->get['return_id'] . '&page={page}', true);

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($history_total) ? (($page - 1) * 10) + 1 : 0, ((($page - 1) * 10) > ($history_total - 10)) ? $history_total : ((($page - 1) * 10) + 10), $history_total, ceil($history_total / 10));


		if(file_exists(DIR_LOCAL_TEMPLATE .'sale/return_history.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'sale/return_history', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'sale/return_history', $data));
		}


		
	}

    public function returnCoupon()
    {


        $this->load->model('marketing/coupon');

        $data['error'] = '';
        $data['success'] = '';

        $data['token'] = $this->session->data['token'];
        $data['order_id'] = $this->request->get['order_id'];
        $data['return_id'] = isset($this->request->get['return_id']) ? $this->request->get['return_id'] : 0;

        $orders_return_info = $this->db->query("SELECT * FROM ps_return WHERE order_id = '". (int)$this->request->get['order_id'] ."' ")->rows;

        $data['coupon_name'] = '';
        $price_total = 0;
        $data['return_products_list'] = array();
        foreach ($orders_return_info as $item){
            $data['return_products_list'][] = array(
                'name' => $item['product'],
                'return_or_change' => $item['return_or_change'],
            );
            $order_product_item = $this->db->query("SELECT * FROM ps_order_product WHERE order_id = '". (int)$this->request->get['order_id'] ."' AND model = '". $item['model'] ."' ")->row;
            $price_total += ($order_product_item['price'] + $order_product_item['total']);
            $data['coupon_name'] = $item['firstname'] . ' ' . $item['lastname'];
        }

        $data['price_total'] = number_format($price_total, 2, '.', '.');

        $coupons = $this->model_marketing_coupon->getCouponReturn($data['order_id']);


        $data['coupon_code'] = array();
        if($coupons){
            foreach ($coupons as $coupon){
                $coupon_info = $this->model_marketing_coupon->getCoupon($coupon['coupon_id']);
                if($coupon_info){
                    $data['coupon_code'][] = $coupon_info['code'];
                }
            }


        }

        $data['coupon_code'] = implode(',', $data['coupon_code']);


        if(file_exists(DIR_LOCAL_TEMPLATE .'sale/return_coupon.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'sale/return_coupon', $data));
        }else{
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'sale/return_coupon', $data));
        }

	}

    public function returnCouponMakeDone()
    {

        $this->load->model('sale/return');

        $json = array();

        $order_id = $this->request->get['order_id'];
        $return_id = $this->request->get['return_id'];

        $json['warning'] = '';

        if(!$this->request->post['coupon_name']){
            $json['warning'] = "Kupon ismi yazmalısınız!";
        }else{
            $coupon_name = $this->request->post['coupon_name'];
        }

        if(!$this->request->post['coupon_cost']){
            $json['warning'] = "Kupon tutarı girmelisiniz!";
        }else{
            $coupon_cost = $this->request->post['coupon_cost'];
            if(!is_numeric($coupon_cost)){
                $json['warning'] = "Kupon sayısal olmalıdır!";
            }
        }

        if(!$this->request->post['coupon_code']){
            $json['warning'] = "Kupon kodu oluşturmalısınız!";
        }else{
            $coupon_code = $this->request->post['coupon_code'];
        }

        $use_campaign = $this->request->post['use_campaign'];

        if(!$json['warning']){

            $this->load->model('marketing/coupon');
            $post_data = array(
                'name' => $coupon_name,
                'code' => $coupon_code,
                'discount' => $coupon_cost,
                'type' => 'F',
                'total' => 0,
                'logged' => 0,
                'shipping' => 0,
                'date_start' => '',
                'date_end' => '',
                'uses_total' => 1,
                'uses_customer' => 1,
                'return_coupon' => $use_campaign ? 0 : 1, //02.09.20 return coupon field added (ali a.)
                'status' => 1,
            );

            $coupon_id = $this->model_marketing_coupon->addCoupon($post_data);

            if($coupon_id){
                $coupon_data = array(
                    'order_id' => $order_id,
                    'return_id' => $return_id,
                    'coupon_id' => $coupon_id
                );
                $this->model_marketing_coupon->addCouponReturn($coupon_data);

                $comment = '';

                $comment .= 'Merhaba,' . "\n\n";
                $comment .= 'Değişim işleminize karşılık hesabınıza iade ettiğiniz ürün tutarında kupon tanımlanmıştır.' . "\n\n";
                $comment .= 'Kupon kodunuz ile '.$coupon_cost.' TL tutarında yeniden ücretsiz alışveriş yapabilirsiniz.' . "\n\n";
                $comment .= 'KUPON KODUNUZ: ' . $coupon_code . "\n\n";
                $comment .= 'Kuponların Kullanım Süresi 1 Aydır!' . "\n\n";
                $comment .= 'Kupon kodunuzu mevcut üyeliğiniz üzerinden veya üyelik oluşturarak ödeme sayfasında ‘Kupon Kullan’ alanına girerek kullanabilirsiniz. '. "\n\n";
                $comment .= 'Sağlıklı günler dileriz' . "\n\n";

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

                if($netgsm_ayarlari['netgsm_status'] == 1){

                    $text_mesaj = 'Merhaba, ';
                    $text_mesaj .= 'Değişim işleminize karşılık hesabınıza iade ettiğiniz ürün tutarında kupon tanımlanmıştır. ';
                    $text_mesaj .= 'Kupon kodunuz ile '.$coupon_cost.' TL tutarında yeniden ücretsiz alışveriş yapabilirsiniz. ';
                    $text_mesaj .= 'KUPON KODUNUZ: ' . $coupon_code . ' ';
                    $text_mesaj .= 'Kuponların Kullanım Süresi 1 Aydır!';
                    $text_mesaj .= 'Kupon kodunuzu mevcut üyeliğiniz üzerinden veya üyelik oluşturarak ödeme sayfasında ‘Kupon Kullan’ alanına girerek kullanabilirsiniz. ';
                    $text_mesaj .= 'Sağlıklı günler dileriz';

                    $netgsmsms = new Netgsmsms($netgsm_ayarlari['netgsm_user'],$netgsm_ayarlari['netgsm_pass'],$netgsm_ayarlari['netgsm_input_smstitle'],1);
                    $order_info = $this->db->query("SELECT telephone FROM ps_order WHERE order_id = '". $order_id ."' ")->row;
                    $netgsmsms->sendSMS($order_info['telephone'],$text_mesaj);
                }

                $info_data = array(
                    'return_status_id' => 5,
                    'notify' => 1,
                    'comment' => $comment,
					'coupon_code'=> $coupon_code // -Can 28.01.2022
                );

                $this->model_sale_return->addReturnHistory($return_id, $info_data);

                $json['success'] = "Kupon oluşturuldu! Kupon Kodu: " . $coupon_code;
            }else{
                $json['warning'] = "Sorun oluştu!";
            }



        }


        echo json_encode($json, true);



        
	}

    public function returnCouponMake()
    {

        $json = array();

        capa:
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randstring = 'R-';
        for ($i = 0; $i < 9; $i++) {
            $rand = rand(0, strlen($characters));
            $randstring .= $characters[$rand-1];
        }

        $json['coupon_code'] = $randstring;

        $coupon_exist = $this->db->query("SELECT * FROM ps_coupon WHERE code = '". $this->db->escape($randstring) ."'  ")->row;
        if($coupon_exist)
            goto capa;

        echo json_encode($json, true);



    }

    /**
     * 08.09.20 filter code moved here because of purpose of prevent repetation (ali.a)
     */
    private function getFilters() {

        $filter_return_id = null;
        if (isset($this->request->get['filter_return_id'])) {
            $filter_return_id = $this->request->get['filter_return_id'];
        }

        $filter_return_action_id = null;
        if (isset($this->request->get['filter_return_action_id'])) {
            $filter_return_action_id = $this->request->get['filter_return_action_id'];
        }

        $filter_order_id = null;
        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        }

        $filter_customer = null;
        if (isset($this->request->get['filter_customer'])) {
            $filter_customer = $this->request->get['filter_customer'];
        }

        $filter_product = null;
        if (isset($this->request->get['filter_product'])) {
            $filter_product = $this->request->get['filter_product'];
        }

        $filter_model = null;
        if (isset($this->request->get['filter_model'])) {
            $filter_model = $this->request->get['filter_model'];
        }

        $filter_return_status_id = null;
        if (isset($this->request->get['filter_return_status_id'])) {
            $filter_return_status_id = $this->request->get['filter_return_status_id'];
        }

        $filter_date_added = null;
        if (isset($this->request->get['filter_time_range'])) {
            switch ($this->request->get['filter_time_range']) {
                case 'last_week': $filter_date_added = date('d/m/Y', strtotime('-1 week')) . '-' . date('d/m/Y'); break;
                case 'last_month': $filter_date_added = date('d/m/Y', strtotime('-1 month')) . '-' . date('d/m/Y'); break;
                case 'last_year': $filter_date_added = date('d/m/Y', strtotime('-1 year')) . '-' . date('d/m/Y'); break;
                case 'all': $filter_date_added=''; break;
            }
        }
        elseif (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        }

        $filter_date_modified = null;
        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        }

        $sort = 'r.return_id';
        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        }

        $order = 'DESC';
        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        }

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

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

        $filter_return_or_change = null;
        if (isset($this->request->get['filter_return_or_change'])) {
            $filter_return_or_change = $this->request->get['filter_return_or_change'];
        }

        $filter_data = array(
            'filter_return_or_change' => $filter_return_or_change,
            'filter_return_id'        => $filter_return_id,
            'filter_order_id'         => $filter_order_id,
            'filter_customer'         => $filter_customer,
            'filter_product'          => $filter_product,
            'filter_model'            => $filter_model,
            'filter_return_status_id' => $filter_return_status_id,
            'filter_return_action_id' => $filter_return_action_id,
            'filter_date_added'       => $filter_date_added,
            'filter_date_modified'    => $filter_date_modified,
            'filter_by'               => $filter_by,
            'sort'                    => $sort,
            'order'                   => $order,
            'start'                   => ($page - 1) * $this->config->get('config_limit_admin'),
            'limit'                   => $this->config->get('config_limit_admin'),
            'page'                    => $page,
        );

        return $filter_data;
    }

}