<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Account extends CI_Controller {
	public function __construct(){
		parent::__construct();
		checkDashboard();
		//$this->load->library('flashdata');
		//$this->load->library('layouts');
		$this->load->model('project/projectmain','projmain');
		$this->load->model('account/accountmain','accmain');
		$this->lang->load('account', $this->session->userdata('language'));
		$this->projectID = $this->session->userdata('projectID');
		$this->session->set_userdata('menu', "account");
	}
	
	public function index() {
		$user = $this->session->userdata('logged_in');
		
		$data['respond']['type'] = NULL;
		$data['respond']['message'] = NULL;
		if($flashdata = $this->flashdata->get(NULL, FALSE)) {
			$data['respond']['type'] = (isset($flashdata['type'])) ? strtoupper($flashdata['type']) : NULL;
			$data['respond']['message'] = (isset($flashdata['message'])) ? $flashdata['message'] : NULL;
		}
		
		$data['account'] = $this->accmain->getAccount($user['userID']);
		$data['billing'] = $this->accmain->getMyBillingInfo($user['userID']);
		$data['organization'] = $this->accmain->getUserOrganizationDetail($user['userID']);
		$data['userID'] = $user['userID'];
		
		$this->layouts->view('account/index', array(), $data);
	}
	
	public function save() {
    $type = $_POST['type'];
    $ID = $_POST['ID'];
    $user = $_POST['user'];
		
		$data = NULL;
		$proceed = TRUE;
		$message = NULL;
		
		if(!$this->accmain->checkAccountExists($user)) { $proceed = FALSE; $message[] = "Account does not exist"; }	
		
		if($proceed) {
			if($type == 'ACCOUNT') {
				$data['username'] = $_POST['account']['username'];
				$data['email'] = $_POST['account']['email'];
				$resetImageFile = $_POST['account']['resetImageFile'];
				
				if(trim( $data['username'] ) === "") { $proceed = FALSE; $message[] = "Please enter your full name."; }
				
				if($proceed) {					
					if($this->accmain->saveAccount($data, $user)) {
						if($resetImageFile) {
							if($this->accmain->resetImageFile($user)) {
								$proceed = TRUE;
								$message = NULL;
							} else {
								$proceed = FALSE;
								$message[] = "Fail to reset profile image";
							}
						} else {
							if($_FILES && !empty($_FILES) && isset($_FILES['account_imageFile']) && $_FILES['account_imageFile']['size']) {
								$r = $this->uploadProfileImage($user);
								if($r['message'] == 'SUCCESS') {
									if($this->accmain->saveImageFile($user, $r['file'])) {
										$proceed = TRUE;
										$message = NULL;
									} else {
										$proceed = FALSE;
										$message[] = "Fail to save profile image";
									}
								} else {
									$proceed = FALSE;
									$message[] = "Fail to upload profile image";
								}
							} else {
								$proceed = TRUE;
								$message = NULL;
							}
						}
					} else {
						$proceed = FALSE;
						$message[] = "Fail to save account detail due to technical issue";
					}
				}
			}
			
			if($type == 'PASSWORD') {
				$data['oldpassword'] = $_POST['password']['oldpassword']; 
				$data['newpassword'] = $_POST['password']['newpassword']; 
				$data['confirmpassword'] = $_POST['password']['confirmpassword'];
				
				if(trim( $data['oldpassword'] ) === "") { $proceed = FALSE; $message[] = "Please enter your old password."; }
				if(trim( $data['newpassword'] ) === "") { $proceed = FALSE; $message[] = "Please enter your new password."; }
				if(trim( $data['confirmpassword'] ) === "") { $proceed = FALSE; $message[] = "Please enter your new password confirmation."; }
		
				if($proceed) {
					$oldpass = $this->accmain->getOldPassword($user);
					if(md5(trim($data['oldpassword'])) == trim($oldpass)) {
						if(trim($data['newpassword']) != trim($data['confirmpassword'])) {
							$proceed = FALSE;
							$message[] = "Password confirmation not matched.";
						} else {
							$proceed = TRUE;
							$message = NULL;
						}
					} else {
						$proceed = FALSE;
						$message[] = "Old password is not correct.";
					}
				}
				
				if($proceed) {
					if($this->accmain->savePassword($user, trim($data['newpassword']))) {
						$proceed = TRUE;
						$message = NULL;
					} else {
						$proceed = FALSE;
						$message[] = "Fail to save new password due to technical issue";
					}
				}
			}
			
			if($type == 'BILLING') {
				$data['phoneNo'] = $_POST['billing']['phoneNo'];
				$data['faxNo'] = $_POST['billing']['faxNo'];
				$data['email'] = $_POST['billing']['email'];
				$data['address'] = $_POST['billing']['address'];
				$data['postcode'] = $_POST['billing']['postcode'];
				$data['city'] = $_POST['billing']['city'];
				$data['country'] = $_POST['billing']['country'];
				$data['state'] = $_POST['billing']['state'];
				
				if(trim( $data['phoneNo'] ) === "") { $proceed = FALSE; $message[] = "Please select your billing phone number."; }
				if(trim( $data['email'] ) === "") { $proceed = FALSE; $message[] = "Please enter your billing email."; }
				if(trim( $data['address'] ) === "") { $proceed = FALSE; $message[] = "Please enter your billing address."; }
				if(trim( $data['postcode'] ) === "") { $proceed = FALSE; $message[] = "Please enter your billing postcode."; }
				if(trim( $data['city'] ) === "") { $proceed = FALSE; $message[] = "Please enter your billing city."; }
				if(trim( $data['country'] ) === "") { $proceed = FALSE; $message[] = "Please select your billing country."; }				
				
				if($proceed) {		
					if($this->accmain->saveBilling($data, $user)) {
						$proceed = TRUE;
						$message = NULL;
					} else {
						$proceed = FALSE;
						$message[] = "Fail to save billing detail due to technical issue";
					}
				}
			}
			
			if($type == 'ORGANIZATION') {										
				$data['name'] = $_POST['organization']['name'];
				$data['regNo'] = $_POST['organization']['regNo'];
				$data['phoneNo'] = $_POST['organization']['phoneNo'];
				$data['faxNo'] = $_POST['organization']['faxNo'];
				$data['website'] = $_POST['organization']['website'];
				$data['email'] = $_POST['organization']['email'];
				$data['address'] = $_POST['organization']['address'];
				$data['postcode'] = $_POST['organization']['postcode'];
				$data['city'] = $_POST['organization']['city'];
				$data['country'] = $_POST['organization']['country'];
				$data['state'] = $_POST['organization']['state'];
				$resetLogoImage = $_POST['organization']['resetLogoImage'];
				
				if(trim( $data['name'] ) === "") { $proceed = FALSE; $message[] = "Please enter your organization name."; }		
				
				if($proceed) {		
					if($this->accmain->saveOrganization($data, $user)) {
						if($resetLogoImage) {
							if($this->accmain->resetLogoImage($user)) {
								$proceed = TRUE;
								$message = NULL;
							} else {
								$proceed = FALSE;
								$message[] = "Fail to reset logo image";
							}
						} else {
							if($_FILES && !empty($_FILES) && isset($_FILES['organization_logoImage']) && $_FILES['organization_logoImage']['size']) {
								$r = $this->uploadLogoImage($user);
								if($r['message'] == 'SUCCESS') {
									if($this->accmain->saveLogoImage($user, $r['file'])) {
										$proceed = TRUE;
										$message = NULL;
									} else {
										$proceed = FALSE;
										$message[] = "Fail to save logo image";
									}
								} else {
									$proceed = FALSE;
									$message[] = "Fail to upload logo image";
								}
							} else {
								$proceed = TRUE;
								$message = NULL;
							}
						}
					} else {
						$proceed = FALSE;
						$message[] = "Fail to save organization detail due to technical issue";
					}
				}
			}
		}
		
		if(!$proceed && $message && !empty($message)) {
			$this->flashdata->clear();
			$this->flashdata->set(implode("<br />",$message),'message');
			$this->flashdata->set('FAIL','type');
		} else {
			$this->flashdata->clear();
			$this->flashdata->set('SUCCESS','message');
			$this->flashdata->set('SUCCESS','type');
		}
				
		$url = base_url()."account";
		redirect($url);
	}
	
	public function delete($p) {
		if(!$p) redirect(base_url()."account/setup");
		
		if(!$this->accmain->checkAccountExists($p)) {
			$this->flashdata->set('Account does not exist','message');
			$this->flashdata->set('FAIL','type');
			redirect(base_url()."account/setup");
		}
		
		if(!$this->accmain->deleteAccount($p)) {
			$this->flashdata->set('Fail to delete account','message');
			$this->flashdata->set('FAIL','type');
			redirect(base_url()."account/detail/".$p);
		}
		
		redirect(base_url()."account/setup");
		
	}
	
	/**
	* AJAX
	*/
	public function checkemailexistsajax() {
		$ID = (isset($_POST['ID']) && trim($_POST['ID'])) ? trim($_POST['ID']) : NULL;
		$email = (isset($_POST['email']) && trim($_POST['email'])) ? trim($_POST['email']) : NULL;
		echo ($this->accmain->checkEmailExists($email, $ID)) ? 1 : 0;
	}
	
	public function getcountriesajax() {
		echo ($data = $this->accmain->getAllCountries()) ? json_encode($data) : NULL;
	}
	
	public function getstatesajax() {
		$country = (isset($_POST['country']) && $_POST['country']) ? $_POST['country'] : NULL;
		echo ($data = $this->accmain->getAllStates($country)) ? json_encode($data) : NULL;
	}
	
	/**
	* PRIVATE
	*/
	private function sendEmail($data) {
		if(!trim($data['from']['email'])) return true;
		if(!trim($data['to']['email'])) return true;
		
		$this->load->library('email');
		
		$this->email->from($data['from']['email'], $data['from']['name']);
		$this->email->to($data['to']['email'], $data['to']['name']);
		$this->email->set_newline("\r\n");
		
		$this->email->subject('Thank you for signing up with SPS E-Voting');
		$this->email->message($this->load->view($data['view'], $data, true));
		
		return($this->email->send()) ? TRUE : FALSE;
	}
	
	private function uploadProfileImage($id) {
		$ext = array('jpg','jpe','jpeg','png','gif','ico','bmp','svg');
		
		$rel = "img/profile";
		$virt = base_url().$rel;
		$abso = str_replace('\\','/',FCPATH);
		$dir = str_replace('\\','/',$abso).$rel;
		$key = 'account_imageFile';
		$config = array(
			'allowed_types' => implode("|",$ext),
			'upload_path' => $dir,
			'file_name' => $id,
			'max_size' => '6048',
			'overwrite' => TRUE
		);
	
		$return['path'] = NULL;
		$return['file'] = NULL;
		$return['message'] = NULL;
		if(file_exists($dir)) {				
			chmod($dir, 0755);
			if (is_uploaded_file($_FILES[$key]['tmp_name'])) {
				$this->load->library('upload', $config);			
				if ($this->upload->do_upload($key)) {
					if($data = $this->upload->data()) {	
						$return['path'] = $data['full_path'];
						$return['file'] = $data['file_name'];
						$return['message'] = "SUCCESS";
					} else {
						$return['message'] = $this->upload->display_errors();
						$return['file'] = NULL;
						$return['path'] = NULL;
					}
				} else {
					$return['message'] = $this->upload->display_errors();
					$return['file'] = NULL;
					$return['path'] = NULL;
				}
			}
		} else {
			$return['message'] = "Location to upload does not exist";
			$return['file'] = NULL;
			$return['path'] = NULL;
		}
		
		return $return;
	}

	private function uploadLogoImage($id) {
		$ext = array('jpg','jpe','jpeg','png','gif','ico','bmp','svg');
		
		$rel = "img/logos";
		$virt = base_url().$rel;
		$abso = str_replace('\\','/',FCPATH);
		$dir = str_replace('\\','/',$abso).$rel;
		$key = 'organization_logoImage';
		$config = array(
			'allowed_types' => implode("|",$ext),
			'upload_path' => $dir,
			'file_name' => $id,
			'max_size' => '6048',
			'overwrite' => TRUE
		);
	
		$return['path'] = NULL;
		$return['file'] = NULL;
		$return['message'] = NULL;
		if(file_exists($dir)) {				
			chmod($dir, 0755);
			if (is_uploaded_file($_FILES[$key]['tmp_name'])) {
				$this->load->library('upload', $config);			
				if ($this->upload->do_upload($key)) {
					if($data = $this->upload->data()) {	
						$return['path'] = $data['full_path'];
						$return['file'] = $data['file_name'];
						$return['message'] = "SUCCESS";
					} else {
						$return['message'] = $this->upload->display_errors();
						$return['file'] = NULL;
						$return['path'] = NULL;
					}
				} else {
					$return['message'] = $this->upload->display_errors();
					$return['file'] = NULL;
					$return['path'] = NULL;
				}
			}
		} else {
			$return['message'] = "Location to upload does not exist";
			$return['file'] = NULL;
			$return['path'] = NULL;
		}
		
		return $return;
	}


}

?>