<?php
defined('BASEPATH') OR exit('No direct script access allowed');
defined('DIR_SEPARATOR') || define('DIR_SEPARATOR', '/');

class Votermain extends CI_Model {
	
	public function __construct() { parent::__construct(); }
	
	public function checkVoterNoInUse($authid, $project, $voter) {
		$sql = "SELECT COUNT(1) CT FROM user WHERE UPPER(noAhli) = ".(strtoupper(trim($authid)))." AND projectID = ".$project." AND userID != ".$voter;
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result()) && $r[0] && $r[0]->CT) ? TRUE : FALSE;
	}
	
	public function saveVoter($data) {
		$sql = "SELECT COUNT(1) CT FROM user WHERE userID = ".$data['userID']." AND projectID = ".$data['projectID'];
		$q = $this->db->query($sql);
		
		if($ct = ($q && ($r = $q->result()) && $r[0] && $r[0]->CT) ? TRUE : FALSE) {
			$sql = "UPDATE user
								SET
									noAhli = '".(addslashes(trim($data['noAhli'])))."',
									name = '".(addslashes(trim($data['voterName'])))."'
									".((trim($data['companyID'])) ? ", companyID = '".(trim($data['companyID']))."' " : NULL)."
									".((trim($data['userPassword'])) ? ", userPassword = '".(md5(trim($data['userPassword'])))."' " : NULL)."
								WHERE userID = ".$data['userID']."
								AND projectID = ".$data['projectID'];
			return ($this->db->query($sql)) ? $data['userID'] : 0;
		} else {
			$sql = "INSERT INTO user (
								noAhli, name, projectID
								".((trim($data['companyID'])) ? ", companyID " : NULL)."
								".((trim($data['userPassword'])) ? ", userPassword " : NULL)."
							) VALUES (
								'".(addslashes(trim($data['noAhli'])))."',
								'".(addslashes(trim($data['voterName'])))."',
								".($data['projectID'])."
								".((trim($data['companyID'])) ? ", '".(trim($data['companyID']))."' " : NULL)."
								".((trim($data['userPassword'])) ? ", '".(md5(trim($data['userPassword'])))."' " : NULL)."
							)";
							
			return ($this->db->query($sql)) ? $this->db->insert_id() : 0;
		}
	}
	
	public function ObjToArray($item) { return json_decode(json_encode($item),true); }
	
}































