<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
	$mod_template="add_bug.tpl";
	$versions=Db::i()->selectCol("SELECT version_id AS ARRAY_KEY, version FROM ?_bt_versions WHERE project_id=? ORDER BY version_id", $project_id);

	if ($_SERVER['REQUEST_METHOD']=='POST')
	{
		User::checkToken();
		if (!array_key_exists($_POST['type'], $bug_types)) LabCMS::i()->error("Не выбран тип сообщения!");
		if ($_POST['version_id']!=-1 && !array_key_exists($_POST['version_id'], $versions)) LabCMS::i()->error("Не выбрана версия программы!");
		if(!trim($_POST['summary'])) LabCMS::i()->error("Не заполнена тема сообщения");
		if(!trim($_POST['description'])) LabCMS::i()->error("Не заполнено описание!");
		if($_POST['type']==1 && !trim($_POST['steps'])) LabCMS::i()->error("Пожалуйста, напишите пошагово как воспроизвести ошибку.");
		$ids=array();
		if (LabCMS::i()->no_errors)
		{
			foreach($_FILES['shot']['name'] as $key=>$value)
			{
				if (LabConfig::$mcfg['max_upload_size'] && ($_FILES['shot']['size'][$key]>(LabConfig::$mcfg['max_upload_size']*1024)))
				{
					LabCMS::i()->error(sprintf(_m("Файл %s слишком большой"), $_FILES['shot']['name'][$key]), true);
					break;
				}
				if ($_FILES['shot']['tmp_name'][$key] && $id=upload_file($_FILES['shot']['name'][$key], $_FILES['shot']['tmp_name'][$key])) $ids[]=$id;
			}
		}
		
		if (LabCMS::i()->no_errors)
		{
			$bug_id=Db::i()->query("INSERT INTO ?_bt_bugs (project_id, version_id, summary, type, author_id, bug_date, status, importance) VALUES(?, ?, ?, ?, ?, NOW(), ?, 10)", $project_id, $_POST['version_id'], $_POST['summary'], $_POST['type'], User::i()->id, (access('approve,perform')?10:20));
			$msg="[b]Описание[/b]\r\n".$_POST['description'].($_POST['steps']?"\r\n[b]Последовательность действий[/b]\r\n".$_POST['steps']:'');
			$post_id=Db::i()->query("INSERT INTO ?_bt_posts (user_id, bug_id, msg, putdate) VALUES(?, ?, ?, NOW())", User::i()->id, $bug_id, $msg);
			
			if (count($ids)) Db::i()->query("UPDATE ?_bt_files SET post_id=? WHERE file_id IN (?a)", $post_id, $ids);
			refresh('', LabCMS::i()->url($bug_id, 'item'));
		}
		else
		{
			if (count($ids)) delete_files($ids);
		}
	}
	
	Tpl::i()->assign('versions', $versions);
	Tpl::i()->assign('bug_types', $bug_types);
	
	if (is_array($versions))
	{
		$keys=array_keys($versions);
		$last_version=array_pop($keys);
		Tpl::i()->assign('version_id', $last_version);
	}

	//вывод смайликов
	Tpl::i()->assign("js_smiles", bbcode_smiles_js(4,4));