<?php 
if($_COOKIE['sejahtera_role'] == 10)
{
	include_once ("includes/setup_pemohon.inc.php");
}
else
{
	include_once ("includes/setup.inc.php");
}

$myID = fetch_postget_val('id',$_POST, $_GET);
$program = fetch_postget_val('program',$_POST, $_GET);
$borangitem = fetch_postget_val('borangitem',$_POST, $_GET);
$reloadBtn = fetch_postget_val('reloadBtn',$_POST, $_GET);
$readonly = fetch_postget_val('readonly',$_POST, $_GET);
$uniqueId = time(); //to prevent duplicated form name

$indicator_Query = "SELECT B.*
				  FROM u_pautanborang A
				  LEFT JOIN u_borangitem B ON A.id_borangitem = B.id_borangitem
				  WHERE 
				  B.linked_borangitem = ? 
				  AND A.id_program = ?
				  ORDER BY B.susunan";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $borangitem, PDO::PARAM_INT);
$PDO_stmt->bindValue(2, $program, PDO::PARAM_INT);
$PDO_stmt->execute();
$borangList = [];
while($result = $PDO_stmt->fetch(PDO::FETCH_ASSOC))
{
	$borangList[] = $result;
}

$indicator_Query = "SELECT *
				  FROM u_datatableitem
				  WHERE type = 1 AND id_borangitem = ?";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $borangitem, PDO::PARAM_INT);
$PDO_stmt->execute();
$datatableitem = $PDO_stmt->fetch(PDO::FETCH_ASSOC);

$indicator_Query = "SELECT *
				  FROM {$datatableitem['table_name']}
				  WHERE {$datatableitem['column_name']} = ?";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $myID, PDO::PARAM_INT);
$PDO_stmt->execute();
$indicator_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC);
?>
<div class="modal-header">
	<h5 class="modal-title">Daftar / Kemaskini Maklumat</h5>
	<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closeBtn" name="closeBtn" ></button>
</div>
<div class="modal-body">
	<form action="javascript:;" class="form-horizontal" name="indicator_form_<?=$uniqueId?>" id="indicator_form_<?=$uniqueId?>">
		<div class="form-body">
			<div class="row">
				<?php
					foreach($borangList as $key => $item)
					{
						switch ($item['id_inputtype']) 
						{
							case '1': //textbox
								createTextBox($item['label'], $item['input_name'], $item['placeholder']!=''?$item['placeholder']:$item['label'], $indicator_List[$item['value']], $item['label_size'], $readonly, $item['input_size'], $item['div_size'], $item['extra_param'], 'text');
								break;
							case '2': //dropdown
								createDropDown($PDO, $item['label'], $item['extra_param'], $item['input_name'], $indicator_List[$item['value']], $item['placeholder'], $item['input_size'], $item['label_size'], $item['div_size'], $readonly);
								break;
							case '3': //dropdown_sql
								createDropDown_sql($PDO, $item['label'], $item['extra_param'], $item['input_name'], $indicator_List[$item['value']], $item['placeholder'], $item['input_size'], $item['label_size'], $item['div_size'], $readonly);
								break;
							case '5': //custom
								echo $item['extra_param'];
								break;
							case '7': //action insert
								//script_url<BRE>borang_div<BRE>table_name<BRE>id_table<BRE>id_insert<BRE>id_update
								$action_value = 'general-borang_insert.php'.'<BRE>'.$borangitem.'<BRE>'.$item['value'];
								$allInfo = explode('<BRE>', $item['value']);
								echo '<input type="hidden" id="saveAction_'.$uniqueId.'" value=\''.$action_value.'\'>';
								break;
							case '8': //textbox uncopyable
								createTextBox($item['label'], $item['input_name'], $item['placeholder']!=''?$item['placeholder']:$item['label'], $indicator_List[$item['value']], $item['label_size'], $readonly, $item['input_size'], $item['div_size'], $item['extra_param'], 'text', '', ' oncopy="return false" onpaste="return false" ');
								break;
							case '12': //hidden input
								echo '<input type="hidden" id="'.$item['input_name'].'" value=\''.$indicator_List[$item['value']].'\'>';
								break;
						  default:
							echo '';
						}
						
						//build a json that will be use for validation here
						if($item['checking_type'] != '')
						{
							$validator[] = array($item['input_name'], $item['label'], $item['checking_type']);
						}
					}
					
					//set all hidden input for action
					foreach($actionArray as $actKey => $actItem)
					{
						echo '<input type="hidden" id="'.$actKey.'" value=\''.join(',', $actItem).'\'>';
					}
					
					echo '<input type="hidden" id="formValidator_'.$uniqueId.'" value=\''.json_encode($validator).'\'>';
				?>
			</div>
		</div>
	</form>
</div>
<div class="modal-footer">
	<?php
		echo '<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>';
		if($readonly == 0)
		{
			echo '<button type="button" class="btn btn-primary" id="simpanBtn">Simpan</button>';
		}
	?>
</div>

<script>
$(document).ready(function(){  

	$('#simpanBtn').click(function() {
		var formValidator = JSON.parse($('#formValidator_' + "<?=$uniqueId?>").val());
		console.log(formValidator);
		if (formValidator == null || checkInput(formValidator))
		{
			var saveAction = $('#saveAction_' + "<?=$uniqueId?>").val();
			if(saveAction != null)
			{
				//script_url<BRE>borang_div<BRE>table_name<BRE>id_table<BRE>id_insert<BRE>id_update
				var actions = saveAction.split("<BRE>");
				$(this).prop("disabled",true);
				var param = $('#indicator_form_' + "<?=$uniqueId?>").serialize();
				param += '&type=2';
				param += '&current_id=' + "<?=$myID?>";
				param += '&program=' + $('#id_borang_program').val();
				param += '&id_pemohon=' + $('#id_pemohon_borang').val();
				param += '&borangitem=' + actions[1];
				param += '&table=' + actions[2];
				if(actions.length >= 3) param += '&id_table=' + actions[3];
				if(actions.length >= 4) param += '&id_insert=' + actions[4];
				if(actions.length >= 5) param += '&id_update=' + actions[5];
				$.ajax({
					type: "POST", 
					url: "general-borang_insert.php", 
					data: param,

					success: function(res){
						if(res > 0)
						{
							swal.fire({
								text: "Berjaya Kemaskini Maklumat",
								icon: "success",
								buttonsStyling: false,
								confirmButtonText: "OK!",
								customClass: {
									confirmButton: "btn font-weight-bold btn-light-primary"
								}
							}).then(function() {
								$('#' + "<?=$reloadBtn?>").click();
								//window.parent.reloadTable();
								$("#closeBtn").click();
							});
						}
						else
						{
							swal.fire({
								text: "Error. " + res,
								icon: "error",
								buttonsStyling: false,
								confirmButtonText: "OK!",
								customClass: {
									confirmButton: "btn font-weight-bold btn-light-primary"
								}
							}).then(function() {
								$(this).prop("disabled",false);										
							});
						}
						
					} 
				});  //end ajax
			}
		}
	});		
});		
</script>