<?php
/**
 * btnsort.php
 *
 * The is the new and much imporved button sort feature. The code is fully encapsulated
 * and will work with any module and template type without much effort.
 * The old code was badly implemented and not flexible plus a bunch of hard-coded template types.
 * The old code had specific code to deal with different modules but still much much slower than
 * this new generic one. It was more work to clean up the old module-sort duplicated queries and
 * hard-coded template types than implementing this whole new generic sorting sub-system...
 *
 * @author $Author: dtong $
 * @version $Id: btnsort.php,v 1.3 2011/05/13 03:39:31 dtong Exp $
 * @copyright Copyright (c) 2011, Tiller Software Co., Ltd.
*/
class Btnsort extends CI_Controller {
	function __construct() {
		parent::__construct();
		$this->load->model('cms/btnsort_model');
		if (!osa_login_object()) {
			exit;
		}
	}

	function up($id, $coreid, $linkid) {
		$this->_move($id, Btnsort_model::ACTION_UP, $coreid, $linkid);
	}

	function down($id, $coreid, $linkid) {
		$this->_move($id, Btnsort_model::ACTION_DOWN, $coreid, $linkid);
	}

	//coreid and linkid are not really necessary but for checking only
	private function _move($id, $action, $coreid, $linkid) {
		if ( !osa_is_int_one($id) ) {
			echo osa_ajaxmsg(lang('gen_internalservererror'));
			exit;
		}
		if ( !($data = $this->btnsort_model->get_swap_data($id, $action)) ) {
			echo osa_ajaxmsg(lang('gen_btnsort_error'));
			exit;
		}

		//$data can be true value which means reaching boundary and do nothing
		if ( is_array($data) ) {
			if ( $data[0]->coreid != $coreid || $data[0]->linkid != $linkid ) {
				echo osa_ajaxmsg(lang('gen_btnsort_error'));
				exit;
			}
			//segmentids are mostly null except for outcomes and lt
			if ( $data[0]->segmentid != $data[1]->segmentid ) {
				//Reaches segment boundary so do nothing. This is caused by 2 people sorting at the same time.
				//Doesn't happen very often but can be an issue if not handled.
				exit;
			}
			//Put security check here
			$this->load->library('cms/cms_security');
			if ( !$this->cms_security->validate(CMS_ACTION_EDIT, CMS_BTNSORT_SECURITY_TEMPLATE_NAME, $data[0]->type, $coreid) ) {
				echo osa_ajaxmsg(lang('gen_security_no_permission'));
				exit;
			}

			if ( !$this->btnsort_model->swap($data) ) {
				echo osa_ajaxmsg(lang('gen_btnsort_error'));
				exit;
			}
		}
		exit;
	}
 }