<?php
// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

add_action(
	'admin_init',
	function () {
		// Check if user has required capabilities.
		if ( ! current_user_can( 'edit_pages' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'x4email-lite' ) );
		}

		if ( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD'] === 'POST' ) {
			// Toggle email status.
			if (
			isset( $_POST['x4email_toggle_submit'] ) &&
			isset( $_POST['email_id'], $_POST['_wpnonce'], $_POST['email_status'] ) &&
			current_user_can( 'edit_pages' )
			) {
				// Sanitize and validate nonce inputs early.
				$email_id = isset( $_POST['email_id'] ) ? sanitize_text_field( wp_unslash( $_POST['email_id'] ) ) : '';
				$nonce    = isset( $_POST['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ) : '';

				// Verify nonce with sanitized values.
				if ( ! wp_verify_nonce( $nonce, 'x4email_toggle_' . $email_id ) ) {
					wp_die( esc_html__( 'Security check failed.', 'x4email-lite' ) );
				}

				$email_id   = sanitize_text_field( wp_unslash( $_POST['email_id'] ) );
				$new_status = sanitize_text_field( wp_unslash( $_POST['email_status'] ) );

				// Validate status value.
				if ( ! in_array( $new_status, array( 'yes', 'no' ) ) ) {
					wp_die( esc_html__( 'Invalid status value.', 'x4email-lite' ) );
				}

				// Ensure WooCommerce emails are initialized.
				if ( ! class_exists( 'WooCommerce' ) ) {
					wp_die( esc_html__( 'WooCommerce is not active.', 'x4email-lite' ) );
				}

				$mailer = WC()->mailer();
				if ( empty( $mailer->emails ) ) {
					$mailer->init(); // Force loading email classes
				}

				if ( isset( WC()->mailer()->emails[ $email_id ] ) ) {
					$email_obj  = WC()->mailer()->emails[ $email_id ];
					$email_slug = $email_obj->id;

					// Validate email object.
					if ( ! is_object( $email_obj ) || ! isset( $email_obj->settings ) ) {
						wp_die( esc_html__( 'Invalid email object.', 'x4email-lite' ) );
					}

					$email_obj->settings['enabled'] = $new_status;

					// Sanitize settings before saving.
					$sanitized_settings = array_map( 'sanitize_text_field', $email_obj->settings );
					update_option( "woocommerce_{$email_slug}_settings", $sanitized_settings );

					// Force WooCommerce to reload the email settings.
					$email_obj->init_form_fields();
					$email_obj->init_settings();

				}

				wp_safe_redirect( add_query_arg( 'updated', '1', admin_url( 'admin.php?page=x4email-hooks' ) ) );
				exit;
			}
		}
	}
);

/**
 * Display the email hooks management page.
 *
 * Renders the interface for managing WooCommerce email hooks,
 * allowing users to enable/disable different email types.
 *
 * @since 1.0.0
 */
function x4email_hooks_page() {
	wp_enqueue_style( 'x4email-admin-modern', esc_url( plugins_url( 'assets/css/admin-modern.css', dirname( __DIR__ ) ) ), array(), X4EMAIL_LITE_VER );
	if ( ! current_user_can( 'edit_pages' ) ) {
		wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'x4email-lite' ) );
	}

	if ( ! class_exists( 'WooCommerce' ) ) {
		echo '<div class="notice notice-error"><p>' . esc_html__( 'WooCommerce is not active.', 'x4email-lite' ) . '</p></div>';
		return;
	}

	// Always show the header and table, no license checks.
	echo '<div class="x4email-admin" style="min-height:100vh; background: var(--color-bg); padding: 2.5rem 0;">';
	echo '  <div style="max-width: 1200px; margin: 0 auto;">';
	echo '    <div class="x4email-title" style="display:flex;align-items:center;justify-content:space-between;gap:0.75em;flex-direction:row;">';
	echo '        <div style="display:flex;flex-direction:column;align-items:flex-start;">';
	echo '            <h1 style="color:#fff;">EMAIL HOOKS</h1>';
	echo '            <span style="font-size:1rem;color:#fff;opacity:0.9;margin-top:0.25em;letter-spacing:0.01em;">Enable, disable, and customize WooCommerce email notifications.</span>';
	echo '        </div>';
	echo '        <span style="font-size:3.5em;opacity:0.95;line-height:1;display:flex;align-items:center;justify-content:center;"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="white" stroke-width="2" width="48" height="48"><path stroke-linecap="round" stroke-linejoin="round" d="M16.862 3.487a2.25 2.25 0 0 1 3.182 3.182l-13.5 13.5a2.25 2.25 0 0 1-3.182-3.182l13.5-13.5z"/></svg></span>';
	echo '    </div>';

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is only a display notice, no data processed.
	if ( isset( $_GET['updated'] ) ) {
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Email settings updated successfully.', 'x4email-lite' ) . '</p></div>';
	}

	$emails = WC()->mailer()->get_emails();
	?>
	<div class="x4email-card x4email-box-shadow x4email-mb-lg" style="margin-top:2.5rem;">
		<div class="x4email-table-responsive">
		<table>
		<thead>
			<tr>
			<th style="width:32px;"></th>
			<th>Email</th>
			<th class="x4email-desc-col">Description</th>
			<th>Status</th>
			<th>Recipient</th>
			<th>Actions</th>
			</tr>
		</thead>
		<tbody>
		<?php
		foreach ( $emails as $email ) :
			$email_id  = get_class( $email );
			$title     = esc_html( $email->get_title() );
			$desc      = esc_html( $email->get_description() );
			$recipient = $email->recipient ? esc_html( $email->recipient ) : esc_html__( 'Customer', 'x4email-lite' );
			$enabled   = $email->get_option( 'enabled', 'yes' );
			$nonce     = wp_create_nonce( 'x4email_toggle_' . $email_id );
			?>
			<tr>
			<td><span class="x4email-status-dot <?php echo $enabled === 'yes' ? 'active-dot' : 'disabled'; ?>"></span></td>
			<td><strong><?php echo esc_html( $title ); ?></strong></td>
			<td class="x4email-desc-col"><?php echo esc_html( $desc ); ?></td>
				<td>
				<form method="post" style="margin:0;display:flex;align-items:center;gap:0.5em;">
				<?php wp_nonce_field( 'x4email_toggle_' . $email_id, '_wpnonce', true, true ); ?>
				<input type="hidden" name="email_id" value="<?php echo esc_attr( $email_id ); ?>" />
				<select name="email_status" class="x4email-input" style="max-width:110px;">
					<option value="yes" <?php echo selected( $enabled, 'yes', false ); ?>>Enabled</option>
					<option value="no" <?php echo selected( $enabled, 'no', false ); ?>>Disabled</option>
						</select>
				<input type="submit" name="x4email_toggle_submit" class="x4email-btn" value="Save" />
					</form>
				</td>
			<td><?php echo esc_html( $recipient ); ?></td>
				<td>
				<a href="<?php echo esc_url( admin_url( 'admin.php?page=x4email-template-editor&template=' . get_template_name( $email_id ) ) ); ?>" class="x4email-btn-outline">Customize</a>
				</td>
			</tr>
		<?php endforeach; ?>
		</tbody>
		</table>
		</div>
	</div>
	<?php
	echo '  </div></div>';
}

/**
 * Get template name for an email ID.
 *
 * Maps WooCommerce email class names to their corresponding
 * template file names used in the plugin.
 *
 * @since 1.0.0
 *
 * @param string $email_id The WooCommerce email class name.
 * @return string The corresponding template name or the original email ID.
 */
// Helper function to map email IDs to template names.
function get_template_name( $email_id ) {
	$template_map = array(
		'WC_Email_New_Order'                 => 'admin-new-order',
		'WC_Email_Cancelled_Order'           => 'admin-cancelled-order',
		'WC_Email_Failed_Order'              => 'admin-failed-order',
		'WC_Email_Customer_Processing_Order' => 'customer-processing-order',
		'WC_Email_Customer_Completed_Order'  => 'customer-completed-order',
		'WC_Email_Customer_Refunded_Order'   => 'customer-refunded-order',
		'WC_Email_Customer_On_Hold_Order'    => 'customer-on-hold-order',
		'WC_Email_Customer_Note'             => 'customer-note',
		'WC_Email_Customer_New_Account'      => 'customer-new-account',
		'WC_Email_Customer_Invoice'          => 'customer-invoice',
		'WC_Email_Customer_Reset_Password'   => 'customer-reset-password',
	);

	return isset( $template_map[ $email_id ] ) ? $template_map[ $email_id ] : '';
}

