<?php 
namespace App\Controllers\Admin;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;
use App\Libraries\PHPMailer;
use App\Libraries\PDF;

class Support extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 19 september, 2016
	 * This controller to manage ticket page.
	 * Created karthiga.
	 * @see http://zhyip.com/admin/support/
	 * Last Updated: 19 september, 2016
	 * End
	 * 
	 */

	public function __construct() {
		$this->session = session();
		// admin login only
		if($this->session->get('admin_login')) {
			// form validation library
			// $this->load->library('form_validation');

			// custom encryption
			// $this->load->library('MyEncrypt');
			$myencrypt = new MyEncrypt;
			$this->isSubadmin();
			
		} else {
			$this->session->set('last_page', current_url());
			return redirect()->to('admin/login');
		}

	}

	public function index()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.support_lbl')
		
		);
		$this->data['module_name'] = 'settings';

		$this->data['ticketlist'] = $this->common_model->GetResults('tickets');		

		echo view('admin/tickets',$this->data);

	}
	private function isSubadmin() {
		$this->router = service('router');
		$this->session = session();

		if($this->session->get('user_type') == 'subadmin') {
			$controller = $this->router->controllerName();
			$pages = json_decode($this->session->get('permission'));
		
			if(!in_array(ucfirst($controller), $pages)) {
				return redirect()->to('admin');
			}
		}
	}

	public function ticketdetails($id=''){
	$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}

		
		$this->session = session();
		$this->form_validation = \Config\Services::validation();
		$this->common_model = model('CommonModel');

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.support_lbl')
		
		);
		$this->data['module_name'] = 'settings';
		$this->data['action'] = "admin/support/ticketdetails";

		if($id) {

	        $myencrypt = new MyEncrypt;
			$ticket_no = $myencrypt->decode($id);
	        $condition = "ticket_no = '".$ticket_no."'";
			$this->data['ticket_data'] = $this->common_model->GetRow('tickets',$condition);
			$ticket_dt = $this->common_model->GetRow('tickets',$condition);

	        
	        $condition1 = "uusersid = '".$ticket_dt->uusers_id."'";
			$this->data['username'] = $this->common_model->GetRow('uusers',$condition1);

			$this->data['con_date'] = $this->common_model->GetResults('ticket_conversation',$condition);

			$condition3 = "ticket_no = '".$ticket_no."' order by con_date desc limit 0,1";
			$this->data['lat_date'] = $this->common_model->GetRow('ticket_conversation',$condition3);
		}

		if($this->request->getPost()){

			$this->form_validation->setRule('message', lang("language_lang.ticket_reply_lbl"), 'trim|required');
         
          	// check form validate
			if ($this->form_validation->withRequest($this->request)->run() == TRUE) {

            	if($this->request->getPost('status') == "3"){
               		$status_name = "reopen";
               	} elseif ($this->request->getPost('status') == "2") {
               		$status_name = "fixed";
               	} elseif ($this->request->getPost('status') == "1") {
               		$status_name = "onhold";
               	} elseif ($this->request->getPost('status') == "0") {
               		$status_name = "new";
               	}
               	else{
               		$status_name = "close";
               	}
                $condition3 = "ticket_no = '".$this->request->getPost('tkt')."'";
	            $ticket_subject = $this->common_model->GetRow('tickets',$condition3);

                $condition1 = "uusersid = '".$ticket_subject->uusers_id."'";
                $mail_to = $this->common_model->GetRow('uusers',$condition1);

                $condition2="id = '1'";
                $admin = $this->common_model->GetRow('admin',$condition2);
            
            	$ticket_Data1 = array(
					"adminid"	=>	'0',
                    "uusersid"	    =>	$mail_to->uusersid, 						
					"ticket_no"	=>	$this->request->getPost('tkt'),
					"from_id"   =>  $mail_to->email,
					"to_id"	=>	$admin->email,
					"tkt_message"	=>	$this->request->getPost('message'),
					"tkt_status"	=>	$status_name,
					"con_date"	=>	date('Y-m-d H:i:s'),
					"ip_address"	=>	$this->request->getIpAddress(),
					"status"	=>	$this->request->getPost('status')
				);
				$query_status = $this->db->table('ticket_conversation')->insert($ticket_Data1);

				$subject = 'Ticket';
				$mailid = '14';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[FIRSTNAME]', $mail_to->username, $mail_subject_data->message);
				$message  = str_replace('#ticketno', $this->request->getPost('tkt'), $message);
				$message  = str_replace('#subject', $ticket_subject->subject, $message);
				$message  = str_replace('#status', $status_name, $message);
				$message  = str_replace('#content', $this->request->getPost('message'), $message);
				$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);

				if($mail_subject_data->status=='1'){

				$mail_status = $this->sendmail($mail_to->email, $mail_to->username, $subject, $message,$mail_subject_data->from_mail);
				
				}

				$ticketstatus_update = array(
                   "ticket_status" => $status_name,
                   "status" => $this->request->getPost('status')
				);
               
				$query_update = $this->db->table('tickets')->where('ticket_no',$this->request->getPost('tkt'))->update($ticketstatus_update);
                $myencrypt = new MyEncrypt;
                $ticket_no = $myencrypt->encode($this->request->getPost('tkt'));
				if($query_status) {
					$this->session->setFlashData('success_message', lang('language_lang.tick_reply_success'));
					return redirect()->to('admin/support/ticketdetails/'.$ticket_no);
				} else {
					$this->session->setFlashData('error_message', lang('language_lang.tick_reply_err'));
					return redirect()->to('admin/support/ticketdetails/'.$ticket_no);
				}

			}
          

		}


		echo view('admin/ticketdetails',$this->data);

	}
	public  function deleteticket($id) {

		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = session();
		
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->db = db_connect();
		$this->session = session();
		if($id) {
			$myencrypt = new MyEncrypt;
			// $ticket_no = $myencrypt->decode($id);
	        $condition = "ticket_no = '".$ticket_no."'";
	        $delete_status = $this->db->table('tickets')->where('ticket_id',$id)->delete();

	        
	        // $delete_status = $this->db->table('ticket_conversation')->where('ticket_no',$ticket_no)->delete();
	        if($delete_status) {
	        	$this->session->setFlashData('success_message', lang('language_lang.tick_remove_success'));
	        	return redirect()->to('admin/support');
	        } else {
	        	$this->session->setFlashData('error_message', lang('language_lang.tick_remove_err'));
	        	return redirect()->to('admin/support');
	        }
	    } 
	    else {
	    	return redirect()->to('admin/support');
	    }  
	}

	public function sendmail($useremail, $fullname, $subject, $message,$from_mail) {
        
		// $this->load->library('My_PHPMailer');
		$condition = "settings_name = 'email'";
		$email_setting_data = $this->common_model->GetSettingall_lang($condition);

		foreach ($email_setting_data as $row) {
			$mail_data[$row->site_key] = $row->site_value;
		}

		if($mail_data['email_throw']=='php')
		{
			$mail = new PHPMailer();
	        $mail->isMail();

		} else {

			$mail = new PHPMailer();
	        $mail->IsSMTP(); 
	        $mail->SMTPAuth   = TRUE; 
	        $mail->SMTPSecure = $mail_data['smtp_type'];  
	        $mail->Host       = $mail_data['smtp_hostname'];      
	        $mail->Port       = $mail_data['smtp_portno'];                   
	        $mail->Username   = $mail_data['smtp_username'];  
	        $mail->Password   = $mail_data['smtp_password'];   
		}
		         
        $mail->SetFrom($from_mail, site_info_lang('site_name',$this->session->get('langid')));  
        $mail->AddReplyTo($from_mail,site_info_lang('site_name',$this->session->get('langid')));

        $message  = str_replace('#adminemail', $from_mail, $message);

        $mail->Subject    = $subject;
        $mail->msgHTML($message);
        
        $mail->AddAddress($useremail, $fullname);
        if(!$mail->Send()) {
        	return true;
        } else {
            return true;
        }
	}
	

	

}

