<?php 
include_once ("includes/setup.inc.php");

$myID = fetch_postget_val('id',$_POST, $_GET);
$readonly = fetch_postget_val('readonly',$_POST, $_GET);
$temp = ($my_details->usr_id).'_'.time();

$indicator_Query = "SELECT A.*
				  FROM i_banner A
				  WHERE A.id_banner = ?";
$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);

$uploadId = $myID;
if($myID == 0)
{
	$uploadId = 'temp_'.$my_details->usr_id;
}
?>
<div class="modal-header">
	<h5 class="modal-title">Tambah/Kemaskini Perundangan</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" id="indicator_form">
		<div class="form-body">
			<div class="row">
				<?php
					createTextBox('Tajuk', 'tajuk', 'Tajuk', $indicator_List['tajuk'], 3, $readonly, 7, 12, '', 'text', 'Sila masukkan tajuk perundangan');
					createTextBox('Keyword', 'tajuk_butang', 'Keyword', $indicator_List['tajuk_butang'], 3, $readonly, 7, 12, '', 'text');
					createTextBox('Kategori', 'hyperlink', 'Kategori', $indicator_List['hyperlink'], 3, $readonly, 7, 12, '', 'text');
					//createDateTB('Tarikh Mula', 'tkh_mula', 'Tarikh Mula',(formatDate($indicator_List['tkh_mula'], 'd M Y') == ''?date('d M Y'):formatDate($indicator_List['tkh_mula'], 'd M Y')), 3, 4, 0, 12);					
					//createDateTB('Tarikh Tamat', 'tkh_tamat', 'Tarikh Tamat',(formatDate($indicator_List['tkh_tamat'], 'd M Y') == ''?date('d M Y'):formatDate($indicator_List['tkh_tamat'], 'd M Y')), 3, 4, 0, 12);					
					
					$flag_aktif = 1;
					if($myID > 0)
					{
						$flag_aktif = $indicator_List['aktif'];						
					}					
					$myArray = [];
					$myArray[] = array(1, 'YA');
					createDropDown_Array('Aktif', $myArray, 'aktif', $flag_aktif, 'TIDAK', 4, 3, 12, $readonly);
				?>
				
			</div>
			<div class="form-group row">
				<label class="col-form-label col-lg-3 col-sm-12 text-lg-right">Muat Naik Dokumen</label>
				<div class="col-lg-4 col-md-9 col-sm-12">
					<div class="dropzone dropzone-default" id="myDropzone">
						<div class="dropzone-msg dz-message needsclick">
							<h3 class="dropzone-msg-title">Klik di sini untuk muat naik dokumen</h3>
							<span class="dropzone-msg-desc">Hanya fail .pdf sahaja</span>
						</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>';
		if($readonly == 0)
		{
			echo '<button type="button" class="btn btn-primary" id="indicator_simpanBtn">Simpan</button>';
		}
	?>
</div>

<script>
var uploadPath = "upload_banner";
var myDropzone = new Dropzone("div#myDropzone", {
	acceptedFiles: "application/pdf",
	maxFiles: 1,
	url: "general-photo_upload.php",
	paramName: "uploadfile", // The name that will be used to transfer the file
	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:"<?=$uploadId?>", generalName:"doc.pdf", uploadFolder:uploadPath}, function(data) {
			$.each(data, function(key,value){
	console.log(key);
				var mockFile = { name: value.name, size: value.size };				
				myDropzone.emit("addedfile", mockFile);
				//myDropzone.emit("thumbnail", mockFile, uploadPath + "/" + "<?=$uploadId?>" + '/' + value.name);
				myDropzone.emit("thumbnail", mockFile, uploadPath + "/pdf.jpg");
				myDropzone.emit("complete", mockFile);
				myDropzone.files.push(mockFile);
			});
		});
	}
});

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

myDropzone.on('success', function(file, photoPath) {
	console.log(file);
	file.previewElement.querySelector('[data-dz-name]').innerHTML = photoPath;
	file.previewElement.querySelector('[data-dz-thumbnail]').style.height = 120;
	file.previewElement.querySelector('[data-dz-thumbnail]').style.width = 120;
	//file.previewElement.querySelector('[data-dz-thumbnail]').css('width', '120');
	//file.previewElement.querySelector('[data-dz-thumbnail]').css('object-fit', 'cover');
	myDropzone.emit("thumbnail", file, uploadPath + "/" + "<?=$uploadId?>" + '/' + photoPath);
	/*
	{
		$('[data-dz-thumbnail]').css('height', '120');
		$('[data-dz-thumbnail]').css('width', '120');
		$('[data-dz-thumbnail]').css('object-fit', 'cover');
	}; 
	*/
});

myDropzone.on('sending', function(file, xhr, formData){
	formData.append('uploadId', "<?=$uploadId?>");
	formData.append('generalName', "doc.pdf");
	formData.append('uploadFolder', uploadPath);
	myDropzone.removeAllFiles(); //remove all 1st
});
	
myDropzone.on('dictRemoveFileConfirmation', function(file, xhr, formData){
	formData.append('uploadId', "<?=$uploadId?>");
});

myDropzone.on("addedfile", function(file) {
	var deleted = false;
	/*
	if (myDropzone.files.length) {
		var _i, _len;
		for (_i = 0, _len = myDropzone.files.length; _i < _len - 1; _i++) // -1 to exclude current file
		{
			if(myDropzone.files[_i].name === file.name && myDropzone.files[_i].size === file.size && (myDropzone.files[_i].lastModifiedDate == null || myDropzone.files[_i].lastModifiedDate.toString() === file.lastModifiedDate.toString()))
			{
				alert(file.name + ' already exist in database and this file will not be process');
				myDropzone.removeFile(file);
				deleted = true;
			}
		}
	}
	*/
	
	if(deleted == false)
	{
		//var src = "upload_banner/"+ "<?=$myID?>" + '/' + file.name;

		file.previewElement.addEventListener("click", function() {
			loadMyModal('general-photo_view.php?src="' + file.previewElement.querySelector("img").src + '"', '#large_photo-modal');
			//$('#large_photo-modal').modal({remote: 'general-photo_view.php?src="' + file.previewElement.querySelector("img").src + '"' });
			//$('#large_photo-modal').modal('show');
		});
		
		// 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) {
			// Make sure the button click doesn't submit the form:
			e.preventDefault();
			e.stopPropagation();

			// If you want to the delete the file on the server as well,
			// you can do the AJAX request here.
			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=" + "<?=$uploadId?>" + "&filename="+name+ "&uploadFolder=" + uploadPath,
				dataType: 'html'
			});
			// Remove the file preview.
			myDropzone.removeFile(file);
        });

        // Add the button to the file preview element.
        file.previewElement.appendChild(removeButton);
	}
	
});

$(document).ready(function(){  

	$('.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%' }); 
	
	$('#indicator_simpanBtn').click(function() {
		var indicator_list = [[]];
		indicator_list.push(['tajuk', 'Tajuk', 'tb']);
		indicator_list.push(['tkh_mula', 'Tarikh Mula', 'tb']);		
		indicator_list.push(['tkh_tamat', 'Tarikh Tamat', 'tb']);
		
		if (checkInput(indicator_list))
		{
			$(this).prop("disabled",true);
			var param = $('#indicator_form').serialize();
			$.ajax({
				type: "POST", 
				url: "in_banner-tambah_insert.php", 
				data: param+ '&id=' + "<?=$myID?>"+ '&temp=' + "<?=$temp?>",

				success: function(res){
					if(res > 0)
					{
						swal.fire({
							text: "Berjaya Tambah/Kemaskini Maklumat Perundangan",
							icon: "success",
							buttonsStyling: false,
							confirmButtonText: "OK!",
							customClass: {
								confirmButton: "btn font-weight-bold btn-light-primary"
							}
						}).then(function() {
							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>
