@php
    $user_role = Auth::user()->role;
@endphp

@extends('app.app')

@section('title')
    User Activity
@endsection

@section('customcss')
	<link
		rel="stylesheet"
		href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css"
		integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY="
		crossorigin=""
	/>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="content">
            <div class="card">
                <div class="card-header">
                    <div class="row d-flex align-items-center">
                        <div class="col-3">
                            <p class="card-title text-bold mb-0">User Activity</p>
                        </div>
                        <div class="col-auto text-end ps-0">
                            <!-- <button class="btn btn-sm btn-danger">Download</button> -->
                        </div>
                    </div>
                </div>
                <div class="card-body">
					<!-- filter -->
					<div class="row">
						<div class="col-2">
							<div class="form-group">
								<label class="text-muted">From</label>
								<!-- default today -->
								<!-- <input class="form-control" id="tgl0" value="02-09-2025 00:00"> -->
								<input class="form-control" id="tgl0" value="{{ date('d-m-Y 00:00') }}">
							</div>
						</div>
						<div class="col-2">
							<div class="form-group">
								<label class="text-muted">To</label>
								<!-- <input class="form-control" id="tgl1" value="02-09-2025 23:00"> -->
								<input class="form-control" id="tgl1" value="{{ date('d-m-Y 23:59') }}">
							</div>
						</div>
						<div class="col-2">
							<div class="form-group">
								<label class="text-muted">User</label>
								<select name="user" class="form-control" id="filterUser">
									<option value="">-- All --</option>
									@foreach ($users as $user)
										<option value="{{ $user->id }}">{{ $user->email }}</option>
									@endforeach
								</select>
							</div>
						</div>
						<div class="col-1 d-flex align-items-end">
							<button class="btn btn-primary" id="submitFilter">Submit</button>
						</div>
						<div class="col-5 d-flex align-items-end">
							<button class="btn btn-sm btn-danger ms-auto" id="btnDownloadReport">Download Report</button>
						</div>
					</div>
					</div>
                    <div class="table-responsive p-3">
                        <table id="tLogs" class="table table-hover dataTable w-100">
                            <thead>
                                <tr class="">
                                    <th class="">Time</th>
									<th class="">User</th>
									<th class="">Module</th>
									<th class="">Description</th>
									<th class="">Action</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

@endsection

@section('customjs')
    <script src="{{ asset('assets/js/load-image.all.min.js') }}"></script>
	<!-- DataTables Buttons + JSZip (for Excel export) -->
	<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
	<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js" integrity="sha512-ozq8xQKq6urvuU6jNgkfqAmT7jKN2XumbrX1JiB3TnF7tI48DPI4Gy1GXKD/V3EExgAs1V+pRO7vwtS1LHg0Gw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> -->
	<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
    <script src="https://unpkg.com/leaflet-routing-machine@3.2.12/dist/leaflet-routing-machine.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
	<script src="{{ asset('assets/vendor/printThis.js') }}"></script>

	<script>
        'use strict';

        const Wrapper = {
            activate: function() {
                Wrapper.init();
                Wrapper.event();
                DTable.activate();
			},
			init: ()=>{
				$('.time').each(function () {
					const unix = parseInt($(this).text().trim()) + AppState.TIMEFIX;
					$(this).text(moment.unix(unix).format('DD MMM YYYY HH:mm:ss'));
				});
				$('#tgl0, #tgl1').datetimepicker({
					format:'d-m-Y H:i',
					defaultTime:'00:00',
					closeOnDateSelect: true,
					// mask:true
				});
			},
            event: function() {
				$('#submitFilter').on('click', function() {
					DTable.reload();
				});
				// Trigger export on external button click
				$('#btnDownloadReport').on('click', function() {
					DTable.table.button('.buttons-excel').trigger();
				});
            },
        };

        const DTable = {
			table: null,
    		lastAjax: null, // keep track of the last ajax request
            activate: function() {
                DTable.reload();
            },
            reload: function() {
				// Abort the last request if it's still running
				if (DTable.lastAjax) {
					DTable.lastAjax.abort();
				}
				if (DTable.table) {
					// If table already exists → reload
					DTable.table.ajax.reload();
					return;
				}

				DTable.table = $('#tLogs').DataTable({
					searching: false,   // 🔹 remove search box
					ordering: false,    // 🔹 disable sorting for all columns
					processing: true,
					serverSide: false,
					bLengthChange: true,
					deferRender: true,
					destroy: true,
					ajax: function(data, callback, settings) {
						// Abort previous
						if (DTable.lastAjax) {
							DTable.lastAjax.abort();
						}

						// Fire new request
						DTable.lastAjax = $.ajax({
							url: `{{ route('api_user_logs') }}?
								tgl0=${moment($('#tgl0').val(), "DD-MM-YYYY HH:mm").unix()}
								&tgl1=${moment($('#tgl1').val(), "DD-MM-YYYY HH:mm").unix()}
								&userId=${$('#filterUser').val() || ''}
							`,
							type: 'GET',
							success: function(json) {
								callback(json);
							},
							error: function(xhr, status, error) {
								if (status !== 'abort') {
									console.error("AJAX error:", error);
								}
							},
							complete: function() {
								DTable.lastAjax = null;
							}
						});
					},
                    deferRender: true,
					columns: [
						{
							data: 'crt',
							render: (data, type, row, meta) => {
								// let addr = row
								return `
									${moment.unix(data).format('DD MMM YYYY HH:mm:ss')}<br>
								`;
							} 

						},
						{ data: 'email' },
						{ 
							data: 'log',
							render: (data, type, row, meta) => {
								let log = JSON.parse(data);
								let module = log.module || '-';
								return module;
							}
						},
						{ 
							data: 'log',
							render: (data, type, row, meta) => {
								let log = JSON.parse(data);
								let desc = log.desc || '-';
								return desc;
							}
						},
						{ 
							data: 'log',
							render: (data, type, row, meta) => {
								let log = JSON.parse(data);
								let action = log.action || '-';

								// use badge for action
								// action = `<span class="badge bg-secondary">${action}</span>`;
								let badge = '';
								if (action.toLowerCase() === 'create') {
									badge = `<span class="badge bg-success">${action}</span>`;
								} else if (action.toLowerCase() === 'update') {
									badge = `<span class="badge bg-warning">${action}</span>`;
								} else if (action.toLowerCase() === 'delete') {
									badge = `<span class="badge bg-danger">${action}</span>`;
								} else {
									badge = `<span class="badge bg-secondary">${action}</span>`;
								}
								return badge;
							}
						},
					],
					paging: false,
					buttons: [
						{
							extend: 'excelHtml5',
							title: () => {
								return `
								User Activity Report - 
								${moment($('#tgl0').val(), "DD-MM-YYYY HH:mm").format('DD MMM YYYY HH:mm')} 
								to 
								${moment($('#tgl1').val(), "DD-MM-YYYY HH:mm").format('DD MMM YYYY HH:mm')}`
							},
							className: 'd-none', // hide default button
							// exportOptions: {
							// 	columns: ':visible:not(:last-child)' // 
							// }
						}
					]
				});
            },
        };

        Wrapper.activate();
    </script>
@endsection
