<?
	$form_action	= "insert";
	$button_value 	= "Submit";
	################################################## START INSERT ##################################################
	if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'insert'){
		$form_name = $_REQUEST["form_name"];
		mysqli_query($conn,"INSERT INTO dynamic_form(form_name) VALUES('$form_name')");
		$dynamic_form_id = mysqli_insert_id($conn);
		
		foreach($_REQUEST['form_field'] as $key=>$val){
			if(isset($_REQUEST['form_field'][$key]) && $_REQUEST['form_field'][$key] !=""){
				$form_field = $val;
				$field_name = $_REQUEST['field_name'][$key];
				$field_label = $_REQUEST['field_label'][$key];
				$is_required = isset($_REQUEST['is_required'][$key][0]) ? $_REQUEST['is_required'][$key][0] : "";
				$d_on_parent = isset($_REQUEST['d_on_parent'][$key][0]) ? $_REQUEST['d_on_parent'][$key][0] : "";
				$d_on_parent_element = $_REQUEST['d_on_parent_element'][$key];
				$d_parent_field = $_REQUEST['d_parent_field'][$key];
				$show_on_listing = isset($_REQUEST['show_on_listing'][$key][0]) ? $_REQUEST['show_on_listing'][$key][0] : "";
				
				mysqli_query($conn,"INSERT INTO dynamic_form_element(dynamic_form_id,form_field,field_name,field_label,is_required,d_on_parent,d_on_parent_element,d_parent_field,show_on_listing) VALUES('$dynamic_form_id','$form_field','$field_name','$field_label','$is_required','$d_on_parent','$d_on_parent_element','$d_parent_field','$show_on_listing')");
				$dynamic_form_element_id = mysqli_insert_id($conn);
				
				foreach($_REQUEST['check_list'][$key] as $check_list_key=>$check_list_val){
					//echo $check_list_key."-->".$check_list_val."<br>";
					mysqli_query($conn,"INSERT INTO dynamic_form_element_option(dynamic_form_id,dynamic_form_element_id,option_value) VALUES('$dynamic_form_id','$dynamic_form_element_id','$check_list_val')");
				}
			}
		}
		
		$_SESSION['info_message'] = "Dynamic form created sucessfully";
		$redirect = "index?page=dynamic_form_view";
		header("Location: $redirect");
		exit();
	}
	################################################## END INSERT ####################################################
	
	################################################## START EDIT ####################################################
	if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
		$form_action 	= "update";
		$button_value 	= "Update";
	
		$id = $_REQUEST["id"];
		$sql = "SELECT * FROM dynamic_form WHERE id = '$id' ";
		$rs = mysqli_query($conn,$sql);
		$data = mysqli_fetch_assoc($rs);
		$form_name = $data["form_name"];
		$dynamic_form_id = $data["id"];
		//$no_of_element = $data["no_of_element"];
	}
	################################################## END EDIT ######################################################
	
	################################################## START UPDATE ##################################################
	if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'update'){
		$dynamic_form_id = $_REQUEST["id"];
		$form_name = $_REQUEST["form_name"];
		mysqli_query($conn,"UPDATE dynamic_form SET form_name = '$form_name' WHERE id = '$dynamic_form_id' ");
		
		mysqli_query($conn,"DELETE FROM dynamic_form_element WHERE dynamic_form_id = '$dynamic_form_id' ");
		mysqli_query($conn,"DELETE FROM dynamic_form_element_option WHERE dynamic_form_id = '$dynamic_form_id' ");
		foreach($_REQUEST['form_field'] as $key=>$val){
			if(isset($_REQUEST['form_field'][$key]) && $_REQUEST['form_field'][$key] !=""){
				$form_field = $val;
				$field_name = $_REQUEST['field_name'][$key];
				$field_label = $_REQUEST['field_label'][$key];
				$is_required = isset($_REQUEST['is_required'][$key][0]) ? $_REQUEST['is_required'][$key][0] : "";
				$d_on_parent = isset($_REQUEST['d_on_parent'][$key][0]) ? $_REQUEST['d_on_parent'][$key][0] : "";
				$d_on_parent_element = $_REQUEST['d_on_parent_element'][$key];
				$d_parent_field = $_REQUEST['d_parent_field'][$key];
				$show_on_listing = isset($_REQUEST['show_on_listing'][$key][0]) ? $_REQUEST['show_on_listing'][$key][0] : "";
				
				mysqli_query($conn,"INSERT INTO dynamic_form_element(dynamic_form_id,form_field,field_name,field_label,is_required,d_on_parent,d_on_parent_element,d_parent_field,show_on_listing) VALUES('$dynamic_form_id','$form_field','$field_name','$field_label','$is_required','$d_on_parent','$d_on_parent_element','$d_parent_field','$show_on_listing')");
				$dynamic_form_element_id = mysqli_insert_id($conn);
				
				foreach($_REQUEST['check_list'][$key] as $check_list_key=>$check_list_val){
					//echo $check_list_key."-->".$check_list_val."<br>";
					mysqli_query($conn,"INSERT INTO dynamic_form_element_option(dynamic_form_id,dynamic_form_element_id,option_value) VALUES('$dynamic_form_id','$dynamic_form_element_id','$check_list_val')");
				}
			}
		}
		
		$_SESSION['info_message'] = "Dynamic form updated sucessfully";
		$redirect = "index?page=dynamic_form_view";
		header("Location: $redirect");
		exit();
	}
	################################################## END UPDATE ####################################################
?>
<!---------------------------------- Cloning Start --------------------------------------------->
	<div id="div_to_clone" style="display:none;">
		<div class="form-group" > 
			<div class="col-sm-2">
				<label class="control-label" for="Field">Field</label> 
				<? $gsi->getFormFieldList("form_field[]","","100%",false,"form-control form_field_drop_down"); ?>
			</div> 
			<div class="col-sm-2">
				<label class="control-label" for="Name">Name</label>  
				<input type="text" id="field_name" name="field_name[]" class="form-control" value="" placeholder="Field Name">
			</div>
			<div class="col-sm-2">
				<label class="control-label" for="Label">Label</label>  
				<input type="text" id="field_label" name="field_label[]" class="form-control" value="" placeholder="Label">
			</div>
			<div class="col-sm-1">
				<label class="control-label" for="Required">Required</label><br>
				<input type="checkbox" id="is_required" name="is_required[]" value="1">
			</div>
			<!--<div class="col-sm-3">
				<label class="control-label" for="D. on parent">D. on parent</label><br>
				<input type="checkbox" id="d_on_parent" name="d_on_parent[]" value="1" style="float:left;clear:right;">
				
				<input type="text" id="d_on_parent_element" name="d_on_parent_element[]" class="form-control" value="" placeholder="D. Field Option" style="float:right;width:105px;display:none;">
				<input type="text" id="d_parent_field" name="d_parent_field[]" class="form-control" value="" placeholder="D. Parent Field" style="float:right;width:110px;margin-right:3px;display:none;">
			</div>-->
			<div class="col-sm-2">
				<label class="control-label" for="Show on listing">Show on listing</label><br>
				<input type="checkbox" id="show_on_listing" name="show_on_listing[]" value="1">
				
				<div class="box-tools pull-right">
					<button type="button" class="btn btn-box-tool field_delete"><i class="fa fa-times"></i></button>
				</div>
			</div>
			<div class="col-sm-10" style="margin-top:5px;">
				<div class="external-options" style="font-size:11px;">
				
				</div>
				<div style="clear:both;"></div>
				<div class="input-group add_new_option" style="display:none;">
					<input type="text" class="form-control new-option" placeholder="Option">
					<div class="input-group-btn">
						<button type="button" class="btn btn-primary btn-flat add-new-option">Add Option</button>
					</div>
				</div>
			</div>
		</div>
	</div>
<!----------------------------------- Cloning End  --------------------------------------------->

<section class="content-header">
<? if(isset($_SESSION['info_message'])){ ?>
  <div class="alert alert-info alert-dismissable" style="margin-bottom:5px;">
	<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
	<? echo $_SESSION['info_message'];
		unset($_SESSION['info_message']);
	?>
  </div>
<? } ?>
</section>
<section class="content-header">
  <h1>
	Dynamic Form
  </h1>
</section>
<section class="content">
	<div class="row">
		<div class="col-xs-12">
			<!-- general form elements -->
              <div class="box box-primary">
                <form class="form-horizontal" method="post" name="form1" id="form1" action="index?page=dynamic_form_add&action=<?=$form_action;?>">
                  <div class="box-body">
					<div class="form-group">
						<label for="Form Name" class="col-sm-2 control-label">Form Name</label>
						<div class="col-sm-8">
							<input type="text" id="form_name" name="form_name" value="<?=$form_name;?>" class="form-control" placeholder="Form Name">
						</div>
					</div>
					<? 
					if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit'){
						$i = 0;
						$j = 1;
						//for($j = 1;$j<=$no_of_element;$j++){ 
						$sql_for_form_element = "SELECT * FROM dynamic_form_element WHERE dynamic_form_id = '$dynamic_form_id' ";
						$rs_for_form_element = mysqli_query($conn,$sql_for_form_element);
						if(mysqli_num_rows($rs_for_form_element) > 0){
						$no_of_element = mysqli_num_rows($rs_for_form_element);
						while($row_for_form_element = mysqli_fetch_assoc($rs_for_form_element)){
						
						$dynamic_form_element_id = $row_for_form_element["id"];
						$form_field = $row_for_form_element["form_field"];
						$field_name = $row_for_form_element["field_name"];
						$field_label = $row_for_form_element["field_label"];
						$is_required = $row_for_form_element["is_required"];
						$d_on_parent = $row_for_form_element["d_on_parent"];
						$d_on_parent_element = $row_for_form_element["d_on_parent_element"];
						$d_parent_field = $row_for_form_element["d_parent_field"];
						$show_on_listing = $row_for_form_element["show_on_listing"];
					?>
						<div class="element_class_div" id="element_<?=$j?>" alt="<?=$j?>" style="float:left;width:100%;color:blue;cursor:pointer;padding-bottom:10px;">
							<div class="col-sm-12">
								<? echo  $gsi->getFormFieldById($form_field)." : ".$field_label;?>
							</div>
						</div>
						<div id="element_no_<?=$j?>" alt="<?=$j?>" style="display:none;">
							<div class="form-group" > 
								<div class="col-sm-2">
									<label class="control-label" for="Field">Field</label> 
									<? $gsi->getFormFieldList("form_field[$i]",$form_field,"100%",false,"form-control form_field_drop_down"); ?>
								</div> 
								<div class="col-sm-2">
									<label class="control-label" for="Name">Name</label>  
									<input type="text" id="field_name" name="field_name[<?=$i?>]" class="form-control" value="<?=$field_name?>" placeholder="Field Name">
								</div>
								<div class="col-sm-2">
									<label class="control-label" for="Label">Label</label>  
									<input type="text" id="field_label" name="field_label[<?=$i?>]" class="form-control" value="<?=$field_label?>" placeholder="Label">
								</div>
								<div class="col-sm-1">
									<label class="control-label" for="Required">Required</label><br>
									<input type="checkbox" class="flat-red" id="is_required" name="is_required[<?=$i?>][]" value="1" <? echo ($is_required == 1) ? "checked" : "";?>>
								</div>
								<div class="col-sm-3">
									<label class="control-label" for="D. on parent">D. on parent</label><br>
									<input type="checkbox" class="flat-red d_on_parent" id="d_on_parent" name="d_on_parent[<?=$i?>][]" value="1" <? echo ($d_on_parent == 1) ? "checked" : "";?> style="float:left;clear:right;" alt="<?=$j;?>">
									
									<? $d_display = ($d_on_parent == 1) ? "block" : "none";?>
									<input type="text" id="d_on_parent_element<?=$j;?>" name="d_on_parent_element[<?=$i?>]" class="form-control" value="<?=$d_on_parent_element?>" placeholder="D. Field Option" style="float:right;width:100px;display:<?=$d_display;?>">
									<input type="text" id="d_parent_field<?=$j;?>" name="d_parent_field[<?=$i;?>]" class="form-control" value="<?=$d_parent_field?>" placeholder="D. Parent Field" style="float:right;width:110px;margin-right:3px;display:<?=$d_display;?>">
								</div>
								<div class="col-sm-2">
									<label class="control-label" for="Show on listing">Show on listing</label><br>
									<input type="checkbox" class="flat-red" id="show_on_listing" name="show_on_listing[<?=$i?>][]" value="1" <? echo ($show_on_listing == 1) ? "checked" : "";?>>
									
									<div class="box-tools pull-right">
										<button type="button" alt="<?=$j?>" class="btn btn-box-tool field_delete"><i class="fa fa-times"></i></button>
									</div>
								</div>
								<div class="col-sm-10" style="margin-top:5px;">
									<div class="external-options" style="font-size:11px;">
										<?
										$sql_for_form_element_option = "SELECT * FROM dynamic_form_element_option WHERE dynamic_form_id = '$dynamic_form_id' AND dynamic_form_element_id = '$dynamic_form_element_id' ";
										$rs_for_form_element_option = mysqli_query($conn,$sql_for_form_element_option);
										if(mysqli_num_rows($rs_for_form_element_option) > 0){
											while($row_for_form_element_option = mysqli_fetch_assoc($rs_for_form_element_option)){
											$option_value = $row_for_form_element_option["option_value"];
										?>
										<div class="check_list"><?=$option_value;?><input type="hidden" name="check_list[<?=$i;?>][]" value="<?=$option_value;?>"><span class="remove_check_list"><i class="fa fa-times"></i></span></div>
										<? 
											} } 
										?>
									</div>
									<div style="clear:both;"></div>
									<? $display = ($form_field == 2 || $form_field == 3 || $form_field == 4 || $form_field == 5) ? "block" : "none";?>
									<div class="input-group add_new_option" style="display:<?=$display;?>;">
										<input type="text" class="form-control new-option" style="width:89%;" placeholder="Option">
										<div class="input-group-btn">
											<button type="button" class="btn btn-primary btn-flat add-new-option">Add Option</button>
										</div>
									</div>
								</div>
							</div>
						</div>
					<? 
						$i++;
						$j++;
						} }
					}
					?>
					<div class="form-group col-sm-12 div_to_append">						
						<label class="add_one_more" style="margin-left:1%;cursor:pointer" for="Phone"><span class="fa fa-plus"></span> Add one more </label>
					</div>
                  </div><!-- /.box-body -->
                  <div class="box-footer">
					<input type="hidden" name="no_of_element" id="no_of_element" value="<?=$no_of_element;?>">
					<input type="hidden" name="id" id="id" value="<?=$id;?>">
                    <button type="submit" id="add" name="add" value="submit" class="btn btn-primary"><?=$button_value;?></button>
                  </div>
                </form>
              </div><!-- /.box -->
		</div>
	</div>
</section>
<style>
.check_list{
	float: left;
    clear: right;
    margin-right: 3px;
	background-color: #337ab7;
	border-color: #337ab7;
	color: #fff;
	cursor: default;
	padding: 5px 10px;
    margin-bottom: 4px;
    box-shadow: 0 1px 1px rgba(0,0,0,0.1);
    text-shadow: 0 1px 1px rgba(0,0,0,0.1);
    border-radius: 3px;
}
.remove_check_list{
	padding:0px 0px 0px 5px;
	float:right;
	cursor:pointer;
}
</style>
<script type="text/javascript">
$(function(){
	$('.add_one_more').click(function(){
		var no_of_element = $('#no_of_element').val();
		form_setting = no_of_element;
		if(no_of_element == ""){
			no_of_element = 1;
			form_setting = 0;
		}else{
			no_of_element++;
		}
		$('#no_of_element').val(no_of_element);
		
		$('#div_to_clone').show();		
		var cloned_div = $('#div_to_clone').clone().attr("id","element_no_"+no_of_element);
		$('.div_to_append').before(cloned_div);		
		$('#div_to_clone').hide();		
		
		$('#element_no_'+no_of_element).attr("alt",no_of_element);
		
		$('#element_no_'+no_of_element).children().find("#form_field").attr("name","form_field["+form_setting+"]");
		$('#element_no_'+no_of_element).children().find("#field_name").attr("name","field_name["+form_setting+"]");
		$('#element_no_'+no_of_element).children().find("#field_label").attr("name","field_label["+form_setting+"]");
		
		$('#element_no_'+no_of_element).children().find("#is_required").attr("id","is_required"+no_of_element);
		$("#is_required"+no_of_element).attr("name","is_required["+form_setting+"][]");
		$("#is_required"+no_of_element).iCheck({
			checkboxClass: 'icheckbox_flat-blue'
		});
		$('#element_no_'+no_of_element).children().find("#d_on_parent").attr("id","d_on_parent"+no_of_element);
		$("#d_on_parent"+no_of_element).attr("name","d_on_parent["+form_setting+"][]");
		$("#d_on_parent"+no_of_element).attr("alt",no_of_element);
		$("#d_on_parent"+no_of_element).iCheck({
			checkboxClass: 'icheckbox_flat-blue'
		});
		$("#d_on_parent"+no_of_element).addClass("d_on_parent");
		$('#element_no_'+no_of_element).children().find("#show_on_listing").attr("id","show_on_listing"+no_of_element);
		$("#show_on_listing"+no_of_element).attr("name","show_on_listing["+form_setting+"][]");
		$("#show_on_listing"+no_of_element).iCheck({
			checkboxClass: 'icheckbox_flat-blue'
		});
		$('#element_no_'+no_of_element).children().find(".field_delete").attr("alt",no_of_element);
		$('#element_no_'+no_of_element).children().find("#d_on_parent_element").attr("id","d_on_parent_element"+no_of_element);
		$('#element_no_'+no_of_element).children().find("#d_parent_field").attr("id","d_parent_field"+no_of_element);
	});
	
	$("#form1").on("click",".add-new-option",function(e){
      e.preventDefault()
	  var form_setting = $(this).parent().parent().parent().parent().parent().attr("alt");
	  form_setting--;
      //Get value and make sure it is not null
      var val = $(this).parent().parent().children('.new-option').val();
	  //alert(val);
      if (val.length == 0) {
        return
      }

      //Create events
      var event = $('<div />')
      event.addClass('check_list')
      event.html(val)
	  $('<input>').attr({
		type: 'hidden',
		name: 'check_list['+form_setting+'][]',
		value: val
	  }).appendTo(event);
	  $('<span class="remove_check_list"><i class="fa fa-times"></i></span>').appendTo(event);
      //$('#external-options').prepend(event)
      $(this).parent().parent().parent().children('.external-options').prepend(event)

      //Remove event from text input
      $(this).parent().parent().children('.new-option').val('');
    });
	
	$("#form1").on("click",".remove_check_list",function(){
		$(this).parent().remove();
	});
	
	$("#form1").on("change",".form_field_drop_down",function(){
		if($(this).val() == 2 || $(this).val() == 3 || $(this).val() == 4 || $(this).val() == 5){
			$(this).parent().parent().parent().children().find('.add_new_option').show();
		}else{
			$(this).parent().parent().parent().children().find('.remove_check_list').trigger("click");
			$(this).parent().parent().parent().children().find('.new-option').val("");
			$(this).parent().parent().parent().children().find('.add_new_option').hide();
		}
	});
	$("#form1").on("click",".field_delete",function(){
		if(confirm("Are you sure! You want to remove")){
			var no_of_element = $(this).attr("alt");
			$('#element_no_'+no_of_element).children().find('.remove_check_list').trigger("click");
			$('#element_no_'+no_of_element).remove();
			$('#element_'+no_of_element).remove();
		};
	});
	
	$("#form1").on("click",".element_class_div",function(){
		var element_no = $(this).attr("alt");
		$("#element_no_"+element_no).toggle();
	});
	$("#form1").on("ifChanged",".d_on_parent",function(event){
		var element_no = $(this).attr("alt");
		if(event.target.checked){
			$("#d_on_parent_element"+element_no).show();
			$("#d_parent_field"+element_no).show();
		}else{
			$("#d_on_parent_element"+element_no).hide();
			$("#d_on_parent_element"+element_no).val("");
			
			$("#d_parent_field"+element_no).hide();
			$("#d_parent_field"+element_no).val("");
		}
	});
});
</script>