<?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);
$type = fetch_postget_val('type',$_POST, $_GET);
$from = fetch_postget_val('from',$_POST, $_GET);
$readonly = 0;

$indicator_Query = "SELECT *
					FROM m_pemohon
					WHERE id_pemohon = ?";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $myID, PDO::PARAM_INT);
$PDO_stmt->execute();
$pemohon_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC);

$indicator_Query = "SELECT *
					FROM m_bayaran_KH
					WHERE id_pemohon = ?";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $myID, PDO::PARAM_INT);
$PDO_stmt->execute();
$bayaranKH_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC);

$id_bayaran_KH = $bayaranKH_List['id_bayaran_KH'];

$indicator_Query = "SELECT *
					FROM m_waris
					WHERE id_pemohon = ?
					AND status = 1";
$PDO_stmt = $PDO->prepare($indicator_Query);
$PDO_stmt->bindValue(1, $myID, PDO::PARAM_INT);
$PDO_stmt->execute();
$waris_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC);

$id_program = $pemohon_List['id_program'];
?>

<div class="modal-header">
	<h5 class="modal-title">Permohonan Khairat Kematian & Pertukaran Status
	<br>Pemohon : <b><?=$pemohon_List['nama_pemohon']?></b>
	<br>No KP : <b><?=$pemohon_List['kpbaru_pemohon']?></b>
	<br>Tarikh Daftar Program : <b><?=formatDate($pemohon_List['tkh_daftar'], "d M Y")?></b>
	</h5>
	<button type="button" class="close" data-dismiss="modal" aria-label="Close" id="closeBtn" name="closeBtn" ></button>
</div>
<div class="modal-body">
	<input type="hidden" id="dz_myID" value="<?=$myID?>">
	<form action="javascript:;" class="form-horizontal" name="indicator_form" id="indicator_form">
		<div class="form-body">
			<div class="row">
				<div class="col-md-12">
					<ul class="nav nav-tabs" id="myTab" role="tablist">
						<li class="nav-item">
							<a class="nav-link active" id="info-tab" data-toggle="tab" href="#info">
								<span class="nav-text">Maklumat Kematian</span>
							</a>
						</li>
						<li class="nav-item">
							<a class="nav-link <?php echo ($myID > 0)?'':'disabled'; ?>" id="waris-tab" data-toggle="tab" href="#waris">
								<span class="nav-text">Maklumat Waris</span>
							</a>
						</li>
					</ul>
					<div class="tab-content" id="myTabContent">
						<div class="tab-pane fade show active" id="info" role="tabpanel" aria-labelledby="info-tab">
							<div class="row">
								<div class="col-md-12" style="margin-top: 20px;">
									<?php
										if($pemohon_List['id_sahmati'] == 1 && $pemohon_List['ulasan_sahmati'] != '')
										{
											createTextArea('<b>Ulasan Query Pengesahan</b>', 'ulasan_sahmati', '', $pemohon_List['ulasan_sahmati'], 1, 3, 7, 12, '', 3);
										}
										createDropDown($PDO, 'Kategori', 'i_khairatkat', 'id_khairatkat', $pemohon_List['id_khairatkat'], 'Pilih Kategori', 7, 3, 12, $readonly);
										createTextBox('No. Sijil Mati', 'no_sijilmati', 'No. Sijil Mati', $pemohon_List['no_sijilmati'], 3, $readonly, 7, 12, '', 'text');
										createDateTB('Tarikh Kematian', 'tkh_mati', 'Tarikh Kematian',(formatDate($pemohon_List['tkh_mati'], 'd M Y') == ''?date('d M Y'):formatDate($pemohon_List['tkh_mati'], 'd M Y')), 3, $readonly, 4, 12);	
										createTextArea('Ulasan', 'ulasan_mati', 'Sila nyatakan ulasan', $pemohon_List['ulasan_mati'], $readonly, 3, 7, 12, '', 10);	

										if($bayaranKH_List['id_bayaran_KH'] > 0 && $type == 1)
										{
											createDropDown($PDO, 'Kategori Bayaran', 'i_bayarankat', 'id_bayarankat', $bayaranKH_List['id_bayarankat'], 'Pilih Kategori Bayaran', 7, 3, 12, $readonly);
											createDropDown($PDO, 'Fasa Bayaran', 'i_bayaranfasa', 'id_bayaranfasa', $bayaranKH_List['id_bayaranfasa'], 'Pilih Fasa Bayaran', 7, 3, 12, $readonly);
											createDropDown($PDO, 'Cara Bayaran', 'i_carabayar', 'id_carabayarKH', $bayaranKH_List['id_carabayar'], 'Pilih Cara Bayaran', 7, 3, 12, $readonly);
											createDropDown($PDO, 'Bank Dibayar', 'i_bank', 'id_bankKH', $bayaranKH_List['id_bank'], 'Pilih Bank', 7, 3, 12, $readonly);
											createTextBox('No. Akaun Dibayar', 'no_akaunKH', 'No. Akaun Dibayar', $bayaranKH_List['no_akaun'], 3, $readonly, 7, 12, '', 'text');	
											createDateTB('Tarikh Bayaran', 'tkh_bayar', 'Tarikh Bayaran',(formatDate($bayaranKH_List['tkh_bayar'], 'd M Y') == ''?date('d M Y'):formatDate($bayaranKH_List['tkh_bayar'], 'd M Y')), 3, $readonly, 4, 12);	
											createTextBox('No. EFT', 'no_eft', 'No. EFT', $bayaranKH_List['no_eft'], 3, $readonly, 7, 12, '', 'text');											
										}
										echo '<div style="text-align:center;margin-top: 10px;">';
											echo '<button type="button" class="btn btn-primary" id="simpaninfoBtn">Seterusnya</button>';
										echo '</div>';					
									?>
								</div>
							</div>
						</div>
						<div class="tab-pane fade show" id="waris" role="tabpanel" aria-labelledby="waris-tab">
							<div class="row">
								<div class="col-md-12" style="margin-top: 20px;">
									<?php
										createTextBox('Nama Waris', 'nama_waris', 'Nama Waris', $waris_List['nama_waris'], 3, $readonly, 7, 12, '', 'text', 'Sila masukkan nama waris');
										createTextBox('No KP Waris', 'kpbaru_waris', 'No KP Waris', $waris_List['kpbaru_waris'], 3, $readonly, 7, 12, '', 'numonly', 'Sila masukkan No KP Waris','maxlength="12"');
										createTextBox('Alamat', 'alamat_waris', 'Alamat', $waris_List['alamat_waris'], 3, 0, 7, 12, '', 'text');
										createTextBox('', 'alamat_waris2', 'Alamat', $waris_List['alamat_waris2'], 3, 0, 7, 12, '', 'text');
										createTextBox('', 'alamat_waris3', 'Alamat', $waris_List['alamat_waris3'], 3, 0, 7, 12, '', 'text');
										
										$mySQL = "SELECT id_poskod AS id, CONCAT(desk_poskod, '-', bandar) as name, bandar AS cTag1, id_negeri AS cTag2 FROM i_poskod ORDER BY id_poskod";
										
										createDropDown_sql($PDO, 'Poskod', $mySQL, 'id_poskodwaris', $waris_List['id_poskodwaris'], 'Poskod', 4, 3, 12, $readonly);
										createTextBox('Bandar', 'bandar_waris', 'Bandar', $waris_List['bandar_waris'], 3, 0, 4, 12, '', 'text');
										createDropDown($PDO, 'Negeri', 'i_negeri', 'id_negeriwaris', $waris_List['id_negeriwaris'], 'Negeri', 4, 3, 12, $readonly);
										createTextBox('Tel HP/Rumah', 'tel_hpwaris', 'Tel HP/Rumah', $waris_List['tel_hpwaris'], 3, 0, 4, 12, '', 'numonly', '','maxlength="11"');
										//createTextBox('Tel Rumah', 'tel_rumahwaris', 'Tel Rumah', $waris_List['tel_rumahwaris'], 3, 0, 4, 12, '', 'numonly', '','maxlength="9"');
										createTextBox('Emel', 'emel_waris', 'Emel', $waris_List['emel_waris'], 3, 0, 4, 12, '', 'text');
										
										$mySQL = "SELECT id_bank AS id, desk_bank as name, digit_bank_min AS cTag1, digit_bank AS cTag2 FROM i_bank ORDER BY susunan";
										
										createDropDown_sql($PDO, 'Bank', $mySQL, 'id_bankwaris', $waris_List['id_bankwaris'], 'Bank', 4, 3, 12, $readonly);
										createTextBox('No Akaun', 'no_akaunwaris', 'No Akaun', $waris_List['no_akaunwaris'], 3, 0, 4, 12, '', 'text');		
										
										echo '<div class="col-md-12 form-group row">';
											echo '<label id="khairat_dz_label" class="col-md-3 col-form-label">Muat Naik</label>';
											echo '<div class="col-md-9">
													<div class="dropzone dropzone-default" id="khairat_dz">
														<div class="dropzone-msg dz-message needsclick">
															<h3 class="dropzone-msg-title">Dokumen</h3>
															<span class="dropzone-msg-desc">Sila Muat Naik Dokumen Di Sini.</span>
														</div>
													</div>
													*Klik pada ruangan diatas untuk muatnaik dokumen (hanya format gambar/pdf sahaja)
												</div>';
										echo '</div>';
									?>
								
								</div>
							</div>
							<div class="row" style="text-align:center;margin-top: 10px;">
								<div class="col-md-12" style="margin-top: 20px;">
								
									<?php
										if($readonly == 0)
										{
											echo '<button type="button" class="btn btn-primary" id="indicator_simpanBtn">Hantar/Kemaskini Permohonan Khairat</button>';
										}						
									?>
								
								</div>
							</div>
						</div>
					</div>
				</div>
				
			</div>
		</div>
	</form>
</div>
<div class="modal-footer">
	<?php
		echo '<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>';
	?>
</div>

<script>
var uploadPath = 'upload_khairat';
var myDZ_khairat = new Dropzone("div#khairat_dz", {
	acceptedFiles: "image/jpg,image/jpeg,image/png,image/bmp,application/pdf",
	//maxFiles: 1,
	maxFilesize: 2,//max file size in MB,
	url: "general-photo_upload.php",
	paramName: "uploadfile",
	dictDefaultMessage : '<span style="font-style:italic"><h1>Drop files to upload</h1><h3>(or click)</h3></span>',
	init: function() {
		$.get("general-photo_upload.php", {uploadId:$('#dz_myID').val(), generalName:"", uploadFolder:uploadPath}, function(data) {
			$.each(data, function(key,value){
				var mockFile = { name: value.name, size: value.size };				
				myDZ_khairat.emit("addedfile", mockFile);
				if(value.name.trim().endsWith(".pdf"))
				{
					myDZ_khairat.emit("thumbnail", mockFile, uploadPath + "/pdf.jpg");
				}
				else
				{
					myDZ_khairat.emit("thumbnail", mockFile, uploadPath + "/" + $('#dz_myID').val() + "/" + value.name);
				}
				myDZ_khairat.emit("complete", mockFile);
				myDZ_khairat.files.push(mockFile);
			});
		});
	}
});

myDZ_khairat.on("error", function(file, errorMessage) {
	alert("ERROR " + errorMessage);
	myDZ_khairat.removeFile(file);
});

myDZ_khairat.on("success", function(file, photoPath) {
	file.previewElement.querySelector("[data-dz-name]").innerHTML = photoPath;
	console.log(photoPath);
	console.log(photoPath.trim().endsWith(".pdf"));
	if(photoPath.trim().endsWith(".pdf"))
	{
		myDZ_khairat.emit("thumbnail", file, uploadPath + "/pdf.jpg");
	}
	else
	{
		myDZ_khairat.emit("thumbnail", file, uploadPath + "/" + $('#dz_myID').val() + "/" + photoPath);
	}
});

myDZ_khairat.on("sending", function(file, xhr, formData){
	formData.append("uploadId", $('#dz_myID').val());
	//formData.append("generalName", "banner.jpg");
	formData.append("uploadFolder", uploadPath);
	//myDropzone.removeAllFiles(); //remove all 1st
});
	
myDZ_khairat.on("dictRemoveFileConfirmation", function(file, xhr, formData){
	formData.append("uploadId", $('#dz_myID').val());
});

myDZ_khairat.on("addedfile", function(file) {
	var deleted = false;
	if(deleted == false)
	{
		file.previewElement.addEventListener("click", function() {
			var filesrc = uploadPath + "/" + $('#dz_myID').val() + "/" + file.previewElement.querySelector('[data-dz-name]').innerHTML.trim();
			if(filesrc.endsWith(".pdf"))
			{
				window.open(filesrc);
			}
			else
			{
				loadMyModal('general-photo_view.php?src="' + filesrc + '"', '#khairat-modal');
			}
		});
		
		// Create the remove button
		var removeButton = Dropzone.createElement('<a class="btn btn-xs red"><i class="fa fa-trash-o"></i>Remove Image</a>');

		// Listen to the click event
		removeButton.addEventListener("click", function(e) {
			e.preventDefault();
			e.stopPropagation();

			var deleteFileName = file.previewElement.querySelector('[data-dz-name]').innerHTML;
			x = confirm("Are you sure to delete " + deleteFileName + "?");
			if(!x)  return false;
			var name = deleteFileName;                
			$.ajax({
				type: "POST",
				url: "general-photo_delete.php",
				data: "uploadId=" + $('#dz_myID').val() + "&filename="+name+ "&uploadFolder=" + uploadPath,
				dataType: "html"
			});
			myDZ_khairat.removeFile(file);
		});

		file.previewElement.appendChild(removeButton);
	}
	
});

$(document).ready(function(){  
	$('.kp_tb, .numonly, #kpbaru_waris, #tel_hpwaris, #tel_rumahwaris, #no_akaunwaris').keypress(function(evt){
		evt = (evt) ? evt : window.event;
		var charCode = (evt.which) ? evt.which : evt.keyCode;
		if ((charCode >= 48 && charCode <= 57)) {
			return true;
		}
		return false;
	});
	
	$("#id_poskodwaris").change(function(){ 
		if($("#id_poskodwaris").val() > 0)
		{
			var element = $(this).find('option:selected'); 
			var cTag1 = element.attr("cTag1"); 
			var cTag2 = element.attr("cTag2"); 

			$('#bandar_waris').val(cTag1); 
			$('#id_negeriwaris').val(cTag2); 
			$('#id_negeriwaris').trigger('change');
			$('#bandar_waris').prop('disabled', true);
			$('#id_negeriwaris').prop('disabled', true);
		}
	}); 
	$('#id_poskodwaris').trigger('change');

	$('#id_bankwaris').change(function(){
		var element = $(this).find('option:selected'); 
		var cTag1 = element.attr("cTag1"); 
		var cTag2 = element.attr("cTag2"); 
		$("#no_akaunwaris").prop('minLength', cTag1);
		$("#no_akaunwaris").prop('maxLength', cTag2);
	});
	$('#id_bankwaris').trigger('change');

	$('.myDatePicker').datepicker({
		autoclose: true,
		clearBtn: true,
		format: "dd M yyyy",
		todayHighlight: true,
		orientation: "bottom left",
		templates: {
			leftArrow: '<i class="la la-angle-left"></i>',
			rightArrow: '<i class="la la-angle-right"></i>'
		}
	});

	$('.select2').select2({ width: '100%' }); 	
	
	$('#simpaninfoBtn').click(function() {
		$('#waris-tab').click();
	});	
	
	$('#indicator_simpanBtn').click(function() {
		var indicator_list = [[]];
		indicator_list.push(['id_khairatkat', 'Kategori', 'dd']);		
		indicator_list.push(['no_sijilmati', 'No. Sijil Mati', 'tb']);
		indicator_list.push(['tkh_mati', 'Tarikh Kematian', 'tb']);
		indicator_list.push(['ulasan_mati', 'Ulasan', 'tb']);
		
		if($('#id_khairatkat').val() == 1 || $('#id_khairatkat').val() == 4)
		{
			indicator_list.push(['nama_waris', 'Nama Waris', 'tb']);
			indicator_list.push(['kpbaru_waris', 'KP Baru Waris', 'tb']);
			indicator_list.push(['id_bankwaris', 'Bank', 'dd']);
			indicator_list.push(['no_akaunwaris', 'No. Akaun', 'tb']);
		}
		
		if (checkInput(indicator_list))
		{
			$(this).prop("disabled",true);
			var from = "<?=$from?>";
			var param = $('#indicator_form').serialize();
			$.ajax({
				type: "POST", 
				url: "general-khairat_insert.php", 
				data: param+ '&id=' + "<?=$myID?>" + '&id_program=' + "<?=$id_program?>" + '&type=' + "<?=$type?>" + '&id_bayaran_KH=' + "<?=$id_bayaran_KH?>",

				success: function(res){
					if(res > 0)
					{
						swal.fire({
							text: "Berjaya Tambah/Kemaskini Maklumat Khairat",
							icon: "success",
							buttonsStyling: false,
							confirmButtonText: "OK!",
							customClass: {
								confirmButton: "btn font-weight-bold btn-light-primary"
							}
						}).then(function() {
							if(from == 1)
							{								
								window.location.reload();
							}
							else
							{
								window.parent.reloadTable();
							}
							$("#closeBtn").click();
						});
					}	
					else if (res == -999)
					{
						swal.fire({
							text: "Tarikh kematian adalah kurang dari tarikh daftar permohonan. Kategori layak menerima khairat tidak dibenarkan.",
							icon: "error",
							buttonsStyling: false,
							confirmButtonText: "OK!",
							customClass: {
								confirmButton: "btn font-weight-bold btn-light-primary"
							}
						}).then(function() {
							$(this).prop("disabled",false);									
						});							
					}
					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>