<?php 
include 'header.php';
include('xcrud/xcrud.php');
$xcrud = Xcrud::get_instance();
echo Xcrud::load_css(); 
?>

<div class="content-wrapper">

	<section class="content-header"><div class="container-fluid"></div></section>

	<section class="content">
		<div class="container-fluid">
			<div class="col-lg-12">
            <div class="card">
              
              <div class="card-body">
                
                <?php
				$xcrud->table('users');				
				$xcrud->validation_required("username,password,user_type");
				$xcrud->change_type('user_type','select','user','admin,user');
				$xcrud->change_type('calling_type','select','Android','Android,Ipad');
				if ($_SESSION['user_type'] != 'admin') {
					$xcrud->where('id',$_SESSION['user_id']);
					$xcrud->unset_add();
					$xcrud->unset_remove();
					$xcrud->disabled('user_type');
				}
				
				$xcrud->button('#', 'Permission', 'fas fa-lock', 'user-permission', array('data-user_id'=>'{id}'));
				
				$xcrud->unset_title();
				
				echo $xcrud->render();
			  ?>

                
              </div>
            </div>

            
          </div>
		</div>
	</section>

</div>

<div class="modal fade" id="user_permission_modal">
	<div class="modal-dialog modal-lg">
	  <div class="modal-content">
		<div class="modal-header">
		  <h6 class="modal-title" style="font-weight: bold;">User Permission </h6>
		  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
			<span aria-hidden="true">&times;</span>
		  </button>
		</div>

		<div class="modal-body">
			<form id="service_followup_form" class="form-horizontal">
				
				<input type="hidden" id="hidden_user_id" name="hidden_user_id">
				<table class="table table-bordered table-sm align-middle">
					<thead class="table-light">
						<tr>
							<th>Page</th>
							<th class="text-center">View</th>
							<th class="text-center">Edit</th>
							<th class="text-center">Delete</th>
							<th class="text-center other-perms-header">Other Permissions</th>
						</tr>
					</thead>
					<tbody id="permission_table_body">
					</tbody>
				</table>

			</form>
		</div>

		<div class="modal-footer justify-content-between">
		  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
		  <button type="button" class="btn btn-primary" id="save_permissions_btn">Save Permissions</button>
		</div>
	  </div>
	</div>
</div>

<!-- Modal for Other Permissions (Home Page) -->
<div class="modal fade" id="other_permissions_modal">
	<div class="modal-dialog">
	  <div class="modal-content">
		<div class="modal-header">
		  <h6 class="modal-title" style="font-weight: bold;">Home Page - Other Permissions</h6>
		  <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="form-group">
				<label>
					<input type="checkbox" class="other-perm-checkbox" data-perm="today_free_pending">
					Today Free Pending
				</label>
			</div>
			<div class="form-group">
				<label>
					<input type="checkbox" class="other-perm-checkbox" data-perm="today_paid_pending">
					Today Paid Pending
				</label>
			</div>
			<div class="form-group">
				<label>
					<input type="checkbox" class="other-perm-checkbox" data-perm="backdate_pending">
					Backdate Pending
				</label>
			</div>
			<div class="form-group">
				<label>
					<input type="checkbox" class="other-perm-checkbox" data-perm="today_taken">
					Today Taken
				</label>
			</div>
		</div>

		<div class="modal-footer justify-content-between">
		  <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
		  <button type="button" class="btn btn-primary" id="save_other_perms_btn">Save</button>
		</div>
	  </div>
	</div>
</div>

<?php
include 'footer.php';
echo Xcrud::load_js();
?>
<script>
const PAGES = [
    { key: 'home', name: 'Home', editDelete: false, hasOtherPerms: true },
    { key: 'services', name: 'Services', editDelete: true },
    { key: 'service-followup', name: 'Service Follow-up', editDelete: true },
    { key: 'upload-data', name: 'Upload Data', editDelete: false },
    { key: 'upload-job-card', name: 'Upload Job Card', editDelete: false },
    { key: 'remark-report', name: 'Remark Report', editDelete: false },
	{ key: 'bulk-home', name: 'Bulk Service', editDelete: false },
	{ key: 'appointment', name: 'Appointment', editDelete: false },
];

const OTHER_PERMS = {
    today_free_pending: 'Today Free Pending',
    today_paid_pending: 'Today Paid Pending',
    backdate_pending: 'Backdate Pending',
    today_taken: 'Today Taken'
};

var userPermissionModal;
var otherPermsModal;
var currentPageKey = null;
var currentOtherPerms = {};

function openModal() {
    var modalEl = document.getElementById('user_permission_modal');
    if (modalEl) {
        userPermissionModal = new bootstrap.Modal(modalEl);
        userPermissionModal.show();
    }
}

function closeModal() {
    if (userPermissionModal) {
        userPermissionModal.hide();
    }
}

function openOtherPermsModal(pageKey, otherPerms) {
    currentPageKey = pageKey;
    currentOtherPerms = otherPerms || {};

    // Reset all checkboxes
    $('.other-perm-checkbox').prop('checked', false);

    // Check the ones that are enabled
    Object.keys(currentOtherPerms).forEach(function(key) {
        if (currentOtherPerms[key] === 1 || currentOtherPerms[key] === true) {
            $(`[data-perm="${key}"]`).prop('checked', true);
        }
    });

    var modalEl = document.getElementById('other_permissions_modal');
    if (modalEl) {
        otherPermsModal = new bootstrap.Modal(modalEl);
        otherPermsModal.show();
    }
}

function closeOtherPermsModal() {
    if (otherPermsModal) {
        otherPermsModal.hide();
    }
}

$(document).on('click', '.user-permission', function (e) {
    e.preventDefault();
    var userId = $(this).data('user_id');
    $('#hidden_user_id').val(userId);
	
	$.ajax({
		url: 'ajax_call.php',
		type: 'POST',
		data: { action: 'load', user_id: userId },
		dataType: 'json',
		success: function (res) {
			// Convert DB rows to map
			let dbPerms = {};
			res.forEach(function (row) {
				dbPerms[row.page_key] = row;
			});

			let html = '';

			PAGES.forEach(function (page) {
				let perm = dbPerms[page.key] || {
					can_view: 0,
					can_edit: 0,
					can_delete: 0,
					other_permissions: {}
				};

				// Parse other_permissions if it's a JSON string
				let otherPerms = {};
				if (perm.other_permissions) {
					if (typeof perm.other_permissions === 'string') {
						otherPerms = JSON.parse(perm.other_permissions);
					} else {
						otherPerms = perm.other_permissions;
					}
				}

				html += `
				<tr data-page="${page.key}">
					<td>${page.name}</td>

					<td class="text-center">
						<input type="checkbox" class="perm-view"
							${perm.can_view == 1 ? 'checked' : ''}>
					</td>

					<td class="text-center">
						<input type="checkbox" class="perm-edit"
							${page.editDelete ? '' : 'disabled'}
							${page.editDelete && perm.can_edit == 1 ? 'checked' : ''}>
					</td>

					<td class="text-center">
						<input type="checkbox" class="perm-delete"
							${page.editDelete ? '' : 'disabled'}
							${page.editDelete && perm.can_delete == 1 ? 'checked' : ''}>
					</td>`;

				// Add other permissions column only for home page
				if (page.hasOtherPerms) {
					html += `
					<td class="text-center">
						<button type="button" class="btn btn-sm btn-info other-perms-btn" data-page="${page.key}" data-other-perms='${JSON.stringify(otherPerms)}'>
							Configure
						</button>
					</td>`;
				} else {
					html += `<td class="text-center"></td>`;
				}

				html += `</tr>`;
			});

			$('#permission_table_body').html(html);
		},
		error: function (xhr, status, error) {
			console.error('AJAX ERROR');
			console.log(xhr.responseText);
		}
	});

	openModal();
});

// Handle other permissions button click
$(document).on('click', '.other-perms-btn', function (e) {
    e.preventDefault();
    var pageKey = $(this).data('page');
    var otherPerms = $(this).data('other-perms');
    openOtherPermsModal(pageKey, otherPerms);
});

// Save other permissions
$('#save_other_perms_btn').on('click', function () {
    var otherPerms = {};

    $('.other-perm-checkbox').each(function () {
        var permKey = $(this).data('perm');
        otherPerms[permKey] = $(this).is(':checked') ? 1 : 0;
    });

    // Store in the corresponding row
    var row = $(`#permission_table_body tr[data-page="${currentPageKey}"]`);
    row.data('other-perms', otherPerms);

    closeOtherPermsModal();
});

$('#save_permissions_btn').on('click', function () {

    var userId = $('#hidden_user_id').val();

    if (!userId) {
        alert('User ID missing');
        return;
    }

    var permissions = [];

    $('#permission_table_body tr').each(function () {
        var pageKey = $(this).data('page');
        var otherPermsData = $(this).data('other-perms') || {};

        permissions.push({
            page_key: pageKey,
            can_view: $(this).find('.perm-view').is(':checked') ? 1 : 0,
            can_edit: $(this).find('.perm-edit').is(':checked') ? 1 : 0,
            can_delete: $(this).find('.perm-delete').is(':checked') ? 1 : 0,
            other_permissions: otherPermsData
        });
    });

    $.ajax({
        url: 'ajax_call.php',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
			action: 'save',
            user_id: userId,
            permissions: permissions
        }),
        success: function (res) {
            alert('Permissions saved successfully');
			closeModal();
        },
        error: function (xhr) {
            console.error(xhr.responseText);
            alert('Error saving permissions');
        }
    });
});
</script>