<?php
if (!defined('ABSPATH')) {
	exit;
}
if (!current_user_can('manage_options')) {
	return;
}
$status_labels = [
	'pending'  => __('Pending', 'unlock-addons-for-elementor'),
	'complete' => __('Complete', 'unlock-addons-for-elementor'),
	'cancel'   => __('Cancelled', 'unlock-addons-for-elementor'),
];
$es = isset($email_settings) ? $email_settings : [];
$from_name  = isset($es['from_name']) ? $es['from_name'] : '';
$from_email = isset($es['from_email']) ? $es['from_email'] : '';
$smtp_host  = isset($es['smtp_host']) ? $es['smtp_host'] : '';
$smtp_port  = isset($es['smtp_port']) ? $es['smtp_port'] : '587';
$smtp_enc   = isset($es['smtp_encryption']) ? $es['smtp_encryption'] : 'tls';
$smtp_no_ssl = !empty($es['smtp_disable_ssl_verify']) && $es['smtp_disable_ssl_verify'] === 'yes';
?>
<div class="wrap unlockafe-reservation-list-wrap">
	<h1><?php esc_html_e('Reservation List & Details', 'unlock-addons-for-elementor'); ?></h1>

	<div class="unlockafe-email-sender-box" style="max-width:600px; margin-bottom:24px; padding:16px; background:#fff; border:1px solid #c3c4c7; box-shadow:0 1px 1px rgba(0,0,0,.04);">
		<h2 style="margin-top:0;"><?php esc_html_e('Email Sender Settings (Reservation emails to admin & customer)', 'unlock-addons-for-elementor'); ?></h2>
		<?php if (!empty($email_saved_message)) : ?>
			<div class="notice notice-success"><p><?php echo esc_html($email_saved_message); ?></p></div>
		<?php endif; ?>
		<?php
		$show_gmail_warning = !empty($is_gmail_like) && !$has_smtp_password;
		if ($show_gmail_warning) : ?>
			<div class="notice notice-warning" style="border-left-color: #dba617;">
				<p><strong><?php esc_html_e('Why are emails not sending?', 'unlock-addons-for-elementor'); ?></strong></p>
				<p><?php esc_html_e('Gmail (and smtp.gmail.com) requires an App Password to send emails from this site. Without it, emails will not be delivered to admin or customer.', 'unlock-addons-for-elementor'); ?></p>
				<p><?php esc_html_e('What to do:', 'unlock-addons-for-elementor'); ?></p>
				<ol style="list-style:decimal; margin-left:20px;">
					<li><?php esc_html_e('Go to Google Account → Security → 2-Step Verification (enable if needed).', 'unlock-addons-for-elementor'); ?></li>
					<li><?php esc_html_e('Under "App passwords", create a new app password for "Mail".', 'unlock-addons-for-elementor'); ?></li>
					<li><?php esc_html_e('Copy the 16-character password and paste it in "App Password / SMTP Password" above.', 'unlock-addons-for-elementor'); ?></li>
					<li><?php esc_html_e('Click "Save Email Settings", then use "Send test email" to verify.', 'unlock-addons-for-elementor'); ?></li>
				</ol>
			</div>
		<?php endif; ?>
		<p><?php esc_html_e('Configure the From address and optional SMTP (e.g. Gmail App Password) so reservation confirmation emails are sent to both admin and customer.', 'unlock-addons-for-elementor'); ?></p>
		<form method="post" action="">
			<?php wp_nonce_field('unlockafe_reservation_email_settings', 'unlockafe_reservation_email_nonce'); ?>
			<input type="hidden" name="unlockafe_save_reservation_email" value="1">
			<table class="form-table">
				<tr>
					<th scope="row"><label for="reservation_from_name"><?php esc_html_e('From Name', 'unlock-addons-for-elementor'); ?></label></th>
					<td><input type="text" id="reservation_from_name" name="reservation_from_name" value="<?php echo esc_attr($from_name); ?>" class="regular-text" placeholder="<?php echo esc_attr(get_bloginfo('name')); ?>"></td>
				</tr>
				<tr>
					<th scope="row"><label for="reservation_from_email"><?php esc_html_e('From Email Address', 'unlock-addons-for-elementor'); ?></label></th>
					<td><input type="email" id="reservation_from_email" name="reservation_from_email" value="<?php echo esc_attr($from_email); ?>" class="regular-text" placeholder="<?php echo esc_attr(get_option('admin_email')); ?>"></td>
				</tr>
				<tr>
					<th scope="row"><label for="reservation_smtp_password"><?php esc_html_e('App Password / SMTP Password', 'unlock-addons-for-elementor'); ?></label></th>
					<td>
						<input type="password" id="reservation_smtp_password" name="reservation_smtp_password" value="" class="regular-text" autocomplete="new-password" placeholder="<?php esc_attr_e('Leave blank to keep current', 'unlock-addons-for-elementor'); ?>">
						<p class="description"><?php esc_html_e('Required for Gmail/Yahoo/Outlook. Use your email App Password to send via SMTP. Leave blank to use server default or keep existing password.', 'unlock-addons-for-elementor'); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="reservation_smtp_host"><?php esc_html_e('SMTP Host', 'unlock-addons-for-elementor'); ?></label></th>
					<td>
						<input type="text" id="reservation_smtp_host" name="reservation_smtp_host" value="<?php echo esc_attr($smtp_host); ?>" class="regular-text" placeholder="smtp.gmail.com">
						<p class="description"><?php esc_html_e('Optional. Default: smtp.gmail.com when using Gmail.', 'unlock-addons-for-elementor'); ?></p>
					</td>
				</tr>
				<tr>
					<th scope="row"><label for="reservation_smtp_port"><?php esc_html_e('SMTP Port', 'unlock-addons-for-elementor'); ?></label></th>
					<td><input type="text" id="reservation_smtp_port" name="reservation_smtp_port" value="<?php echo esc_attr($smtp_port); ?>" class="small-text" placeholder="587"></td>
				</tr>
				<tr>
					<th scope="row"><label for="reservation_smtp_encryption"><?php esc_html_e('Encryption', 'unlock-addons-for-elementor'); ?></label></th>
					<td>
						<select id="reservation_smtp_encryption" name="reservation_smtp_encryption">
							<option value="tls" <?php selected($smtp_enc, 'tls'); ?>><?php esc_html_e('TLS', 'unlock-addons-for-elementor'); ?></option>
							<option value="ssl" <?php selected($smtp_enc, 'ssl'); ?>><?php esc_html_e('SSL', 'unlock-addons-for-elementor'); ?></option>
						</select>
					</td>
				</tr>
				<tr>
					<th scope="row"><?php esc_html_e('SSL verification', 'unlock-addons-for-elementor'); ?></th>
					<td>
						<label>
							<input type="checkbox" name="reservation_smtp_disable_ssl_verify" value="1" <?php checked($smtp_no_ssl); ?>>
							<?php esc_html_e('Disable SSL verification (for localhost only)', 'unlock-addons-for-elementor'); ?>
						</label>
						<p class="description"><?php esc_html_e('Enable this if you see "certificate verify failed" or "SSL operation failed". Use only on local/dev sites, not on live server.', 'unlock-addons-for-elementor'); ?></p>
					</td>
				</tr>
			</table>
			<p class="submit">
				<input type="submit" name="submit" id="submit" class="button button-primary" value="<?php esc_attr_e('Save Email Settings', 'unlock-addons-for-elementor'); ?>">
				<button type="button" id="unlockafe-send-test-email" class="button" style="margin-left:8px;"><?php esc_html_e('Send test email', 'unlock-addons-for-elementor'); ?></button>
				<span id="unlockafe-test-email-msg" style="margin-left:10px;"></span>
			</p>
		</form>
	</div>
	<script>
	jQuery(function($) {
		$('#unlockafe-send-test-email').on('click', function() {
			var $btn = $(this), $msg = $('#unlockafe-test-email-msg');
			$msg.text('').removeClass('success error');
			$btn.prop('disabled', true);
			$.post(ajaxurl, {
				action: 'unlockafe_send_reservation_test_email',
				nonce: '<?php echo esc_js(wp_create_nonce('unlockafe_reservation_test_email')); ?>',
				to: $('#reservation_from_email').val() || '<?php echo esc_js(get_option('admin_email')); ?>'
			}).done(function(res) {
				if (res.success) {
					$msg.addClass('success').css('color','#00a32a').text(res.data.message || 'Sent.');
				} else {
					$msg.addClass('error').css('color','#d63638').text(res.data && res.data.message ? res.data.message : 'Failed.');
				}
			}).fail(function() {
				$msg.addClass('error').css('color','#d63638').text('Request failed.');
			}).always(function() {
				$btn.prop('disabled', false);
			});
		});
	});
	</script>

	<p><?php esc_html_e('Table reservations from the Table Reservation widget. Change status below; customer will receive an email when status is updated. Cancellation requires a reason.', 'unlock-addons-for-elementor'); ?></p>

	<?php if (empty($reservations)) : ?>
		<p><?php esc_html_e('No reservations yet.', 'unlock-addons-for-elementor'); ?></p>
	<?php else : ?>
		<table class="wp-list-table widefat fixed striped unlockafe-reservation-table">
			<thead>
				<tr>
					<th class="column-date"><?php esc_html_e('Date', 'unlock-addons-for-elementor'); ?></th>
					<th class="column-time"><?php esc_html_e('Time', 'unlock-addons-for-elementor'); ?></th>
					<th class="column-name"><?php esc_html_e('Name', 'unlock-addons-for-elementor'); ?></th>
					<th class="column-email"><?php esc_html_e('Email', 'unlock-addons-for-elementor'); ?></th>
					<th class="column-seats"><?php esc_html_e('Total seats', 'unlock-addons-for-elementor'); ?></th>
					<th class="column-status"><?php esc_html_e('Status', 'unlock-addons-for-elementor'); ?></th>
					<th class="column-actions"><?php esc_html_e('Actions', 'unlock-addons-for-elementor'); ?></th>
				</tr>
			</thead>
			<tbody>
				<?php foreach ($reservations as $r) :
					$id = isset($r['id']) ? $r['id'] : '';
					$status = isset($r['status']) ? $r['status'] : 'pending';
					if (!isset($status_labels[$status])) {
						$status = 'pending';
					}
					$party = isset($r['party']) ? (int) $r['party'] : 0;
				?>
					<tr data-id="<?php echo esc_attr($id); ?>">
						<td><?php echo esc_html(isset($r['date']) ? $r['date'] : '—'); ?></td>
						<td><?php echo esc_html(isset($r['time']) ? $r['time'] : '—'); ?></td>
						<td><?php echo esc_html(isset($r['name']) ? $r['name'] : '—'); ?></td>
						<td><?php echo esc_html(isset($r['email']) ? $r['email'] : '—'); ?></td>
						<td><?php echo esc_html((string) $party); ?></td>
						<td class="unlockafe-status-cell">
							<span class="unlockafe-status-badge status-<?php echo esc_attr($status); ?>"><?php echo esc_html($status_labels[$status]); ?></span>
						</td>
						<td class="unlockafe-actions-cell">
							<button type="button" class="button button-small unlockafe-toggle-details"><?php esc_html_e('Details', 'unlock-addons-for-elementor'); ?></button>
							<div class="unlockafe-change-status-wrap" style="margin-top:6px;">
								<select class="unlockafe-status-select" data-id="<?php echo esc_attr($id); ?>">
									<option value="pending" <?php selected($status, 'pending'); ?>><?php echo esc_html($status_labels['pending']); ?></option>
									<option value="complete" <?php selected($status, 'complete'); ?>><?php echo esc_html($status_labels['complete']); ?></option>
									<option value="cancel" <?php selected($status, 'cancel'); ?>><?php echo esc_html($status_labels['cancel']); ?></option>
								</select>
								<span class="unlockafe-reason-wrap" style="display:<?php echo $status === 'cancel' ? 'inline' : 'none'; ?>;">
									<input type="text" class="unlockafe-cancel-reason" placeholder="<?php esc_attr_e('Reason (required for cancel)', 'unlock-addons-for-elementor'); ?>" style="width:180px; margin-left:4px;">
								</span>
								<button type="button" class="button button-small button-primary unlockafe-update-status" data-id="<?php echo esc_attr($id); ?>"><?php esc_html_e('Update', 'unlock-addons-for-elementor'); ?></button>
							</div>
							<span class="unlockafe-status-msg" style="display:none; margin-left:6px;"></span>
						</td>
					</tr>
					<tr class="unlockafe-details-row" data-for="<?php echo esc_attr($id); ?>" style="display:none;">
						<td colspan="7" style="background:#f9f9f9; padding:12px 16px;">
							<strong><?php esc_html_e('Details', 'unlock-addons-for-elementor'); ?></strong>
							<ul style="margin:8px 0 0; padding-left:20px;">
								<li><?php esc_html_e('Phone:', 'unlock-addons-for-elementor'); ?> <?php echo esc_html(isset($r['phone']) ? $r['phone'] : '—'); ?></li>
								<li><?php esc_html_e('Location:', 'unlock-addons-for-elementor'); ?> <?php echo esc_html(isset($r['location']) && $r['location'] !== '' ? $r['location'] : '—'); ?></li>
								<?php if (!empty($r['min_guest'])) : ?><li><?php esc_html_e('Min guest:', 'unlock-addons-for-elementor'); ?> <?php echo esc_html($r['min_guest']); ?></li><?php endif; ?>
								<?php if (!empty($r['max_guest'])) : ?><li><?php esc_html_e('Max guest:', 'unlock-addons-for-elementor'); ?> <?php echo esc_html($r['max_guest']); ?></li><?php endif; ?>
								<li><?php esc_html_e('Special requests:', 'unlock-addons-for-elementor'); ?> <?php echo esc_html(isset($r['notes']) && $r['notes'] !== '' ? $r['notes'] : '—'); ?></li>
								<?php if (!empty($r['custom_data']) && is_array($r['custom_data'])) : ?>
									<li><?php esc_html_e('Custom:', 'unlock-addons-for-elementor'); ?>
										<?php
										$parts = [];
										foreach ($r['custom_data'] as $row) {
											$parts[] = (isset($row['type']) ? $row['type'] : '') . ' / ' . (isset($row['qty']) ? (string) $row['qty'] : '');
										}
										echo esc_html(implode('; ', $parts));
										?>
									</li>
								<?php endif; ?>
								<li><?php esc_html_e('Created:', 'unlock-addons-for-elementor'); ?> <?php echo esc_html(isset($r['created']) ? $r['created'] : '—'); ?></li>
								<?php if (!empty($r['status_reason'])) : ?><li><?php esc_html_e('Cancel reason:', 'unlock-addons-for-elementor'); ?> <?php echo esc_html($r['status_reason']); ?></li><?php endif; ?>
							</ul>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
	<?php endif; ?>
</div>

<style>
.unlockafe-reservation-table { margin-top:12px; }
.unlockafe-status-badge { padding:4px 10px; border-radius:4px; font-size:12px; }
.unlockafe-status-badge.status-pending { background:#f0f0f1; color:#2c3338; }
.unlockafe-status-badge.status-complete { background:#d4edda; color:#155724; }
.unlockafe-status-badge.status-cancel { background:#f8d7da; color:#721c24; }
.unlockafe-actions-cell .button { margin-right:4px; }
.unlockafe-status-msg.success { color:#00a32a; }
.unlockafe-status-msg.error { color:#d63638; }
</style>

<script>
(function() {
	var nonce = '<?php echo esc_js(wp_create_nonce('unlockafe_reservation_status')); ?>';
	var ajaxUrl = '<?php echo esc_js(admin_url('admin-ajax.php')); ?>';

	jQuery(function($) {
		// Toggle details row
		$('.unlockafe-toggle-details').on('click', function() {
			var id = $(this).closest('tr').data('id');
			$('.unlockafe-details-row[data-for="' + id + '"]').toggle();
		});

		// Show/hide reason when cancel selected
		$('.unlockafe-status-select').on('change', function() {
			var $row = $(this).closest('tr');
			var isCancel = $(this).val() === 'cancel';
			$row.find('.unlockafe-reason-wrap').toggle(isCancel);
		});

		// Update status
		$('.unlockafe-update-status').on('click', function() {
			var $btn = $(this);
			var id = $btn.data('id');
			var $row = $btn.closest('tr');
			var status = $row.find('.unlockafe-status-select').val();
			var reason = $row.find('.unlockafe-cancel-reason').val() || '';
			var $msg = $row.find('.unlockafe-status-msg');

			if (status === 'cancel' && reason.trim() === '') {
				$msg.removeClass('success').addClass('error').text('<?php echo esc_js(__('Please provide a reason for cancellation.', 'unlock-addons-for-elementor')); ?>').show();
				return;
			}

			$msg.hide();
			$btn.prop('disabled', true);

			$.post(ajaxUrl, {
				action: 'unlockafe_update_reservation_status',
				nonce: nonce,
				id: id,
				status: status,
				reason: reason
			}).done(function(res) {
				if (res.success) {
					$msg.removeClass('error').addClass('success').text(res.data.message || 'Updated').show();
					var label = res.data.status_label || res.data.status || status;
					$row.find('.unlockafe-status-badge').removeClass('status-pending status-complete status-cancel').addClass('status-' + status).text(label);
					$row.find('.unlockafe-cancel-reason').val('');
				} else {
					$msg.removeClass('success').addClass('error').text(res.data && res.data.message ? res.data.message : 'Error').show();
				}
			}).fail(function() {
				$msg.removeClass('success').addClass('error').text('Request failed').show();
			}).always(function() {
				$btn.prop('disabled', false);
			});
		});
	});
})();
</script>
