<?
define("ADMIN_AUTHORIZATION",1);
include("../../../includes/common.php");

$id = $_GET['id']==""?$_POST['id']:$_GET['id'];
$group_ids = $_GET['group_ids']==""?$_POST['group_ids']:$_GET['group_ids'];
$action = trim($_GET['action']=="")?trim($_POST['action']):trim($_GET['action']);

switch($action)
{
	case 'delete' :
		$table = "pincode_collections";
		$index = "./index.php";
		break;
	case 'deletepins' :
	case 'validpins' :
	case 'usedpins' :
		$table = "pincodes";
		$index = "./listcodes.php";
		break;
}

if(is_numeric($id)){
	$group_ids = Array();
	$group_ids[0]=$id;
}

$result_flag = true;

if(sizeof($group_ids)==0||!is_array($group_ids)){
	header("Location: ./index.php?l_pager");
	exit;
}

switch($action){
	case "delete":
		$flag = true;
		foreach($group_ids as $value){
			if(!mysql_query("DELETE FROM `pincodes` WHERE `collection_id`=$value;"))
			{
				$result_flag = false;
				break;
			}
			if(!(@DeleteRecord($table,$value))){
				$result_flag = false;
				break;
			}
			
			mysql_query("DELETE FROM ex_currencies WHERE pincode_collection_id=$value");
		}
		break;
	case "deletepins" :
		$flag = true;
		foreach($group_ids as $value){

			$pin = @mysql_fetch_object(mysql_query("select * from pincodes where id=$value"));
			if($pin)
			{
				$collection = @mysql_fetch_object(mysql_query("select * from pincode_collections where id=$pin->collection_id"));

				if($collection)
				{
					$res = @mysql_fetch_object(@mysql_query("select count(*) as pincount from pincodes where status='valid' and collection_id=$collection->id"));
					$pincount = (integer)$res->pincount;

					@mysql_query("update ex_currencies set amount='".$pincount*$collection->sell_price."' where pincode_collection_id=$collection->id");
				}
			}

			if(!(@DeleteRecord($table,$value))){
				$result_flag = false;
				break;
			}
		}


		break;
	case "validpins":
		$flag = true;
		foreach($group_ids as $value){
			if(!(@UpdateRecord($table,array("status"=>"valid"),$value))){
				$result_flag = false;
				break;
			}
		}
		break;
	case "usedpins":
		$flag = true;
		foreach($group_ids as $value){
			if(!(@UpdateRecord($table,array("status"=>"used"),$value))){
				$result_flag = false;
				break;
			}
		}
		break;
}
if($result_flag){
	$_SESSION['STATUS_MSG'] = "Операция успешно завершена.";

}
else{
	$_SESSION['ERROR_MSG'] = "Ошибка. Возможно стоит запрет на операцию в базе данных.";
}

header("Location: $index?l_pager");
exit;