<?php
include('includes/application_top.php');
include(DIR_WS_CLASSES.'delivery_conditions.php');

include(DIR_WS_CLASSES.'class.dbform.php');
$smarty = new yesSmarty();
$smarty->compile_dir = DIR_FS_CATALOG.'templates_c';

$dbf = new dbform('delivery_conditions','delivery_conditions_id',$conn);

$dbf->fields['title']->set_title(ENTRY_NAME,1);
$dbf->fields['title']->set_required($min_length=3,$validate_func = '');
$dbf->fields['code']->set_title(ENTRY_CODE,6);
$dbf->fields['code']->set_required($min_length=2,$validate_func = 'code');
$dbf->fields['code']->set_comments(TEXT_CODE_FIELD);

// bei edit die id angeben
$dbf->select_id = xtc_db_input($_GET['id']);

if(xtc_not_null($dbf->select_id)){
	$mode = 'edit';
}else{
	$smarty->assign('PAGE_TITLE',HEADING_TITLE_NEW);
	$mode = 'add';
}

// POST DATA ABFANGEN BEIM SPEICHERN
$mode = ($_POST['action'] == 'edit' or $_POST['action'] == 'add') ? $_POST['action'] : $mode; 

$menu = yes_draw_href_button(IMAGE_BACK,xtc_href_link(FILENAME_DELIVERY_CONDITIONS),$access='delivery_conditions');
$smarty->assign('PAGE_MENU',$menu);

$result = $dbf->get_form($form_name = 'delivery_conditions',$page = yes_get_php_self(),$mode,$template = DIR_FS_ADMIN.'templates/formular.tpl',$smarty);

if( $result == 'save' ){
	// SAVE HANDLER
	switch($mode){
		case 'edit':
			$sql_update_array = $dbf->get_sql_array($_POST);

			xtc_db_perform($dbf->table,$sql_update_array,'update',$dbf->index_field."='".$dbf->select_id."'");

			$YES_HISTORY->add('system',sprintf(HISTORY_DELIVERY_CONDITION_UPDATED,$_POST['code']));
			
			$messageStack->add_session(MESSAGE_SUCCESS_UPDATE,'success');
			xtc_redirect(xtc_href_link(FILENAME_DELIVERY_CONDITIONS));
			break;
		case 'add':
			$sql_insert_array = $dbf->get_sql_array($_POST);
			$sql_insert_array['date_added'] = 'now()';

			xtc_db_perform($dbf->table,$sql_insert_array);
			$id = $conn->Insert_ID();
			
			$YES_HISTORY->add('system',sprintf(HISTORY_DELIVERY_CONDITION_ADDED,$_POST['title']));
			
			$messageStack->add_session(MESSAGE_SUCCESS_CREATE,'success');
			xtc_redirect(xtc_href_link(FILENAME_DELIVERY_CONDITIONS));
			break;
	}
}
include(DIR_WS_INCLUDES.'header.php');
echo $result;

include('includes/footer.php');
