<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Menu_model extends MY_Model{
	function __construct(){
		$this->table = "WEB_MENU";
		
		
//		$this->join .= "LEFT JOIN WEB_MENU ON WEB_MENU.PKKEY = <T>.MENU ";
	}
	
	function toggle($pk, $direction){
		$data_array = $this->get_data(array(
			'condition' => "<T>.<PK> = '".$pk."'",
		));
		if(count($data_array) > 0){
			$data_1 = $data_array[0];
			
			//Get Sibling---
			if($data_1->PARENT_ID == "" || $data_1->PARENT_ID == "0"){
				$condition = "(<T>.PARENT_ID IS NULL OR <T>.PARENT_ID = '')";
			}
			else{
				$condition = "<T>.PARENT_ID = '".$data_1->PARENT_ID."'";
			}
			if($condition != ""){
				if($direction == "up"){
					$condition .= " AND <T>.SEQN < '".$data_1->SEQN."' AND <T>.<PK> != '".$pk."'";
				}
				else if($direction == "down"){
					$condition .= " AND <T>.SEQN > '".$data_1->SEQN."' AND <T>.<PK> != '".$pk."'";
				}
			}
			
			if($direction == "up"){
				$sibling_menu_array = $condition != ""? $this->get_data(array(
					'condition' => $condition,
					'limit' => 1,
					'sort' => "WEB_MENU.SEQN DESC",
				)):array();
			}
			else if($direction == "down"){
				$sibling_menu_array = $condition != ""? $this->get_data(array(
					'condition' => $condition,
					'limit' => 1,
					'sort' => "WEB_MENU.SEQN",
				)):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);
				//---------
			}
			
			if($data_1->PARENT_ID == 0){
				return $data_1->PARENT_ID;
			}
			else{
				$data_array = $this->get_data(array(
					'condition' => "<T>.<PK> = '".$data_1->PARENT_ID."'",
				));
				
				if(count($data_array) > 0){
					if($data_array[0]->PARENT_ID == 0){
						return $data_array[0]->PKKEY;
					}
					else{
						return $data_array[0]->PARENT_ID;
					}
				}
			}
		}
	}
}