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

class Sendnewsletter extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 20 September, 2016
	 * This controller to manage user side sendnewsletter.
	 * Created karthiga.
	 * @see http://zhyip.com/
	 * Last Updated: 18 November, 2016
	 * End
	 * 
	 */

	public function __construct() {
		$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');
		}
		// admin login only
		if($session->get('admin_login')) {
			// form validation library

			// custom encryption
			$myencrypt = new MyEncrypt;
			$this->isSubadmin();

		} else {
			return redirect()->to('admin/login');
		}

	}

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

	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->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.text_extra')
		
		);
		$this->data['flag']=0;
		$this->data['module_name'] = 'settings';
		$this->data['uusers_list'] = $this->common_model->GetResults('uusers');
		$this->data['action'] =  'admin/sendnewsletter';

		if($this->request->getPost()) {
			
			// form validation
			$validation->setRules([
				'message' => ['label' => lang("language_lang.lbl_mail_message"), 'rules' => 'trim|required'],
				'subject' => ['label' => lang("language_lang.lbl_mail_subject"), 'rules' => 'trim|required']
			]);
		 	// $this->form_validation->set_rules('message', lang("language_lang.lbl_mail_message"), 'trim|required');
    //      	$this->form_validation->set_rules('subject', lang("language_lang.lbl_mail_subject"), 'trim|required');
            if($this->request->getPost('select_user') && $this->request->getPost('userlist')){
            	$validation->setRules([
				'select_user' => ['label' => lang("language_lang.bonus_usertype"), 'rules' => 'trim|required'],
				'userlist' => ['label' => lang("language_lang.bonus_select_user"), 'rules' => 'trim|required']
			]);
	         	// $this->form_validation->set_rules('select_user',lang("language_lang.bonus_usertype"),'required');
	         	// $this->form_validation->set_rules('userlist',lang("language_lang.bonus_select_user"),'required'); 
            }

            if ($validation->withRequest($this->request)->run() == TRUE) {

            	if($this->request->getPost('userlist')){
                     $userlist = $this->request->getPost('userlist'); 

                     foreach ($userlist as $row => $value) {

                     	    $condition = "uusersid = '".$value."'";
						    $user = $this->common_model->GetRow('uusers', $condition);

						    $useremail = $user->email;
						    $fullname = $user->fullname;
						    $subject = $this->request->getPost('subject');
						    $message = $this->request->getPost('message');
							$mail_status = $this->sendmail($useremail, $fullname, $subject, $message);
					}
				    if($mail_status) {
						$session->setFlashData('success_message', lang('language_lang.sendnews_default_success'));
						return redirect()->to('admin/sendnewsletter');
					} else {
						$session->setFlashData('error_message', lang('language_lang.sendnews_default_error'));
						return redirect()->to('admin/sendnewsletter');
					}

            	}	
            	

                
            }
			
		}

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

	}

	public function sendmail($useremail, $fullname, $subject, $message) {
        $session =session();
		// $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($mail_data['admin_email'], site_info_lang('site_name',$session->get('langid')));  
        $mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',$session->get('langid')));

        $message  = str_replace('#adminemail', $mail_data['admin_email'], $message);

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

	public function list_user($id)
	{
		$this->db = db_connect();
		$this->common_model = model('CommonModel');
		if($id != '4')
		{
	      $condition = 'status = '."'".$id."'";
	    }
	    else
	    {
		  $condition = "status in('1','0')";
	    }	
	      $uusers_list = $this->common_model->GetResults('uusers',$condition);
		      foreach ($uusers_list as $row) {
		      	echo "<option value='".$row->uusersid."'>".ucfirst($row->email)."</option>";
			  }

	}


	

}

