<?php

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

class Position_model extends CI_Model {
	
	public function checkOrderingExists($order, $project, $position) {
		$sql = "SELECT COUNT(1) CT
						FROM position
						WHERE ordering = ".$order."
						AND projectID = ".$project;
		$sql .= ($position) ? " AND positionID != ".$position : NULL;
		$q = $this->db->query($sql);
		return ($q && ($r = $q->result()) && $r[0] && $r[0]->CT) ? TRUE : FALSE;
	}

    public function position_all() {
		$this->db->select('a.*');
		$this->db->select('if(sum(b.positionID) > 0, false, true) as checkStatus', false);
		$this->db->from('position a');
		$this->db->where('a.projectID', $this->session->userdata('projectID'));
		$this->db->join('vote b', 'a.positionID = b.positionID', 'LEFT');
		$this->db->order_by('ordering', 'ASC');
		$this->db->group_by('positionID');
		$query = $this->db->get();
        if($query->num_rows() >= 1){
            return $query->result();
        } else {
            return FALSE;
        }
    }
	
	
	public function position_filterbydatatables($valuedatatable5) {
		$this->db->select('a.*');
		$this->db->select('if(sum(b.positionID) > 0, false, true) as checkStatus', false);
		$this->db->from('position a');
		$this->db->where($valuedatatable5);
		$this->db->where('a.projectID', $this->session->userdata('projectID'));
		$this->db->join('vote b', 'a.positionID = b.positionID', 'LEFT');
		$this->db->order_by('ordering', 'ASC');
		$this->db->group_by('positionID');
		$query = $this->db->get();
        if($query->num_rows() >= 1){
            return $query->result();
        } else {
            return FALSE;
        }
    }


	public function insert($tname, $data){
		$sql = $this->db->insert_string($tname, $data);
		$query = $this->db->query($sql);
		if($query === TRUE){
			return $this->db->insert_id();
		} else {
			return NULL;
		}
	}
	
	public function update($tname, $ID, $data) {
        $this->db->where('positionID', $ID);
        $query = $this->db->update($tname, $data);
        if ($query === TRUE) {
            return $ID;
        } else {
            return NULL;
        }
    }
	
	public function delete($tname, $ID) {
        $this->db->where('positionID', $ID);
        $query = $this->db->delete($tname);
        if ($query === TRUE) {
            return TRUE;
        } else {
            return FALSE;
        }
    }
	
	

	
	
//***********************************
	

}
