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

class Import extends CI_Controller {
	protected $projectID = 0;
	
	public function __construct(){
		parent::__construct();

		checkDashboard();

		$this->load->library('excel');
		$this->load->library('flashdata');
		$this->load->library('layouts');
		
		$this->load->model('project/projectmain','projmain');
		$this->load->model('import/importmain','importmain');		

		$this->lang->load('import', $this->session->userdata('language'));
		
		$this->projectID = $this->session->userdata('projectID');
		$this->session->set_userdata('menu', "voter");
	}
	
	public function index() {
		$data['project'] = $this->projmain->getProject($this->projectID);
		$data['respond']['type'] = NULL;
		$data['respond']['message'] = NULL;
		if($flashdata = $this->flashdata->get()) {
			$data['respond']['type'] = (isset($flashdata['type'])) ? strtoupper($flashdata['type']) : NULL;
			$data['respond']['message'] = (isset($flashdata['message'])) ? $flashdata['message'] : NULL;
		}
		
		$this->layouts->view('import/import', array(), $data);
	}
	
	public function process() {
		$data['respond']['type'] = NULL;
		$data['respond']['message'] = NULL;
		if($flashdata = $this->flashdata->get()) {
			$data['respond']['type'] = (isset($flashdata['type'])) ? strtoupper($flashdata['type']) : NULL;
			$data['respond']['message'] = (isset($flashdata['message'])) ? $flashdata['message'] : NULL;
		}
		
		if($data['project'] = $this->projmain->getProject($this->projectID)) {
			if(!trim($data['project']['importfile'])) {
				$this->flashdata->set('NO VOTERS IMPORTED / VOTER IMPORT FILE CANNOT BE FOUND','message');
				$this->flashdata->set('FAIL','type');
				redirect(base_url()."import");
			}
			
			$dir = ($data['project']['importfile']) ? str_replace('\\','/',FCPATH).$data['project']['importfile'] : NULL;
			if(!file_exists($dir)) {
				$this->flashdata->set('VOTER IMPORT FILE CANNOT BE FOUND','message');
				$this->flashdata->set('FAIL','type');
				redirect(base_url()."import");
			}
		
			$this->load->library('excel');
			$objPHPExcel = PHPExcel_IOFactory::load($dir);
			$collection = $objPHPExcel->getActiveSheet()->getCellCollection();
			$list = NULL;
			
			$ids = [];
			$columns = array('A'=>'name', 'B'=>'voter_ID', 'C'=>'voter_key');
			foreach ($collection as $cell) {
				$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
				$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
				$colval = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
				
				if ($row == 1) {
					$header[$column] = $columns[(strtoupper($column))];	//$colval;
				} else {
					$list[($row-2)][$header[$column]] = $colval;
					if($column == 'B') $ids[] = $colval;
				}
			}
			
			$data['used'] = $this->importmain->getUsedIDVoters($this->projectID,$ids);
			
			$data['list'] = $list;
		} else {
			$this->flashdata->set('PROJECT DOES NOT EXIST','message');
			$this->flashdata->set('FAIL','type');
			redirect(base_url()."project/setup");
		}
		
		$this->layouts->view('import/process', array(), $data);
	}
	
	/**
	* AJAX
	*/
	public function uploadajax() {		
		$p = (isset($_POST['p']) && trim($_POST['p'])) ? $_POST['p'] : 0;
		if($project = $this->projmain->getProject($p)) {
			$ext = array('xlsx');
		
			$rel = "dist/doc/import";
			$virt = base_url().$rel;
			$abso = str_replace('\\','/',FCPATH);
			$dir = str_replace('\\','/',$abso).$rel;
			$key = 'file';
			$config = array(
				'allowed_types' => implode("|",$ext),
				'upload_path' => $dir,
				'file_name' => $p."_".date('Ymdhis'),
				'max_size' => '6048',
				'overwrite' => TRUE
			);
		
			$return['url'] = 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['url'] = (str_replace($abso,"",$data['full_path']));
							$return['message'] = "SUCCESS";
							
							$this->importmain->updateProjectVoterFile($p, $return['url']);
						} else {
							$return['message'] = $this->upload->display_errors();
							$return['url'] = NULL;
						}
					} else {
						$return['message'] = $this->upload->display_errors();
						$return['url'] = NULL;
					}
				}
			} else {
				$return['message'] = "Location to upload does not exist";
				$return['url'] = NULL;
			}
		} else {
			$return['message'] = "Project does not exist";
			$return['url'] = NULL;
		}
		
		echo json_encode($return);
		return TRUE;
	}
	
	public function checkvoterajax() {
		$p = ($_POST['p']) ? $_POST['p'] : 0;
		$i = ($_POST['i']) ? $_POST['i'] : NULL;
		echo ($this->importmain->checkAuthIDExist($p,$i)) ? "EXISTS" : "NOT EXISTS";
	}
	
	public function savevoterajax() {
		$message = "SUCCESS";
		if($project = ($_POST['project']) ? $_POST['project'] : NULL) {
			if($this->importmain->clearVoter($project)) {
				if($data = ($_POST['data']) ? $_POST['data'] : NULL) {
					foreach($data as $key=>$value) {
						if(!$this->importmain->saveVoter($value)) {
							$message = "FAIL TO SAVE A VOTER (".$value['authid'].")";
							break;
						}
						
						if(trim(strtoupper($message)) != "SUCCESS") break;
					}
				} else {
					$message = "INVALID DATA.";
				}
			} else {
				$message = "UNABLE TO CLEAR LIST OF VOTERS.";
			}
		} else {
			$message = "INVALID PROJECT.";
		}
		echo $message;
	}
	






























	
}
?>