<?php

declare(strict_types=1);

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$is_modal = ! empty( $_GET['rc_modal'] );
$modal_arg = $is_modal ? array( 'rc_modal' => '1' ) : array();

$search   = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
?>
<div class="wrap">
	<h1 class="wp-heading-inline"><?php esc_html_e( 'Restaurant Costing - Users', 'restaurant-costing' ); ?></h1>
	<div class="rc-version">v<?php echo esc_html( RC_VERSION ); ?></div>
	<button type="button" class="page-title-action" id="rc-add-user-btn"><?php esc_html_e( 'Add User', 'restaurant-costing' ); ?></button>
	<hr class="wp-header-end">

	<div class="rc-filter-bar">
		<form method="get" class="rc-filter-form">
			<input type="hidden" name="page" value="restaurant-costing-users" />
			<input type="search" name="s" placeholder="<?php esc_attr_e( 'Search users...', 'restaurant-costing' ); ?>" value="<?php echo esc_attr( $search ); ?>" class="rc-w-240" />
			<input type="submit" class="button button-primary" value="<?php esc_attr_e( 'Filter', 'restaurant-costing' ); ?>" />
			<a href="<?php echo esc_url( admin_url( 'admin.php?page=restaurant-costing-users' ) ); ?>" class="button"><?php esc_html_e( 'Reset', 'restaurant-costing' ); ?></a>
		</form>
	</div>

	<table class="wp-list-table widefat fixed striped rc-users-table rc-table-rounded">
		<thead>
			<tr>
				<th><?php esc_html_e( 'Username', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Name', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Email', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Phone', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Role', 'restaurant-costing' ); ?></th>
				<th><?php esc_html_e( 'Actions', 'restaurant-costing' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php if ( empty( $items ) ) : ?>
				<tr><td colspan="6"><?php esc_html_e( 'No users found.', 'restaurant-costing' ); ?></td></tr>
			<?php else : ?>
				<?php foreach ( $items as $item ) : ?>
					<tr>
						<td><strong><?php echo esc_html( $item->user_login ); ?></strong></td>
						<td><?php echo esc_html( trim( $item->first_name . ' ' . $item->last_name ) ); ?></td>
						<td><?php echo esc_html( $item->user_email ); ?></td>
						<td><?php echo esc_html( $item->phone ?? '' ); ?></td>
						<td><?php echo esc_html( (array) $item->roles ? translate_user_role( ucwords( str_replace( '_', ' ', reset( $item->roles ) ) ) ) : '' ); ?></td>
						<td class="rc-actions-cell">
							<a href="#" class="button rc-action-btn rc-edit-user" data-id="<?php echo (int) $item->ID; ?>"><?php esc_html_e( 'Edit', 'restaurant-costing' ); ?></a>
							<a href="<?php echo esc_url( wp_nonce_url( add_query_arg( array_merge( array( 'action' => 'rc_delete_user', 'id' => (int) $item->ID ), $modal_arg ), admin_url( 'admin-post.php' ) ), 'rc_delete_user_' . (int) $item->ID ) ); ?>" class="button rc-action-btn rc-action-btn-danger rc-confirm-user-delete"><?php esc_html_e( 'Delete', 'restaurant-costing' ); ?></a>
						</td>
					</tr>
				<?php endforeach; ?>
			<?php endif; ?>
		</tbody>
	</table>

	<div id="rc-user-modal" class="rc-modal" role="dialog" aria-modal="true" hidden>
		<div class="rc-modal-backdrop" tabindex="-1"></div>
		<div class="rc-modal-dialog rc-modal-dialog-md">
			<header class="rc-modal-header">
				<h2 id="rc-user-modal-title"><?php esc_html_e( 'User', 'restaurant-costing' ); ?></h2>
				<button type="button" class="rc-modal-close" aria-label="Close">&times;</button>
			</header>
			<form id="rc-user-modal-form">
				<input type="hidden" id="rc-user-id" name="id" value="" />
				<div class="rc-modal-body">
					<p class="rc-modal-error" id="rc-user-modal-error" hidden></p>

					<table class="form-table">
						<tr>
							<th scope="row"><label for="rc-user-username"><?php esc_html_e( 'Username', 'restaurant-costing' ); ?> *</label></th>
							<td><input type="text" id="rc-user-username" name="username" class="regular-text" required /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-user-email"><?php esc_html_e( 'Email', 'restaurant-costing' ); ?> *</label></th>
							<td><input type="email" id="rc-user-email" name="email" class="regular-text" required /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-user-first-name"><?php esc_html_e( 'First Name', 'restaurant-costing' ); ?></label></th>
							<td><input type="text" id="rc-user-first-name" name="first_name" class="regular-text" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-user-last-name"><?php esc_html_e( 'Last Name', 'restaurant-costing' ); ?></label></th>
							<td><input type="text" id="rc-user-last-name" name="last_name" class="regular-text" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-user-phone"><?php esc_html_e( 'Phone', 'restaurant-costing' ); ?></label></th>
							<td><input type="text" id="rc-user-phone" name="phone" class="regular-text" /></td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-user-password"><?php esc_html_e( 'Password', 'restaurant-costing' ); ?></label></th>
							<td>
								<div class="rc-pw-wrap">
									<input type="password" id="rc-user-password" name="password" class="regular-text" autocomplete="new-password" />
									<button type="button" class="rc-pw-toggle" id="rc-pw-toggle" aria-label="<?php esc_attr_e( 'Show password', 'restaurant-costing' ); ?>">
										<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
									</button>
								</div>
								<p class="description" id="rc-user-password-desc"><?php esc_html_e( 'Leave blank to keep current password on edit.', 'restaurant-costing' ); ?></p>
							</td>
						</tr>
						<tr>
							<th scope="row"><label for="rc-user-role"><?php esc_html_e( 'Assign Role', 'restaurant-costing' ); ?> *</label></th>
							<td>
								<select id="rc-user-role" name="role" required>
									<option value=""><?php esc_html_e( 'Select role...', 'restaurant-costing' ); ?></option>
									<option value="<?php echo esc_attr( RC_Roles::ROLE_USER ); ?>"><?php esc_html_e( 'RC User', 'restaurant-costing' ); ?></option>
									<option value="<?php echo esc_attr( RC_Roles::ROLE_MANAGER ); ?>"><?php esc_html_e( 'RC Manager', 'restaurant-costing' ); ?></option>
								</select>
							</td>
						</tr>
					</table>
				</div>
				<footer class="rc-modal-footer">
					<button type="submit" class="button button-primary"><?php esc_html_e( 'Save', 'restaurant-costing' ); ?></button>
					<button type="button" class="button rc-modal-cancel" style="margin-right:auto;"><?php esc_html_e( 'Cancel', 'restaurant-costing' ); ?></button>
					<button type="button" class="button" id="rc-reset-pw-btn" disabled><?php esc_html_e( 'Reset Password', 'restaurant-costing' ); ?></button>
				</footer>
			</form>
		</div>
	</div>

</div>

<script>
(function ($) {
	'use strict';

	var $modal = $('#rc-user-modal');
	var $form  = $('#rc-user-modal-form');
	var ajaxNonce = '<?php echo wp_create_nonce( 'rc_recipe_ajax' ); ?>';

	$('#rc-add-user-btn').on('click', function () {
		$form[0].reset();
		$('#rc-user-id').val('');
		$('#rc-user-username').prop('readonly', false);
		$('#rc-user-password').prop('required', true);
		$('#rc-user-password-desc').hide();
		$('#rc-user-modal-title').text('<?php echo esc_js( __( 'Add User', 'restaurant-costing' ) ); ?>');
		$('#rc-user-modal-error').prop('hidden', true).text('');
		$('#rc-reset-pw-btn').prop('disabled', true);
		$modal.prop('hidden', false);
		$('#rc-user-username').trigger('focus');
	});

	$('#rc-user-email').on('input', function () {
		var editing = !!$('#rc-user-id').val();
		$('#rc-reset-pw-btn').prop('disabled', !editing || !$(this).val());
	});

	$(document).on('click', '.rc-edit-user', function (e) {
		e.preventDefault();
		var id = $(this).data('id');
		if (!id) return;

		$.getJSON(ajaxurl, {
			action: 'rc_get_user',
			nonce: ajaxNonce,
			id: id
		}).done(function (resp) {
			if (!resp || !resp.success) {
				alert('Could not fetch user data.');
				return;
			}
			var item = resp.data;
			$('#rc-user-id').val(item.ID);
			$('#rc-user-username').val(item.user_login).prop('readonly', true);
			$('#rc-user-email').val(item.user_email);
			$('#rc-user-first-name').val(item.first_name || '');
			$('#rc-user-last-name').val(item.last_name || '');
			$('#rc-user-phone').val(item.phone || '');
			$('#rc-user-password').val('').prop('required', false);
			$('#rc-user-password-desc').show();
			$('#rc-user-role').val(item.role || '');
			$('#rc-user-modal-title').text('<?php echo esc_js( __( 'Edit User', 'restaurant-costing' ) ); ?>');
			$('#rc-user-modal-error').prop('hidden', true).text('');
			$('#rc-reset-pw-btn').prop('disabled', !item.user_email);
			$modal.prop('hidden', false);
		}).fail(function () {
			alert('Request failed.');
		});
	});

	$modal.on('click', '.rc-modal-close, .rc-modal-cancel, .rc-modal-backdrop', function () {
		$modal.prop('hidden', true);
	});

	$(document).on('keydown', function (e) {
		if (e.key === 'Escape' && !$modal.prop('hidden')) {
			$modal.prop('hidden', true);
		}
	});

	$form.on('submit', function (e) {
		e.preventDefault();
		var $error = $('#rc-user-modal-error');
		$error.prop('hidden', true).text('');

		var $btn = $form.find('button[type="submit"]');
		$btn.prop('disabled', true);

		$.post(ajaxurl, {
			action: 'rc_save_user',
			nonce: ajaxNonce,
			id: $('#rc-user-id').val(),
			username: $('#rc-user-username').val(),
			email: $('#rc-user-email').val(),
			first_name: $('#rc-user-first-name').val(),
			last_name: $('#rc-user-last-name').val(),
			phone: $('#rc-user-phone').val(),
			password: $('#rc-user-password').val(),
			role: $('#rc-user-role').val()
		}).done(function (resp) {
			if (!resp || !resp.success) {
				$error.text((resp && resp.data && resp.data.message) || 'Could not save.').prop('hidden', false);
				return;
			}
			window.location.reload();
		}).fail(function () {
			$error.text('Request failed.').prop('hidden', false);
		}).always(function () {
			$btn.prop('disabled', false);
		});
	});

	$('#rc-reset-pw-btn').on('click', function () {
		var id = $('#rc-user-id').val();
		if (!id) return;
		var email = $('#rc-user-email').val();
		if (!email) {
			$('#rc-user-modal-error').text('<?php echo esc_js( __( 'Email is required for this function.', 'restaurant-costing' ) ); ?>').prop('hidden', false);
			return;
		}
		var $btn = $(this);
		rcConfirm('<?php echo esc_js( __( 'Send password reset email to this user?', 'restaurant-costing' ) ); ?>', function (ok) {
			if (!ok) return;
			$btn.prop('disabled', true);
			$.post(ajaxurl, {
				action: 'rc_reset_password',
				nonce: ajaxNonce,
				id: id
			}).done(function (resp) {
				if (resp && resp.success) {
					$('#rc-user-modal-error').text(resp.data.message).css('color', '#46b450').prop('hidden', false);
				} else {
					$('#rc-user-modal-error').text((resp && resp.data && resp.data.message) || 'Could not reset.').css('color', '').prop('hidden', false);
				}
			}).fail(function () {
				$('#rc-user-modal-error').text('Request failed.').css('color', '').prop('hidden', false);
			}).always(function () {
				$btn.prop('disabled', false);
			});
		});
	});
})(jQuery);

document.addEventListener('DOMContentLoaded', function () {
	var toggle = document.getElementById('rc-pw-toggle');
	var pw = document.getElementById('rc-user-password');
	if (toggle && pw) {
		toggle.addEventListener('click', function () {
			var isPassword = pw.type === 'password';
			pw.type = isPassword ? 'text' : 'password';
			toggle.setAttribute('aria-label', isPassword ? '<?php echo esc_js( __( 'Hide password', 'restaurant-costing' ) ); ?>' : '<?php echo esc_js( __( 'Show password', 'restaurant-costing' ) ); ?>');
			toggle.innerHTML = isPassword
				? '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>'
				: '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
		});
	}
});
</script>

<style>
.rc-users-table.striped tbody tr:nth-child(odd) { background-color: #2a384b; }
.rc-users-table.striped tbody tr:nth-child(even) { background-color: #243142; }
.rc-users-table .rc-actions-cell { white-space: nowrap; }

#rc-user-modal[hidden] { display: none !important; }
#rc-user-modal:not([hidden]) { display: block; }
#rc-user-modal .rc-modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,0.55); z-index: 100099; }
#rc-user-modal .rc-modal-dialog { position: fixed; z-index: 100100; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #151e2b; border: 2px solid #273548; border-radius: 10px; box-shadow: 0 8px 32px rgba(0,0,0,0.2); max-height: 85vh; overflow-y: auto; }
#rc-user-modal .rc-modal-header { display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; border-bottom: 1px solid #273548; }
#rc-user-modal .rc-modal-header h2 { margin: 0; font-size: 16px; color: #fff; }
#rc-user-modal .rc-modal-close { background: none; border: none; font-size: 24px; line-height: 1; cursor: pointer; padding: 0 4px; color: #fff; }
#rc-user-modal .rc-modal-body { padding: 12px 16px 0; }
#rc-user-modal .rc-modal-body label { color: #ddd; }
#rc-user-modal .rc-modal-footer { padding: 12px 16px 16px; display: flex; align-items: center; gap: 8px; }
#rc-user-modal .rc-modal-footer .button { flex-shrink: 0; }

.rc-pw-wrap { position: relative; display: inline-block; }
.rc-pw-wrap .regular-text { padding-right: 36px; }
.rc-pw-toggle { position: absolute; right: 2px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; padding: 6px; color: #888; display: flex; align-items: center; }
.rc-pw-toggle:hover { color: #ccc; }
.rc-pw-toggle svg { display: block; }

body.rc-theme-light #rc-user-modal .rc-modal-dialog { background: #fff; border-color: #c3c4c7; }
body.rc-theme-light #rc-user-modal .rc-modal-header h2 { color: #1d2327; }
body.rc-theme-light #rc-user-modal .rc-modal-header { border-bottom-color: #dcdcde; }
body.rc-theme-light #rc-user-modal .rc-modal-close { color: #1d2327; }
body.rc-theme-light #rc-user-modal .rc-modal-body label { color: #1d2327; }
body.rc-theme-light .rc-pw-toggle { color: #666; }
body.rc-theme-light .rc-pw-toggle:hover { color: #333; }
<?php if ( $is_modal ) : ?>
#adminmenumain, #wpadminbar, #wpfooter { display: none !important; }
html.wp-toolbar { padding-top: 0 !important; }
#wpcontent, #wpbody-content { margin-left: 0 !important; padding-left: 0 !important; }
#wpbody-content { padding-bottom: 0 !important; }
body { background: #29364c; }
.wrap { margin: 16px; }
.rc-version { display: none; }
<?php endif; ?>
</style>

<script>
document.addEventListener('DOMContentLoaded', function () {
	if (typeof rcConfirm === 'undefined') return;
	document.querySelectorAll('.rc-confirm-user-delete').forEach(function (el) {
		el.addEventListener('click', function (e) {
			e.preventDefault();
			var href = this.getAttribute('href');
			rcConfirm('<?php echo esc_js( __( 'Delete this user?', 'restaurant-costing' ) ); ?>', function (ok) {
				if (ok) window.location.href = href;
			});
		});
	});
});
</script>
