<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Group_model extends MY_Model{
	function __construct(){
		parent::__construct();
		
		$this->table = "WEB_GROUP";
		
		$this->join .= "LEFT JOIN WEB_USER AS CREATE_USER ON CREATE_USER.PKKEY = <T>.CREATED_BY ";
		$this->join .= "LEFT JOIN WEB_USER AS MODIFY_USER ON MODIFY_USER.PKKEY = <T>.MODIFIED_BY ";
	}
	
	function save_before($post, $save_mode){
		if($save_mode == "INSERT" && ! isset($post['SEQN'])){
			$last_array = $this->get_data(array(
				'select' => "<T>.SEQN",
				'sort' => "<T>.SEQN DESC",
				'limit' => "1",
				'' => "",
			));
			
			$post['SEQN'] = count($last_array) > 0? (int)$last_array[0]->SEQN + 1:1;
		}
		
		return $post;
	}
	
	function move($get){
		$return = array('error' => "");
		
		if(isset($get['PKKEY'], $get['DIRECTION'])){
			$pk_value = $get['PKKEY'];
			$direction = $get['DIRECTION'];
			
			$data_array = $this->get_data(array(
				'condition' => "<T>.<PK> = '".$pk_value."'",
			));
			if(count($data_array) > 0){
				$data_1 = $data_array[0];
				
				//Get Sibling---
				$condition = "";
				if($direction == "UP"){
					$condition = "<T>.SEQN < '".$data_1->SEQN."' AND <T>.<PK> != '".$pk_value."'";
				}
				else if($direction == "DOWN"){
					$condition = "<T>.SEQN > '".$data_1->SEQN."' AND <T>.<PK> != '".$pk_value."'";
				}
				
				$sort = "";
				if($direction == "UP"){
					$sort = "<T>.SEQN DESC";
				}
				else if($direction == "DOWN"){
					$sort = "<T>.SEQN";
				}
				$sibling_menu_array = $condition != ""? $this->get_data(array(
					'condition' => $condition,
					'limit' => 1,
					'sort' => $sort,
				)):array();
				//--------------
				
				if(count($sibling_menu_array) > 0){
					$data_2 = $sibling_menu_array[0];
					
					//1 -> 2---
					unset($data);
					$data['SEQN'] = $data_2->SEQN;
					$this->sql_update($data, $data_1->PKKEY);
					//---------
					
					//2 -> 1---
					unset($data);
					$data['SEQN'] = $data_1->SEQN;
					$this->sql_update($data, $data_2->PKKEY);
					//---------
				}
			}
		}
		
		return $return;
	}
}