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

// use PHPMailer\PHPMailer\PHPMailer;
// use PHPMailer\PHPMailer\Exception;
class Profile extends BaseController {
	/**
	 * 
	 * Start 
	 * Create Date: 23 Aug, 2016
	 * This controller to manage admin profile page.
	 * Created karthiga.
	 * @see http://zhyip.com/admin/profile/
	 * Last Updated: 23 Aug, 2016
	 * End
	 * 
	 */
	public function __construct() {
		$session = \Config\Services::session();
		$this->common_model = model('CommonModel');
		// admin login only
		if(session()->get('admin_login'))
		{
			// form validation library
			// $this->load->library('form_validation');
		} else {
			if(isset($_COOKIE['remember_token'])) {
				$myencrypt = new MyEncrypt;
				$token_value = $myencrypt->decode($this->input->cookie('remember_token'));
				$this->isCookie($token_value);	

			} else {
				session()->set('last_page', current_url());
				redirect()->to('admin/login');
			}
		}
 	}

 	private function isCookie($values) {
		$value = explode('|', $values);
		$result = $this->common_model->getPassword($value[0]);
		$hashed_password = $result->password;
		if(crypt(urlencode($value[1]), $hashed_password)) {
			$array = array(
				"logged_in" => TRUE,
				"userid" => $result->id,
				"admin_login" => TRUE
			);
			$session->set($array);

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

	public function index()
	{   
		$this->db = db_connect();
		$session = \Config\Services::session();
		if(!$session->get('admin_login')){
			return redirect()->to(site_url('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.admin_profile_title')
		);
		$this->data['module_name'] = 'settings';
		$condition="id = '".$session->get('userid')."'";
        $this->data['admin'] = $this->common_model->GetRow('admin',$condition);
        $this->data['action'] = 'admin/profile';
		if($this->request->getPost()) {
            $validation =  \Config\Services::validation();
            $validation->setRules([
				'username' => ['label' => lang("language_lang.admin_username_lbl"), 'rules' => 'trim|required|trim|required|alpha_dash'],
				'email' => ['label' => lang("language_lang.admin_email_lbl"), 'rules' => 'trim|required|valid_email'],
				'contact_email' => ['label' => lang("language_lang.admin_contact_lbl"), 'rules' => 'trim|required|valid_email'],
				'contact_num' => ['label' => lang("language_lang.admin_contactnum_lbl"), 'rules' => 'trim|required|numeric']
			]);
			// $this->form_validation->set_rules('username', lang("language_lang.admin_username_lbl"), 'trim|required|alpha_dash');
			// $this->form_validation->set_rules('email', lang("language_lang.admin_email_lbl"), 'trim|required|valid_email');
			// $this->form_validation->set_rules('contact_email', lang("language_lang.admin_contact_lbl"), 'trim|required|valid_email');
			// $this->form_validation->set_rules('contact_num', lang("language_lang.admin_contactnum_lbl"), 'trim|required|numeric');
			$logo=$_FILES['profile_pic']['tmp_name'];
			if($logo!='') {
				$validation->setRules([
				'profile_pic' => ['label' => lang("language_lang.admin_profile_pic"), 'rules' => 'trim|max_dims[profile_pic,250,250]|ext_in[profile_pic,jpg,png,gif,jpeg]|is_image[profile_pic]']]);
				// $this->form_validation->set_rules('profile_pic', lang("language_lang.admin_profile_pic"), 'trim|callback_validate_image');
			}

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

					$prof_img = array(
						"profile_pic"	=>	$upload_file
					);
					$query_pro_status = $this->db->table('admin')->where('id',$session->get('userid'))->update($prof_img);
					
				
				}

                if($this->request->getPost())
                {
                 	$admin_data = array(
						"username"	=>	$this->request->getPost('username'),
						"email"	=>	$this->request->getPost('email'),
						"contact_email"	=>	$this->request->getPost('contact_email'),
						"contact_num"	=>	$this->request->getPost('contact_num'),
						"modifydate" => date('Y-m-d h:i:s')
					);
					$query_status = $this->db->table('admin')->where('id',$session->get('userid'))->update($admin_data);

					$condition="id = '".$session->get('userid')."'";
                    $admin = $this->common_model->GetRow('admin',$condition);

					// $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(true);
				 //        $mail->isMail();

					// } else {
					// 	$mail = new PHPMailer(true);
				 //        $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 = \Config\Services::email();         
			        $mail->SetFrom($mail_data['admin_email'], site_info_lang('site_name',$session->get('langid')));  
			        $mail->setReplyTo($mail_data['admin_email'],site_info_lang('site_name',$session->get('langid')));
			        $mailid = '4';
			        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
					$message  = str_replace('[FIRSTNAME]', $admin->username, $mail_subject_data->message);
					$message  = str_replace('#adminemail', $mail_data['admin_email'], $message);
					$message  = str_replace('#sitename', site_info_lang('site_name',$session->get('langid')), $message);
                     
			        $mail->Subject    = "Reset password success";
			        $mail->setMessage($message);
			        $mail->AltBody    = "Your Password has been reseted Successfully";
			        
			        // $mail->AddAddress($admin->email, $admin->username);

			        if(!$mail->Send()) {
			            $data["message"] = "Error: " . $mail->ErrorInfo;
			        } else {
			            $data["message"] = "Message sent correctly!";
			        }

                }

                if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.admin_profile_success'));
					return redirect()->to(site_url('admin/profile'));
				} else {
					$session->setFlashData('error_message', 'demo version cannot be update');
					return redirect()->to(site_url('admin/profile'));
				}
            
		    }
			
		}
		echo view('admin/profile',$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;
		}
		
	}

	public function changepassword(){
		
		$session = \Config\Services::session();
		if(!$session->get('admin_login')){
			return redirect()->to(site_url('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.admin_passwd_titlte')
		);

		$this->data['module_name'] = 'settings';
		$condition="id = '".$session->get('userid')."'";
        $this->data['admin'] = $this->common_model->GetRow('admin',$condition);

        $this->data['action'] = base_url().'admin/changepassword';

		if($this->request->getPost())
		{
			$originalpwd = $this->request->getPost('newpwd');
			$password = crypt(urlencode($this->request->getPost('newpwd')));

			$pwd_data = array(
				"password"	=>	$password
			);
            $this->db = db_connect();
			
		    $query_status = $this->db->table('admin')->where('id',$session->get('userid'))->update($pwd_data);

            $condition="id = '".$session->get('userid')."'";
            // $this->data['admin'] = $this->common_model->GetRow('admin',$condition);
            $admin = $this->common_model->GetRow('admin',$condition);
		    $link = base_url().'admin/login';

			// $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')));
	  //       $mailid = '3';
	  //       $mail_subject_data = $this->common_model->getMailTemplate($mailid);
			// $message  = str_replace('[FIRSTNAME]', $admin->username, $mail_subject_data->message);
			// $message  = str_replace('#verfyurl', $link, $message);
			// $message  = str_replace('#sitename', site_info_lang('site_name',$session->get('langid')), $message);
             
	  //       $mail->Subject    = "Reset password success";
	  //       $mail->msgHTML($message);
	  //       $mail->AltBody    = "Your Password has been reseted Successfully";

	  //       $mail->AddAddress($admin->email, $admin->username);

	  //       if(!$mail->Send()) {
	  //           $data["message"] = "Error: " . $mail->ErrorInfo;
	  //       } else {
	  //           $data["message"] = "Message sent correctly!";
	  //       }

    		if($query_status) {
				$session->setFlashData('success_message', lang('language_lang.admin_changepwd_success'));
				return redirect()->to('admin/changepassword');
			} else {
				$session->setFlashData('error_message', lang('language_lang.admin_changepwd_error'));
				return redirect()->to('admin/changepassword');
			}
		}

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

    public function validpassword()
    {
    	$session = \Config\Services::session();
		$post_pwd = $this->request->getPost('current');
		$condition="id = '".$session->get('userid')."'";
		$uemail = $this->common_model->GetRow('admin', $condition);
		$hashed_password = $uemail->password;
	 	if ($hashed_password == crypt(urlencode($this->request->getPost('current')), $hashed_password)) {
            $json['valid'] = true;
		}
		else {
			$json['valid'] = false;
		}
		
		echo json_encode($json);
    }
	
}

