<?php 

error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 'On');

if (!isset($_GET['signin']) || (isset($_GET['signin']) && $_GET['signin'] != 'q@3as4RC')){
	exit();
}

require('../core/classes/collection.class.php');
require('../core/classes/orm.class.php');
require('../core/classes/orm_condition.class.php');
require('../core/classes/register.class.php');
require('../admintools/models/bills.model.php');

require('../application/config/db.cfg.php');
require('../core/classes/db.class.php');

Register::add('db',new Db());
$db = Register::get('db');

//обновление статуса
if ( isset($_GET['bill']) && isset($_GET['status']) ){

	$dic_statuses = new Orm(DB_PREFIX."dic_statuses");
	$done_status = $dic_statuses->select()->fields("id")->where("type=?",1)->fetchOne();
	$done_status_id = $done_status['id'];
	
	$manager_id = 9; // не удалять менеджера 1С из пользователей id 9
	$status = $_GET['status']; // статус id
	$set_operation_item_ids = $_GET['bill']; // передаем много id позиций так ?bill[]=800&bill[]=801&bill[]=802 ... N&status=1
	
	$sql = "UPDATE ".DB_PREFIX."cart
			SET ".DB_PREFIX."cart.status = ".(int)$status.", ".DB_PREFIX."cart.need_alert = 1
			WHERE ".DB_PREFIX."cart.id IN (".(join(",", $set_operation_item_ids)).");";
	$db->post($sql);
	
	foreach ($set_operation_item_ids as $item){
			
		/* перевод заказы в выполнение в автомат. режиме ************************ */
		$sql = "
		SELECT COUNT(t1.id) c
		FROM ".DB_PREFIX."cart t1
		LEFT JOIN ".DB_PREFIX."dic_statuses t2 ON t1.status=t2.id
		WHERE
			t1.scSID = (SELECT scSID FROM ".DB_PREFIX."cart WHERE id = '".(int)$item."') AND
			(t2.type != 1 OR t2.type IS NULL)";
		$res_cc = $db->get($sql);
		
		$sql = "
		UPDATE
			".DB_PREFIX."cart,
			".DB_PREFIX."cart_bills
		SET
			".DB_PREFIX."cart_bills.status = IF((".((int)$res_cc['c']?0:1)."),".(int)$done_status_id.",".(($status == $done_status_id)?DB_PREFIX."cart_bills.status":$status)."),
			".DB_PREFIX."cart_bills.bill_dt_closed = IF((".((int)$res_cc['c']?0:1)."),".time().",".(0).")
		WHERE
			".DB_PREFIX."cart.id IN (".((int)$item).") AND
			".DB_PREFIX."cart.scSID = ".DB_PREFIX."cart_bills.scSID
		;";
		$db->post($sql);
		/* перевод заказы в выполнение в автомат. режиме - конец   *********** */
		 	
		/* логирование статусов ************************ */
		$sql = "
		SELECT
			ITEMS.price,
			BILLS.account_id,
			DS.name dstatus
		FROM ".DB_PREFIX."cart ITEMS
		JOIN ".DB_PREFIX."cart_bills BILLS ON BILLS.scSID=ITEMS.scSID
		LEFT JOIN ".DB_PREFIX."dic_statuses DS ON DS.id=ITEMS.status
		WHERE ITEMS.id = '".(int)$item."'
		;";
		$cartData = $db->get($sql);
		
		$cartData['dstatus'] = ($cartData['dstatus'])?$cartData['dstatus']:'Новый';
		$db->post("
		INSERT INTO ".DB_PREFIX."cart_history
			(`fk_item`,`fk_user`,`status_name`,`dt`,`price`)
		VALUES
			('".(int)$item."','".(int)$manager_id."','".DB::escape($cartData['dstatus'])."','".time()."','".$cartData['price']."')
		;");
	}

	echo('true');
	exit();
	
}
//получение списка позиций по статусу
elseif ( isset($_GET['status']) ){
	
	$params = array('status' => array($_GET['status'])); // массив id статусов
	$data = BillsModel::getHistory($params);
	
	echo('<pre>');
	var_dump($data);
	echo('</pre>');
	
}

?>