<?php

if( $a == 'list' ){
	$aForms = $oDB->throwFileArray( DB_FORMS );
	$oTpl->assign( 'aForms', $aForms );
	$content .= $oTpl->parse( 'forms_list.tpl' );
}
elseif( $a == 'form' ){
	if( !empty( $_POST ) ){
		$_POST['iForm'] = $oDB->save( DB_FORMS, $_POST, 'iForm' );
		if( is_array( $_POST['aFields'] ) ){
			foreach( $_POST['aFields'] as $aField['iFormField'] => $aField ){
				if( empty( $aField['sName'] ) ){
					$oDB->deleteInFile( DB_FORMS_FIELDS, $aField['iFormField'], 'iFormField' );
				} else{
					$aField['iForm'] = $_POST['iForm'];
					if( !isset( $aField['iRequired'] ) ) $aField['iRequired'] = 0;
					if( !isset( $aField['iEmail'] ) ) $aField['iEmail'] = 0;
					$oDB->save( DB_FORMS_FIELDS, $aField, 'iFormField' );
					$oDB->deleteInFile( DB_FORMS_FIELDS_VALUES, $aField['iFormField'], 'iFormField' );
					if( is_array( $aField['aValues'] ) ){
						foreach( $aField['aValues'] as $sValue ) if( !empty( $sValue ) ){
							$oDB->save( DB_FORMS_FIELDS_VALUES, Array( 'iFormField' => $aField['iFormField'], 'sValue' => $sValue ) );
						}
					}
				}
			}
		}
		if( is_array( $_POST['aNewFields'] ) ){
			foreach( $_POST['aNewFields'] as $aField ){
				if( empty( $aField['sName'] ) ){
				} else{
					$aField['iForm'] = $_POST['iForm'];
					if( !isset( $aField['iRequired'] ) ) $aField['iRequired'] = 0;
					if( !isset( $aField['iEmail'] ) ) $aField['iEmail'] = 0;
					$aField['iFormField'] = $oDB->save( DB_FORMS_FIELDS, $aField, 'iFormField' );
					if( is_array( $aField['aValues'] ) ){
						foreach( $aField['aValues'] as $sValue ) if( !empty( $sValue ) ){
							$oDB->save( DB_FORMS_FIELDS_VALUES, Array( 'iFormField' => $aField['iFormField'], 'sValue' => $sValue ) );
						}
					}
				}
			}
		}
		header( 'Location: admin.php?p=forms-form&sOption=save&iForm=' . $_POST['iForm'] );
		exit;
	}
	if( !empty( $sOption ) ){
		$content .= $oTpl->parse( 'message_done.tpl' );
	}
	if( isset( $iForm ) && is_numeric( $iForm ) ){
		$aForm = $oDB->throwData( DB_FORMS, $iForm, 'iForm' );
		$aForm['aFields'] = $oDB->throwFileArray( DB_FORMS_FIELDS, Array( 'iForm' => $iForm ) );
		foreach( $aForm['aFields'] as &$aField ){
			$aField['aValues'] = $oDB->throwFileArray( DB_FORMS_FIELDS_VALUES, Array( 'iFormField' => $aField['iFormField'] ) );
		}
	} else{
	}
	$oTpl->assign( 'aForm', $aForm );
	$content .= $oTpl->parse( 'forms_form.tpl' );
}
elseif( $a == 'delete' && is_numeric( $iForm ) ){
	$oDB->deleteInFile( DB_FORMS, $iForm, 'iForm' );
}