@extends('layouts.app')

@section('content')
<?php usort($tableGrid, "SiteHelpers::_sort"); ?>
<div class="page-titles">
  <h2> {{ $pageTitle }} <small> {{ $pageNote }} </small></h2>
</div>


	<div id="datasopikView"></div>	
	<div id="datasopikGrid">
		<div class="card">
			<div class="card-body">
			@include( $pageModule.'/toolbar')
		
		
			<div class="table-responsive">			
				<table id="datasopikTable" class="display table  table-striped table-hover" cellspacing="0" width="100%">
			        <thead>
			            <tr>
			            	<th>ID</th>	
			            	
			            @if($setting['view-method'] =='expand')<th></th>@endif
			           

			            
		            <?php foreach ($tableGrid as $t) :
						if($t['view'] =='1'):
							$limited = isset($t['limited']) ? $t['limited'] :'';
							if(SiteHelpers::filterColumn($limited ))
							{
								echo '<th align="'.$t['align'].'" width="'.$t['width'].'">'.\SiteHelpers::activeLang($t['label'],(isset($t['language'])? $t['language'] : array())).'</th>';				
							} 
						endif;
					endforeach; ?>
							 <th width="30" class="text-right" > Action </th>
						</tr>

					</thead>	
			               
			    </table>
			</div>	 
		</div>			
	</div>	
	</div>
	
</div>

<!-- Modal untuk melihat file data -->
<div class="modal fade" id="viewFileModal" tabindex="-1" role="dialog" aria-labelledby="viewFileModalLabel" aria-hidden="true">
	<div class="modal-dialog modal-xl" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="viewFileModalLabel">Lihat File Data</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<div class="modal-body">
				<div class="alert alert-info">
					<p><strong>Perhatian:</strong> Silakan masukkan keperluan Anda untuk melihat file ini. Informasi ini akan digunakan untuk keperluan audit dan keamanan.</p>
				</div>
				<div class="form-group text-right">
					<input type="text" id="keperluan" class="form-control mb-3" placeholder="Masukkan keperluan Anda untuk melihat file ini">
					<a id="viewFileBtn" href="#" class="btn btn-primary">View</a>
				</div>
				<!-- PDF.js canvas viewer -->
				<div id="fileContent">
					<div class="text-center mt-3">
						<i class="fa fa-file-pdf" style="font-size: 70px; color: red;"></i>
						<div class="mt-2"><span id="fileName"></span></div>
					</div>
				</div>
				<div id="pdfViewer" style="display:none; background:#525659; padding:16px; max-height:70vh; overflow-y:auto; text-align:center;">
					<p id="pdfLoading" style="color:#ccc; font-size:15px; margin:30px 0;">Memuat dokumen...</p>
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Tutup</button>				
			</div>
		</div>
	</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script>
<script type="text/javascript">
	pdfjsLib.GlobalWorkerOptions.workerSrc =
		'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

	// ── Security: block right-click, Ctrl+S, Ctrl+P, Ctrl+U, F12 on the whole page ──
	document.addEventListener('contextmenu', function(e) {
		if (document.getElementById('pdfViewer').style.display !== 'none') e.preventDefault();
	});
	document.addEventListener('keydown', function(e) {
		var blocked = ['s', 'p', 'u'];
		if ((e.ctrlKey || e.metaKey) && blocked.indexOf(e.key.toLowerCase()) !== -1 &&
			document.getElementById('pdfViewer').style.display !== 'none') {
			e.preventDefault(); return false;
		}
	});

	$(document).ready(function() {
		$('.tips').tooltip();
		$('.dataselect').select2();
		var rows_selected = []; 			
	   	var table = $('#datasopikTable').DataTable( {
	        "processing": true,
	       
	        "serverSide": true,
	        // "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
	        "ajax": {
	            "url": "{!! url('datasopik')!!}",
	            "type": "POST"
	             
        	},
        	"columnDefs": [{ 
        		"targets": [0],
                "visible": false,
                orderable: false,
            	className: 'select-checkbox'
        	}],
        	"columns": [<?php echo $column;?>],
        	'order': [[1, 'asc']],
        	<?php if($access['is_excel'] ==1 ) { ?>
        	dom: 'Bfltip',
        	buttons: [
            	'copy', 'csv', 'excel', 'pdf', 'print'
        	]
        	<?php } ?>
        	
	    });

	   	<?php if($setting['view-method'] =='expand'): ?>
		$('#datasopikTable tbody').on('click', 'td.details-control', function () {
	        var tr = $(this).closest('tr');
	        var row = table.row( tr );
	        var id = row.data().rowId;

	        if ( row.child.isShown() ) {
	        	 row.child.hide();
            	tr.removeClass('shown');
	        }
	        else {
	            // Open this row
	            row.child.show();	            
	            row.child( expand_child(id) ).show();
	            tr.addClass('shown');
	            $.get('{{ url("datasopik/")}}/'+id , function(callback){
	            	$('#'+id).html(callback);
	            	$('#'+id).addClass('data');
	            })
		        
	            
	        }
    	});
    	<?php endif; ?>
		$('.dosearch').keyup(function( e ){
			if (e.keyCode === 13) {
				val = $(this).val();
				table.search(val ).draw();
			}
		})  

	    $('#datasopikTable').Sdtable({
	    	tableId : '#datasopik',
	    	table   : table,
	    	action  : '{{ url("datasopik")}}' 
	    });

	   
	});


    function expand_child( id )
    {
    	return '<div id="'+ id+'"><p class="text-center"> Loading Content .. Please wait</p></div>';	
    }

	function viewFile( file )
	{
		// Reset modal state
		$('#keperluan').val('');
		$('#fileContent').show();
		$('#pdfViewer').hide().empty().append('<p id="pdfLoading" style="color:#ccc;font-size:15px;margin:30px 0;">Memuat dokumen...</p>');
		$('#fileName').text(file);
		$('#viewFileModal').modal('show');
	}

	$("#viewFileBtn").click(function() {
		var keperluan = $('#keperluan').val();
		if (keperluan.trim() === '') {
			alert('Silakan masukkan keperluan Anda untuk melihat file ini.');
			return;
		}
		var fileName = $('#fileName').text();
		$.ajax({
			url: '{{ url("datasopik?action_task=viewfile") }}',
			type: 'POST',
			data: { file: fileName, keperluan: keperluan },
			success: function(response) {
				if (response.success) {
					$('#fileContent').hide();
					var viewer = $('#pdfViewer').show();

					pdfjsLib.getDocument({ url: response.fileUrl, withCredentials: true }).promise
						.then(function(pdf) {
							$('#pdfLoading').remove();
							var modalWidth = viewer.width() - 32;
							var scale = Math.max(0.8, Math.min(1.5, modalWidth / 595));
							var pages = [];
							for (var i = 1; i <= pdf.numPages; i++) {
								pages.push((function(num) {
									return pdf.getPage(num).then(function(page) {
										var vp = page.getViewport({ scale: scale });
										var canvas = document.createElement('canvas');
										canvas.width  = vp.width;
										canvas.height = vp.height;
										canvas.style.cssText = 'display:block;margin:0 auto 12px;box-shadow:0 2px 10px rgba(0,0,0,.5);background:#fff;';
										viewer.append(canvas);
										return page.render({ canvasContext: canvas.getContext('2d'), viewport: vp }).promise;
									});
								})(i));
							}
							pages.reduce(function(p,r){ return p.then(function(){ return r; }); }, Promise.resolve());
						})
						.catch(function(err) {
							viewer.html('<p style="color:#f88;padding:20px">Gagal memuat dokumen: ' + err.message + '</p>');
						});
				} else {
					alert('Gagal memuat file: ' + response.message);
				}
			},
			error: function() {
				alert('Terjadi kesalahan saat memuat file.');
			}
		});
	});

	// Clear viewer when modal closed to save memory
	$('#viewFileModal').on('hidden.bs.modal', function () {
		$('#pdfViewer').hide().empty();
		$('#fileContent').show();
	});
</script>


@endsection