<?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 Subadmin extends BaseController {
	/**
	 * 
	 * Start 
	 * Create Date: 4 October, 2016
	 * This controller to manage subadmin page.
	 * Created karthiga.
	 * @see http://zhyip.com/admin/subadmin/
	 * Last Updated: 2 November, 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;
			if($this->session->get('userid') != '1'){

				return redirect()->to('admin');

			}
		} else {
			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.subadminhistory_log')
		
		);
		$this->data['module_name'] = 'settings';
		$condition = "id != '1'";
		$this->data['subadmin_data'] = $this->common_model->GetResults('admin',$condition);
        

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

	}

	public function uploadFile($path, $image) {
		if ($image->isValid() && ! $image->hasMoved()) {
			$newName = $image->getRandomName();
			$image->move('./'.$path, $newName);
			return $image->getName();
		}
		return "";
	}

	public function add() {
		$this->db = db_connect();
		$this->common_model = model('CommonModel');
        $this->session = session();
        $this->form_validation = \Config\Services::validation();

		$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.subadminhistory_log')
		);
		
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/subadmin/add';
        $this->data['user_list'] = array('Sitesettings','Usersettings','Loginsettings','Emailsettings','Withdrawsettings','Referralsettings','Paymentsettings','Currencysettings','Langsettings','footersettings','adminsettings'); 
        $this->data['user_list1'] = array('Cms','Faq','News','Message','Ip','Mailtemplate','Slider','Sendnewsletter','Checkip','Loghistory'); 

        // $this->data['user_list5'] = array('Finance','History','Reports'); 
        $this->data['finance'] = array('Finance/bonus','Finance/penalty','Finance/pendingpayouts');
        $this->data['history'] = array('History/deposit','History/payouts','History/bonus','History/earnings','History/adminearnings'); 
        $this->data['reports'] = array('Reports/deposit','Reports/payouts','Reports/bonus','Reports/adminearnings'); 
        $this->data['user_list2'] = array('Users'); 
       // $this->data['user_list3'] = array('Package');
        $this->data['user_list4'] = array('Support','Backup'); 
       $this->data['user_list6'] = array('Subadmin');
        

		if($this->request->getPost()) {
			// form validation

			$this->form_validation->setRule('username', lang("language_lang.subadmin_username"), 'trim|required|alpha_dash|is_unique[admin.username]');
			$this->form_validation->setRule('email', lang("language_lang.admin_email_lbl"), 'trim|required|valid_email|is_unique[admin.email]');
			$this->form_validation->setRule('newpwd', lang("language_lang.change_pwd_sub"), 'trim|required|matches[confirm]');
			$this->form_validation->setRule('confirm', lang("language_lang.admin_confirm_pwd"), 'trim|required');
			$this->form_validation->setRule('contact_email', lang("language_lang.admin_contact_lbl"), 'trim|required|valid_email');
			$this->form_validation->setRule('contact_num', lang("language_lang.admin_contactnum_lbl"), 'trim|required|numeric');
			// $this->form_validation->setRule('user_id[]', lang("language_lang.subadmin_previlage"), 'trim|required');

			$logo=$_FILES['profile_pic']['tmp_name'];
			if($logo!='') {
				$this->form_validation->setRule('profile_pic', lang("language_lang.admin_profile_pic"), 'trim|ext_in[profile_pic,jpg,png,gif,jpeg]|is_image[profile_pic]');
			}
            
			// check form validate
			if ($this->form_validation->withRequest($this->request)->run() == TRUE) {


				$userlist = json_encode($this->request->getPost('user_id')); 
				$originalpwd = $this->request->getPost('newpwd');
				$password = crypt(urlencode($this->request->getPost('newpwd')));

			 	$subadmin_data = array(
					"username"	=>	ucfirst($this->request->getPost('username')),
					"password" => $password,
					"email"	=>	$this->request->getPost('email'),
					"contact_email"     =>  $this->request->getPost('contact_email'),
					"contact_num"	=>	$this->request->getPost('contact_num'),
					"permission" => $userlist,
					"modifydate" => date('Y-m-d h:i:s'),
					"date" => date('Y-m-d h:i:s'),
					"type" => "subadmin",
					"profile_pic"=>"avatar.png",
					"status"	=>	($this->request->getPost('message_status')) ? '1' : '0' 
				);

				if($logo!='') {
				
					// $admin_profile_file = $this->upload->data();
					$path 				= 'content/profile/';
					$file 			    = $this->request->getFile('profile_pic');
					$upload_file 	    = $this->uploadFile($path, $file);

					$prof_img = array(
						"profile_pic"	=>	$upload_file
					);
					$prof_img = implode(',', $prof_img);
					$subadmin_data["profile_pic"] = $prof_img;
				}
					
				$query_status = $this->db->table('admin')->insert($subadmin_data);

				$subject = 'Subadmin account created successfully';
				$mailid = '2';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[FIRSTNAME]', ucfirst($this->request->getPost('username')), $mail_subject_data->message);
				$message  = str_replace('#sitename', 'ZHYIP', $message);

				$mail_status = $this->sendmail($this->request->getPost('contact_email'), $this->request->getPost('username'), $subject, $message,$mail_subject_data->from_mail);

				if($query_status) {
					$this->session->setFlashData('success_message', lang('language_lang.subadmin_success_message'));
					return redirect()->to('admin/subadmin');
				} else {
					$this->session->setFlashData('error_message', lang('language_lang.subadmin_error_message'));
					return redirect()->to('admin/subadmin');
				}
				
			} 
			
		}
		echo view('admin/addsubadmin',$this->data);
	}

	public function edit($id=''){
		$this->db = db_connect();
		$this->common_model = model('CommonModel');
		 $this->session = session();
        $this->form_validation = \Config\Services::validation();
		
		$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.subadminhistory_log')
		);
		
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/subadmin/edit';
       
          $this->data['user_list'] = array('Sitesettings','Usersettings','Loginsettings','Emailsettings','Withdrawsettings','Referralsettings','Paymentsettings','Currencysettings','Langsettings','footersettings','adminsettings'); 
        $this->data['user_list1'] = array('Cms','Faq','News','Message','Ip','Mailtemplate','Slider','Sendnewsletter','Checkip','Loghistory'); 

        // $this->data['user_list5'] = array('Finance','History','Reports'); 
        $this->data['finance'] = array('Finance/bonus','Finance/penalty','Finance/pendingpayouts');
        $this->data['history'] = array('History/deposit','History/payouts','History/bonus','History/earnings','History/adminearnings'); 
        $this->data['reports'] = array('Reports/deposit','Reports/payouts','Reports/bonus','Reports/adminearnings'); 
        $this->data['user_list2'] = array('Users'); 
       // $this->data['user_list3'] = array('Package');
        $this->data['user_list4'] = array('Support','Backup'); 
        //$this->data['user_list6'] = array('Subadmin');

		if($id) {
			$myencrypt = new MyEncrypt;
			$subadmin_id = $myencrypt->decode($id);
			$condition = "id = '".$subadmin_id."'";
			$this->data['subadmin_data'] = $this->common_model->GetRow('admin', $condition);
		}

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

			// form validation
            $id = $this->request->getPost('id');
			$this->form_validation->setRule('username', lang("language_lang.subadmin_username"), 'trim|required|alpha_dash|edit_unique_username['.$id.']');
			$this->form_validation->setRule('email', lang("language_lang.admin_email_lbl"), 'trim|required|valid_email|edit_unique_email['.$id.']');
			$this->form_validation->setRule('contact_email', lang("language_lang.admin_contact_lbl"), 'trim|required|valid_email');
			$this->form_validation->setRule('contact_num', lang("language_lang.admin_contactnum_lbl"), 'trim|required|numeric');
			// $this->form_validation->setRule('user_id[]', lang("language_lang.subadmin_previlage"), 'trim|required');

			$file=$_FILES['profile_pic']['tmp_name'];
			if($file!='') {
			$this->form_validation->setRule('profile_pic', lang("language_lang.admin_profile_pic"), 'trim|ext_in[profile_pic,jpg,png,gif,jpeg]|is_image[profile_pic]');
			}

			
            
			// check form validate
			if ($this->form_validation->withRequest($this->request)->run() == TRUE) {

				if($file!='') {
					
					// $admin_profile_file = $this->upload->data();
					$path 				= 'content/profile/';
					$file 			    = $this->request->getFile('profile_pic');
					$upload_file 	    = $this->uploadFile($path, $file);
					$prof_img = array(
						"profile_pic"	=>	$upload_file
					);

				
					$query_status = $this->db->table('admin')->where('id',$id)->update($prof_img);
				}

				$userlist = json_encode($this->request->getPost('user_id'));


				$subadmin_data = array(
					"username"	=>	ucfirst($this->request->getPost('username')),
					"email"	=>	$this->request->getPost('email'),
					"contact_email"     =>  $this->request->getPost('contact_email'),
					"contact_num"	=>	$this->request->getPost('contact_num'),
					"permission" => $userlist,
					"modifydate" => date('Y-m-d h:i:s'),
					"type" => "subadmin",
					"status"	=>	($this->request->getPost('message_status')) ? '1' : '0' 
				);
				$query_status = $this->db->table('admin')->where('id',$id)->update($subadmin_data);

				$subject = 'Subadmin account updated successfully';
				$mailid = '4';
				$mail_subject_data = $this->common_model->getMailTemplate($mailid);
				$message  = str_replace('[FIRSTNAME]', ucfirst($this->request->getPost('username')), $mail_subject_data->message);
				$message  = str_replace('#sitename', 'ZHYIP', $message);

				$mail_status = $this->sendmail($this->request->getPost('contact_email'), $this->request->getPost('username'), $subject, $message,$mail_subject_data->from_mail);

				if($query_status) {
					$this->session->setFlashData('success_message', lang('language_lang.subadmin_success_message'));
					return redirect()->to('admin/subadmin');
				} else {
					$this->session->setFlashData('error_message', lang('language_lang.subadmin_error_message'));
					return redirect()->to('admin/subadmin');
				}
			}
			
			
		}
		echo view('admin/addsubadmin',$this->data);
	}

	/* validate image value */
	public function validate_image($str)
	{
		
		$config['upload_path'] = './content/profile/';
		$config['allowed_types'] = 'gif|jpg|png|jpeg';
		$config['max_width']  = '250';
        $config['max_height']  = '250';
		$config['encrypt_name'] = TRUE;
		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload('profile_pic')) {
			$this->form_validation->set_message('validate_image', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
			return false;
		} else {
			return true;
		}
		
	}


	/* validate username value */
	public function edit_unique_username($str,$id)
	{
		
		$this->db->select('username');
		$this->db->from('admin');
		$this->db->where('id !='.$id);
		$this->db->where('username',$str);

		$query = $this->db->get();
		if ($query->num_rows()>0) {
			$this->form_validation->set_message('username', '<p><em class="text-danger">'.lang('language_lang.sub_admin_username_invalid').'</em></p>');
			return false;
		} else {
			return true;
		}
		
	}


	/* validate email value */
	public function edit_unique_email($str,$id)
	{
		$this->db->select('email');
		$this->db->from('admin');
		$this->db->where('id !='.$id);
		$this->db->where('email',$str);

		$query = $this->db->get();
		if ($query->num_rows()>0) {
			$this->form_validation->set_message('email', '<p><em class="text-danger">'.lang('language_lang.user_emailid_invalid').'</em></p>');
			return false;
		} else {
			return true;
		}
		
	}


	public function delete($id) {
		$this->session = session();
		$this->db = db_connect();
		$myencrypt = new MyEncrypt;
		$subadmin_id = $myencrypt->decode($id);
		if(isset($subadmin_id)){
			
		
			$delete_status = $this->db->table('admin')->where('id',$subadmin_id)->delete();

			if($delete_status) {
				$this->session->setFlashData('success_message', lang('language_lang.subadmin_delete_success_message'));
				return redirect()->to('admin/subadmin');
			} else {
				$this->session->setFlashData('error_message', lang('language_lang.subadmin_delete_error_message'));
				return redirect()->to('admin/subadmin');
			}	
			
		} else {
			return redirect()->to('admin/subadmin');
		}
	}

	public function changeStatus($id) {
		$this->session = session();
		$this->db = db_connect();
		
		$myencrypt = new MyEncrypt;
		$subadmin_id = $myencrypt->decode($id);
	
		$cur_up_data = array(
			"status" => '0'
		);

		$update_status = $this->db->table('admin')->where('id',$subadmin_id)->update($cur_up_data);

		if($update_status){
			$this->session->setFlashData('success_message', lang('language_lang.Subadmin_default_success'));
            return redirect()->to('admin/subadmin');
		} else {
			$this->session->setFlashData('error_message', lang('language_lang.Subadmin_default_error'));
			return redirect()->to('admin/subadmin');
		}

		
	}
	public function changeActiveStatus($id) {
$this->session = session();
		$this->db = db_connect();
		$myencrypt = new MyEncrypt;
		$subadmin_id = $myencrypt->decode($id);
		
		$cur_up_data = array(
			"status" => '1'
		);
		$update_status = $this->db->table('admin')->where('id',$subadmin_id)->update($cur_up_data);

		if($update_status){
			$this->session->setFlashData('success_message', lang('language_lang.Subadmin_default_success'));
			return redirect()->to('admin/subadmin');
		} else {
			$this->session->setFlashData('error_message', lang('language_lang.Subadmin_default_error'));
		    return redirect()->to('admin/subadmin');
		}
		
	}

	public function sendmail($useremail, $fullname, $subject, $message,$from_mail) {
		return true;
	}
	

}

