<?php
class ControllerCustomerTicket extends Controller
{
	
	public function index()
	{
        $this->load->model('customer/ticket');
		$this->document->setTitle("Talepler");
		$this->getList();
	}

	public function getList(){

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

        $url = '';
        

        $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' => 'Talepler',
			'href' => $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, true)
        );
        
        $data['tickets'] = array();

        $filter_data = array(
			'start'                    => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'                    => $this->config->get('config_limit_admin')
        );
        
        $ticket_total = $this->model_customer_ticket->getTotalTickets($filter_data);

        $results = $this->model_customer_ticket->getTickets($filter_data);
        

        foreach ($results as $result) {
            $data['tickets'][] = array(
                'ticket_id'     => $result['ticket_id'],
                'user'          => $result['firstname'] . ' ' .$result['lastname'],
                'user_mail'     => $result['email'],
                'subject'       => $result['subject'],
                'add_time'      => $result['add_time'],
                'status'        => $result['status'],
                'answer_link'   => $this->url->link('customer/ticket/answer', 'token=' . $this->session->data['token'] . '&ticket_id=' . $result['ticket_id'] . $url, true),
            );
        }

        $data['heading_title'] = 'Talepler';
        $data['text_list'] = 'Talep Listesi';
        $data['text_no_results'] = 'Gösterilecek kayıt bulunamadı';


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

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

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



		$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 .'customer/ticket_list.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'customer/ticket_list', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'customer/ticket_list', $data));
		}
    }
    
    public function answer(){

        $ticket_id = $this->request->get['ticket_id'];

        $this->load->model('customer/ticket');
        $this->document->setTitle("Talepler");
        
        $url = '';

        $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' => 'Talepler',
			'href' => $this->url->link('customer/customer', 'token=' . $this->session->data['token'] . $url, true)
        );

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

        $ticket_info = $this->model_customer_ticket->getTicket($ticket_id);

        $data['ticket_id'] =  $ticket_info['ticket_id'];

        $data['answers'][] = array(
            'answer_id'     => 0,
            'ticket_id'     => $ticket_info['ticket_id'],
            'user_id'       => $ticket_info['user_id'],
            'answer'        => $ticket_info['message'],
            'add_time'      => $ticket_info['add_time'],
        );

        $answers = $this->model_customer_ticket->getAnswers($ticket_id);
        foreach($answers as $answer){
            $data['answers'][] = array(
                'answer_id'     => $answer['answer_id'],
                'ticket_id'     => $answer['ticket_id'],
                'user_id'       => $answer['user_id'],
                'answer'        => $answer['answer'],
                'add_time'      => $answer['add_time'],
            );
        }

        $data['heading_title'] = 'Talepler';
        $data['text_list'] = 'Talep Listesi';
        $data['text_no_results'] = 'Bu talebe hiç cevap yazılmamış';

        $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 .'customer/ticket_answer.tpl')){
		    $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'customer/ticket_answer', $data));
		}else{ 
		    $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'customer/ticket_answer', $data));
		}
    }

    public function saveanswer(){

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

        $json = array();
        if(isset($this->request->post['answer'])){
            $answer = $this->request->post['answer'];
            $data = array(
                'answer' => $this->request->post['answer'],
                'ticket_id' => $this->request->post['ticket_id'],
            );

            $answer_id = $this->model_customer_ticket->addAnswer($data);
            $json['message'] = "Cevap İletildi"; 
            $this->sendMail($this->request->post['ticket_id'],$answer_id);

        }else{
            $json['error'] = "Hata oluştu"; 
        }

        $this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));


    }

    public function sendMail($ticket_id, $answer_id){

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

		$ticket = $this->db->query("SELECT * FROM ". DB_PREFIX ."ticket WHERE ticket_id='". (int)$ticket_id ."' ")->row;
        $user = $this->model_customer_customer->getCustomer($ticket['user_id']);

		$subject =  'Destek Talebi - Talebe Cevap Yazıldı';
		

        $text = 'Talep No: '.  $ticket['ticket_id'].'
';        
		$text = 'Konu: '.  $ticket['subject'].'
';
        $text .= 'İçerik: '. $ticket['message'] .'
';        
		$text .= 'Tarih: '. $ticket['add_time'] .'
';


		$answer = $this->db->query("SELECT * FROM ". DB_PREFIX ."ticket_answer WHERE answer_id='". (int)$answer_id ."' ")->row;
		$text .= 'Yazılan Cevap: ' . $answer['answer'].' 
';
		

        $text .= 'Mesaj: Talep sistem yöneticisine iletilmiştir! 
';
        

        $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($user['email']);
		$mail->setFrom($this->config->get('config_email'));
		$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
		$mail->setSubject(html_entity_decode($this->config->get('config_name') . '-' . $subject, ENT_QUOTES, 'UTF-8'));

		$mail->setText($text);
        $mail->send();

		$mail->setTo($this->config->get('config_email'));
		$mail->setFrom($this->config->get('config_email'));
		$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
		$mail->setSubject(html_entity_decode($this->config->get('config_name') . '-' . $subject, ENT_QUOTES, 'UTF-8'));

		$mail->setText($text);
        $mail->send();
        

	}
}