<?
if($_REQUEST['action'] == "addblock"){
    $newEnterNumber = $_REQUEST['newEnterNumber'];
	$html = '
	<div data-indexfrom="0" 
	title="Можно перетащить блок мышкой и поставить его ПОСЛЕ другого" 
	class="block-questions" 
	id="blockid-'.$newEnterNumber.'" 
	data-blocknumber="'.$newEnterNumber.'">
		<span class="icon-dell" onclick="return dellBclock(this);" title="Удалить этот блок (Х)">&#10060;</span>
		<span class="icon-dell icon-edit" onclick="return setActiveBclock(this);" title="Выделить это блок для редактирования">&#9998;</span>
		<span class="icon-dell icon-edit" onclick="return setMoveBclock(this);" title="Переместить блок">&#8597;</span>
		
		<div onclick="return setActiveBlock(this);" class="block-questions_1">Блок № '.$newEnterNumber.'</div>
		<div class="block-questions_2">Заполните вопрос:</div>
		<div title="редактировать этот текст" class="block-questions_3 editable-question" contenteditable="true">Напишите здесь вопрос или удалите текст, если не нужно</div>
		<div class="wrap-answers-radio"></div>
		<div class="wrap-file-input"></div>
		<div class="wrap-text-input"></div>
		<div class="wrap-static-text">
			<div class="block-questions_2">Заполните произвольный текст если нужно(Обычно для сообщения что форма отправлена):</div>
			<div title="редактировать этот текст" class="wrap-free-text editable-free-text" contenteditable="true"></div>
		</div>
		<div class="wrap-footer">
			<div class="wrap-prev-button"></div>
			<div class="wrap-next-button"></div>
		</div>
		<div class="wrap-block-connect">
			<input data-from="block" onchange="return setConnectLineblock(this);" type="text" class="connect-block" value="" />
			Номер блока, куда соеденить целиком блок
		</div>
	</div>
	';
	echo $html;
	die;
}

if($_REQUEST['action'] == "saveprj"){
    $html = trim($_REQUEST['html']);
	file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/form_pojects_save_txt/".$_REQUEST['filename'].".txt", $html);
	file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/current_prj_file.txt", $_REQUEST['filename']);
    $config = Array(
        "emailfrom"=>$_REQUEST['emailfrom'],
        "emailto"=>$_REQUEST['emailto'],
        "subject_email_to_admin"=>$_REQUEST['subject_email_to_admin'],
        "subject_email_to_user"=>$_REQUEST['subject_email_to_user'],
        "select_template"=>$_REQUEST['select_template'],
        "send_to_user"=>$_REQUEST['send_to_user'],
		"no_images_show"=>$_REQUEST['no_images_show'],
		
		"effectDis"=>$_REQUEST['effectDis'],
		
		"effectApp"=>$_REQUEST['effectApp'],
		"speedDis"=>$_REQUEST['speedDis'],
		"speedApp"=>$_REQUEST['speedApp'],
		"zaderjkaApp"=>$_REQUEST['zaderjkaApp'],
		"strDis"=>$_REQUEST['strDis'],
		"strApp"=>$_REQUEST['strApp'],
		
    );
    $configJson = json_encode($config,JSON_HEX_QUOT|JSON_HEX_TAG| JSON_HEX_AMP| JSON_HEX_APOS);
    file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/form_pojects_save_txt/".$_REQUEST['filename'].".config", $configJson);
	echo "Ok";
	die;
}
if($_REQUEST['action'] == "newprj"){
	file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/form_pojects_save_txt/".$_REQUEST['filename'].".txt", "");
	file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/current_prj_file.txt", $_REQUEST['filename']);
	echo "Ok";
	die;
}
if($_REQUEST['action'] == "loadprj"){
	file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/current_prj_file.txt", $_REQUEST['filename']);
	echo "Ok";
	die;
}
if($_REQUEST['action'] == "addradio"){
	$id = 'label-question-'.$_REQUEST['currBlock'].'-answer-'.($_REQUEST['maxRadio'] + 1);
	$flIsLabel  = 1;//1-Заключить в label 0-Заключить в div
	
	$tagWrap = "label";
	if($flIsLabel  === 0){
		$tagWrap = "div";
	}
	
	$html = '
	<'.$tagWrap.' id="'.$id.'" class="quiz__answer-item" for="question-'.$_REQUEST['currBlock'].'-answer-'.($_REQUEST['maxRadio'] + 1).'">
		<input onchange="return setRadioChecked(this);" data-numberradio="'.($_REQUEST['maxRadio'] + 1).'" class="dev-radio-input" type="radio" name="question-'.$_REQUEST['currBlock'].'" id="question-'.$_REQUEST['currBlock'].'-answer-'.($_REQUEST['maxRadio'] + 1).'" value="'.$_REQUEST['textRadio'].'">
		<div class="wr-text-circle wr-text-circle-dev">
			<span onclick="return deActivateChecked(this);" class="quiz__answer-item-circle"></span>
			<span oninput="return setRadioTitle(this);" title="редактировать этот текст" contenteditable="true" class="quiz__answer-item-text">'.$_REQUEST['textRadio'].'</span>
			<span class="answer-dell" onclick="return dellAnswer(this);" title="Удалить этот ответ">❌</span>
		</div>	
		<img onclick="return setImage(this);" title="Изображение вставить в виде строки кода base64. Воспользуйтесь онлайн сервисами для предразовани файла картинки в код. Начинаться должно примерно так: data:image/png;base64,iVBORw0KGgo..." class="icon-img" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAGQCAMAAAC3Ycb+AAABoVBMVEVHcEz6thP6tRT6thT6thT6thT6tRMAIkEAIkH6thP6thT6thT6thT6thP6thT6thT6thT6tRP6thT6thT6thT6thT6tRP6thT6thP6tRT6thQAIkH6thT6thT6tRQAIkH6thT6thP6thP6tRT6thQAIkEAIkEAIkH6thT5thT6thT6thT6thT6thQAIkH6tRT6thT6thT6thP6thT6thT6thT6thT6thT6tRT6thT6thT6tRT6thT6tRT6thT6thT5thT6thP6thT6tRT6thT6thP6thT5thP6thT6tRT6thT6thT5thT5thP6thT6thT6thT6tRT6thP5thP6thT6tRT5thT6thT5thP6thT5thP6thT5thP6tRT6tRT6thT6thT5thT6thT6thT6thT6thP5thT6thT5thT6thT5thT5thP5thT6thP6thP6thP6thT6tRT5thT5thP6thT6thP6thP5thP5thP5thT5thT6thT6thT6thT5thP6thT6tRT6thT5thT5thP5thT6tRT6tRT5thT6thQAIkH6thT+RWXmAAAAiXRSTlMALDzlIEy3q1aNbPXVFsscxcGL61bBYECX1yY6l4HRxxhWDPe14x6PKBIqfAoEcmI6DgYMNhQ8aBoQGggwEBaHFAR0bsMSUgo4BK0skXShHlB0RCQ+gUyJgUYWZAa5HqMIULFI05konZmpIjSHi0ZKEjaNGgYkUkIEiwqvlVwsIgJyiQwGxT4kyWTt6dkAAAcKSURBVHja7d1ne9NWGAZghhMbOkJbunBbA20SSNpAgDDD6GCv7r1b6N577+H+6n7ppffQOhWJZUu27+fjcynKObrjJD5KdFatEhERERERERERERERERERERERERERERERERERERERERERERERERERERERERERERmkNOuROZej/DTakbrLAUSAABEgQAQIEAECRKoJ0mxEplyl8kHqSd1wlYAAAQJEgAARIEAECBABMviXttUuJS1rXR0z1y4rLRc/51uP10gF0ioRxE+ZDmkDAQIECBAgQIAAAQIESIkgffmElh+BAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIED6lR5OojPI5Q03ZdkR9TPRvr4n6vei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" />
		<div class="wrap-block-connect" title="Для случая, когда следующая форма зависит от ответа на вопрос (разветвление движения по формам)">
			<input data-from="radio" onchange="return setConnectLineRadio(this);" type="text" class="connect-radio" value="" />
			Номер блока, куда соеденить(радио)
		</div>
	</'.$tagWrap.'>
	';
	echo $html;
	die;
}
if($_REQUEST['action'] == "inputText"){
    $contenteditable=' contenteditable="true"';
	$html = '
	<label class="quiz__answer-item" for="question-'.$_REQUEST['currBlock'].'-input-'.($_REQUEST['maxInputText'] + 1).'">
		<div class="wr-text-input-title">
			<span title="редактировать этот текст"'.$contenteditable.' class="quiz__answer-item-text">Отредатируйте эту надпись к полю:</span>
		</div>	
		<input 
		onchange="return setTextInputValue(this);" 
		data-numbertextinput="'.($_REQUEST['maxInputText'] + 1).'" 
		data-isemail="0" 
		data-isphone="0" 
		class="dev-text-input" 
		type="text" 
		name="question-'.$_REQUEST['currBlock'].'-input-'.($_REQUEST['maxInputText'] + 1).'" 
		id="question-'.$_REQUEST['currBlock'].'-input-'.($_REQUEST['maxInputText'] + 1).'" 
		value="">
		<span class="answer-dell answer-dell-input-text" 
		onclick="return dellInputText(this);" 
		title="Удалить это поле">❌</span>
		
		<span class="answer-dell answer-isemail-input-text" 
		onclick="return setEmailInputText(this);" 
		title="Отметить(снять отметку) как поле для ввода Емаил">✉</span>
		
		<span class="answer-dell answer-isphone-input-text" 
		onclick="return setPhoneInputText(this);" 
		title="Отметить(снять отметку) как поле для ввода телефона">&#9742;</span>
		
		
	</label>
	';
	echo $html;
	die;
}

if($_REQUEST['action'] == "testemail"){
    $rez = mail($_REQUEST['emailto'], $_REQUEST['fromEmail'], "Это тест почты. Успешно!", "From: ".$_REQUEST['fromEmail']."");
    if($rez){
        $out = "Почта ОТПРАВЛЕНА успешно.\r\nЭто значит хостинг сайта отработал верно.\r\nОднако факт поступления необходимо проверить непосредсьвенно в Вашем почтовом ящике. Только после этого можно сказать работает ли почта или нет.";
    }else{
        $out = "Почта НЕ отправлена.\r\nОшибка на хостинге сайта.\r\nНе работает или заблокирована штатная функция php mail()";
    }
    echo $out;
    die;
}


if($_REQUEST['action'] == "makeshow"){
	//echo "<pre>";print_r($_REQUEST);echo "</pre>";die;
    $template = $_REQUEST['template'];
	$footerHeader = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/header_footer.html");
	$blockForm = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/block_form.html");
	$buttonNext = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/button_next.html");
	$buttonPrev = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/button_prev.html");
	$buttonSend = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/button_send.html");
	$listRadioAnswers = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/list_radio_anwers.html");
	$listTextFields = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/list_text_fields.html");

    $codePhpSendKviz = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/send_kviz.php");
    $codePhpSendKviz = str_replace("#FROM_EMAIL#", $_REQUEST['fromEmail'], $codePhpSendKviz);
    $codePhpSendKviz = str_replace("#TO_EMAIL#", $_REQUEST['emailto'], $codePhpSendKviz);
    $codePhpSendKviz = str_replace("#SUBJECT_EMAIL_TO_ADMIN#", $_REQUEST['subject_email_to_admin'], $codePhpSendKviz);
    $codePhpSendKviz = str_replace("#SUBJECT_EMAIL_TO_USER#", $_REQUEST['subject_email_to_user'], $codePhpSendKviz);
    $codePhpSendKviz = str_replace("#SEND_TO_USER#", $_REQUEST['send_to_user'], $codePhpSendKviz);
    $codePhpSendKviz = str_replace("#USER_EMAIL_KEY_FIELD#", $_REQUEST['userEmailKeyField'], $codePhpSendKviz);
    $codePhpSendKviz = str_replace("#USER_PHONE_KEY_FIELD#", $_REQUEST['userPhoneKeyField'], $codePhpSendKviz);


	$css = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/styles.css");
	// Для шаблона с анимацией
	if($_REQUEST['template'] == "animate_effects"){
		$strOut = str_replace(".disappeared-img img", ".step-item-out", $_REQUEST['globalDisApp']);
		$strIn = str_replace(".appearance-img img", ".step-item-in", $_REQUEST['globalApp']);
		$css .= "\r\n".$strOut."\r\n".$strIn;
		$firstSlide = '
		  .first-item-first-step{
			  opasity:0;
			  dysplay: none;
		  }
		';
		/*$staticStyle = '
			.step-one-item{
			}
			.step-one-item-1{
			}
		';*/
		$css .= "\r\n".$strOut."\r\n".$strIn."\r\n".$firstSlide;
	}
	//$out= str_replace("#LIST_STEP_FORM#");
	$out="";
	$izW=0;
	
	$msSize = 0;
    if(!empty($_REQUEST['dataForm'])){
        $msSize = count($_REQUEST['dataForm']);
    }
	
    $msStyle = Array();
	foreach($_REQUEST['dataForm'] as $val){
		$izW++;
		$part = str_replace("#QUESTION_BY_STEP#", $val['questionText'], $blockForm);
        $persent = round(($izW/$msSize *100), 0);
        $part = str_replace("#PROGRESS_LINE_PERSENT#", $persent, $part);
		
		
		$part = str_replace("#PORJADKOVIY_INDEX#", $izW, $part);//Порядковый номер слайда
		
		
		//Результирующее текстовое поле для показа в конце прохождения формы (что натыкали...)
		$existFornRezult = 0;
		if(!empty($val['blockExistFieldRezult'])){
			if($val['blockExistFieldRezult'] == "Y"){
				$existFornRezult = 1;
			}
		}
		if($existFornRezult === 1){
			$part = str_replace("#REZULT_FIELD#", '<div class="quiz-wrap-fill-rezult-form-by-text"></div>', $part);
		}else{
			$part = str_replace("#REZULT_FIELD#", '', $part);
		}
		
		$buttonSendHtml = "";
		if($val['buttonSend'] == 1){
			$buttonSendHtml = $buttonSend;
			$buttonSendHtml = str_replace("#TO_INDEX#", $val['blockConnectTo'], $buttonSendHtml);
			$buttonSendHtml = str_replace("#FROM_INDEX#", $val['blockConnectFrom'], $buttonSendHtml);
			$buttonSendHtml = str_replace("#CURRENT_INDEX#", $val['indexBlock'], $buttonSendHtml);
			if(empty($val['blockConnectTo'])){
				//echo '<span style="color:red">Ошибка в блоке № '.$val['indexBlock'].' есть кнопка но на ней не указано куда переход</span><br>';
			}
		}
		$buttonPrevHtml = "";
		if($val['buttonPrev'] == 1){
			$buttonPrevHtml = $buttonPrev;
			$buttonPrevHtml = str_replace("#TO_INDEX#", 0, $buttonPrevHtml);
			$buttonPrevHtml = str_replace("#FROM_INDEX#", $val['blockConnectFrom'], $buttonPrevHtml);
			$buttonPrevHtml = str_replace("#CURRENT_INDEX#", $val['indexBlock'], $buttonPrevHtml);
			if(empty($val['blockConnectFrom']) || $val['blockConnectFrom'] == 0){
				echo '<span style="color:red">Ошибка в блоке № '.$val['indexBlock'].' есть кнопка Назад но на ней не указано куда возвращаться</span><br>';
			}
		}
		$buttonNextHtml = "";
		$isNeedLinkToRadioNext = 0;
		if($val['buttonNext'] == 1){
			$buttonNextHtml = $buttonNext;
			$buttonNextHtml = str_replace("#TO_INDEX#", $val['blockConnectTo'], $buttonNextHtml);
			$buttonNextHtml = str_replace("#FROM_INDEX#", $val['blockConnectFrom'], $buttonNextHtml);
			$buttonNextHtml = str_replace("#CURRENT_INDEX#", $val['indexBlock'], $buttonNextHtml);
			if(empty($val['blockConnectTo'])){
				$isNeedLinkToRadioNext = 1;
				echo '<span style="color:red">Ошибка в блоке № '.$val['indexBlock'].' есть кнопка но на ней не указано куда переход</span><br>';
			}
		}
		
		//echo $blockForm;
		
		//echo "4--------------".$part;die;
		$part = str_replace("#BUTTON_PREV#",$buttonPrevHtml, $part);
		$part = str_replace("#BUTTON_NEXT#",$buttonNextHtml, $part);
		$part = str_replace("#BUTTON_SEND#",$buttonSendHtml, $part);
		
		$part = str_replace("#DOP_CLASS#", " dop-index-cls-".$val['indexBlock'], $part);
		
		if($izW === 1){
			$part = str_replace("#HIDDEN_CLASS_STEP#", "", $part);
		}else{
			$part = str_replace("#HIDDEN_CLASS_STEP#", " hidden-step hidden-step2", $part);
		}
		
		
		$part = str_replace("#B_INDEX#", $val['indexBlock'], $part);
		$listAnsverHtml = "";
		$partRadio = "";
		$iz=0;
		//Массив радио кнопок
		
		if(!empty($val['anwersRadio'])){
			foreach($val['anwersRadio'] as $valAnswerRadio){
				$partRadio = str_replace("#B_INDEX#", $val['indexBlock'], $listRadioAnswers);
				
				$partRadio = str_replace("#INDEX_RADIO_ANSWER#", $valAnswerRadio['dataNumbeRadio'], $partRadio);
				$partRadio = str_replace("#TEXT_RADIO_ANSWER#", $valAnswerRadio['inputName'], $partRadio);
				$partRadio = str_replace("#DATA_ULR_IMAGE_BASE64#", $valAnswerRadio['dataImage'], $partRadio);
				
				if($val['buttonNext'] == 0){
				
					if(empty($valAnswerRadio['answerConnectTo'])){
				
						if(!empty($val['blockConnectTo'])){
				
							$partRadio = str_replace("#TO_INDEX#", $val['blockConnectTo'], $partRadio);
							$partRadio = str_replace("#FROM_INDEX#", $val['blockConnectFrom'], $partRadio);
							$partRadio = str_replace("#CURRENT_INDEX#", $val['indexBlock'], $partRadio);
							
						}else{
				
							$partRadio = str_replace("#TO_INDEX#", 0, $partRadio);
							$partRadio = str_replace("#FROM_INDEX#", $val['blockConnectFrom'], $partRadio);
							$partRadio = str_replace("#CURRENT_INDEX#", $val['indexBlock'], $partRadio);
						}
					}
					if(!empty($valAnswerRadio['answerConnectTo'])){
				
						$partRadio = str_replace("#TO_INDEX#", $valAnswerRadio['answerConnectTo'], $partRadio);
						$partRadio = str_replace("#FROM_INDEX#", $val['blockConnectFrom'], $partRadio);
						$partRadio = str_replace("#CURRENT_INDEX#", $val['indexBlock'], $partRadio);
					}
				}
				
				$listAnsverHtml .= $partRadio;
				$iz++;
			}
		}
		$part = str_replace("#LIST_ANSWER_FORM_FIELDS_BY_STEP#", $listAnsverHtml, $part);
		
		$partTextField = "";
		$listTextInputHtml = "";
		$iz=0;
		//Массив текстовых полей
		if(!empty($val['inputTextArr'])){
			foreach($val['inputTextArr'] as $valTextInput){
				$partTextField = str_replace("#B_INDEX#", $val['indexBlock'], $listTextFields);
				$partTextField = str_replace("#NUMBER_TEXT_INPUT#", $valTextInput['dataNumberTextInput'], $partTextField);
				$partTextField = str_replace("#INPUT_TEXT_TITLE#", $valTextInput['valueTextInput'], $partTextField);
                //Отмечаю поля почты и емайла

                $zamenaEmail = "";
                $placeHoldeEmail = "";
                if(!empty($valTextInput['isemail'])){
                    if($valTextInput['isemail'] == "Y"){
						$svgEmail = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M64 112c-8.8 0-16 7.2-16 16v22.1L220.5 291.7c20.7 17 50.4 17 71.1 0L464 150.1V128c0-8.8-7.2-16-16-16H64zM48 212.2V384c0 8.8 7.2 16 16 16H448c8.8 0 16-7.2 16-16V212.2L322 328.8c-38.4 31.5-93.7 31.5-132 0L48 212.2zM0 128C0 92.7 28.7 64 64 64H448c35.3 0 64 28.7 64 64V384c0 35.3-28.7 64-64 64H64c-35.3 0-64-28.7-64-64V128z"></path></svg>';
                        $zamenaEmail = " isemail";
                        $placeHoldeEmail = ' placeholder=""';
						$partTextField = str_replace("#INPUT_SVG_PHONE_OR_EMAIL#", $svgEmail, $partTextField);
                    }
                }
                $partTextField = str_replace("#IS_EMAIL#", $zamenaEmail, $partTextField);
                $partTextField = str_replace("#PLASE_HOLDER_EMAIL#", $placeHoldeEmail, $partTextField);

                $zamenaPhone = "";
                $placeHoldePhone = "";
                #PLASE_HOLDER_PHONE#
                if(!empty($valTextInput['isphone'])){
                    if($valTextInput['isphone'] == "Y"){
                        $zamenaPhone = " isphone";
                        $placeHoldePhone = ' placeholder="+7 (ХХХ)-ХХХ-ХХ-ХХ"';
						$svgPhone = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M136.2 275.2c16.4-7 35.4-2.4 46.7 11.4l33.2 40.6c46-26.7 84.4-65.1 111.1-111.1L286.7 183c-13.8-11.3-18.5-30.3-11.4-46.7l48-112C330.8 6.7 349.7-3.1 368.4 .9l112 24C498.8 28.8 512 45.1 512 64v0c0 231.2-175.2 421.5-400.1 445.5c-9.8 1-19.7 1.8-29.6 2.2c0 0 0 0 0 0c0 0-.1 0-.1 0c-6.1 .2-12.1 .4-18.3 .4l0 0c-18.9 0-35.2-13.2-39.1-31.6l-24-112c-4-18.7 5.8-37.6 23.4-45.1l112-48zM70.5 464C286.3 460.5 460.5 286.2 464 70.5L364.8 49.2l-43 100.4L357.6 179c18.2 14.9 22.9 40.8 11.1 61.2c-30.9 53.3-75.3 97.7-128.6 128.6c-20.4 11.8-46.3 7.1-61.2-11.1l-29.4-35.9-100.4 43L70.5 464zM464 64s0 0 0 0v0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0"></path></svg>';
						$partTextField = str_replace("#INPUT_SVG_PHONE_OR_EMAIL#", $svgPhone, $partTextField);
                    }
                }
                $partTextField = str_replace("#IS_PHONE#", $zamenaPhone, $partTextField);
                $partTextField = str_replace("#PLASE_HOLDER_PHONE#", $placeHoldePhone, $partTextField);

				$listTextInputHtml .= $partTextField;
				$listTextInputHtml .= '<input type="hidden" name="label-question-'.$val['indexBlock'].'-input-'.$valTextInput['dataNumberTextInput'].'" value="'.$valTextInput['valueTextInput'].'">';
				$partTextField = str_replace("#INPUT_SVG_PHONE_OR_EMAIL#", '', $partTextField);
				$iz++;
			}
			$listTextInputHtml .= '<input type="hidden" name="label-question-'.$val['indexBlock'].'-input-count" value="'.count($val['inputTextArr']).'">';
		}
		
		$part = str_replace("#LIST_INPUT_TEXT#",$listTextInputHtml, $part);
		
		$isFreeTextExist = 0;
		if(!empty($val['freeTextField'])){
			$tmp = preg_replace("/\s/","", $val['freeTextField']);
			if(mb_strlen($tmp, "UTF-8")>0){
				$isFreeTextExist = 1;
			}
		}
		if($isFreeTextExist === 0){
			$part = str_replace("#FREE_TEXT_DISPLAY_NONE#"," hidden", $part);
		}else{
			$part = str_replace("#FREE_TEXT_DISPLAY_NONE#","", $part);
		}
		$part = str_replace("#FREE_TEXT#",$val['freeTextField'], $part);
		
		//Файлы
		$filesHtml = "";
		if($val['files'] == 1){
			$filesTpl = file_get_contents($_SERVER['DOCUMENT_ROOT']."/baform/templates/".$template."/file_input.html");
			$filesHtml = $filesTpl;
			$filesHtml = str_replace("#QUESTION_INDEX#", $val['indexBlock'], $filesHtml);
			$part = str_replace("Далее", "Пропустить/Далее", $part);
		}
		$part = str_replace("#FILES_BLOCK#",$filesHtml, $part);
		
		$hiddeFields = "";
		if($izW === 1){
			$hiddeFields .= '<input type="hidden" name="questioncount" value="'.count($_REQUEST['dataForm']).'">';
		}
		$hiddeFields .= '<input type="hidden" name="question_'.$val['indexBlock'].'" value="'.$val['questionText'].'">';
		$part = str_replace("#HIDDEN_FIELD#",$hiddeFields, $part);

        //Регулирование стилей количество элементов в строке радио кнопок
        $rowCountStile = 2;
        $styleRowCountStile = "";
        if(!empty($val['radiorowcount'])){
            if($val['radiorowcount'] == 2){// 2 по умолчанию стили. Ничего не делаю
                $styleRowCountStile = "";
            }else{
                $styleRowCountStile = " row-count_".$val['radiorowcount'];
            }
        }
        if(strlen($styleRowCountStile) > 0 && !in_array($rowCountStile, $msStyle)){
            $msStyle[] = $val['radiorowcount'];
        }
        $part = str_replace("#CLASS_ROW_COUNT#",$styleRowCountStile, $part);
		//echo "2-------------------- ".$izW." > ".$part;die;
		$out .= $part;
	}

    //Регулировка кол-ва элементов в строке радио кнопок
    if(count($msStyle)>0){
        foreach($msStyle as $val){
            $iStyle=0;
            $fr = "";
            for($iStyle=0; $iStyle<$val; $iStyle++){
               if(strlen($fr) === 0){
                   $fr = "1fr";
               }else{
                   $fr .= " 1fr";
               }
            }
            $css .= "\r\n#kviz-form .row-count_".$val."{\r\n";
                $css .= "grid-template-columns:".$fr.";\r\n";
            $css .= "}";
        }
    }
	$style = '<style type="text/css">'.$css.'</style>';

    $fromEmail = $_REQUEST['fromEmail'];

    $footerHeader = str_replace("#DATA_EMAIL_FROM#",  $fromEmail, $footerHeader);//Черезвычайно важный параметр. Иначе почта не придет
	$out = str_replace("#LIST_STEP_FORM#",  $out, $footerHeader);

	$out .= $style;
	if($_REQUEST['number'] == 1 || 1 == 1){
		$indexHtml = '
		<!DOCTYPE html>
		<html lang="ru">
		<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Посмотр квиза на отдельной странице</title>
		</head>
		<body>
		'.$out.'
		</body>
		</html>
		';
		file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/showrezulthtml/index.html", $indexHtml);
        file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/showrezulthtml/send_kviz.php", $codePhpSendKviz);

        //Формирую для скачивания
        file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/showrezulthtml/index-html", $out);
        file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/showrezulthtml/send_kviz-php", $codePhpSendKviz);
	}
	echo $out;
	die;
}
die;
?>