<?php
// PMS Settings

if (! function_exists('pms_save_setting')) {
	function pms_save_setting()
	{
		if (isset($_POST) && ! empty($_POST)) {
			// Check nonce and user permissions
			if (
				isset($_POST['security_nonce'], $_POST['btn_action'], $_POST['setting_key']) &&
				wp_verify_nonce(sanitize_text_field($_POST['security_nonce']), 'security_nonce') &&
				is_user_logged_in() &&
				current_user_can('manage_options')
			) {
				$btn_action = sanitize_text_field($_POST['btn_action']);

				if ($btn_action === 'Save') {
					$pwd = sanitize_text_field($_POST['setting_key']);

					if (! empty($pwd)) {
						update_option('pms_encrypt_key', $pwd);

						// Check if the option was successfully updated
						if (get_option('pms_encrypt_key') === $pwd) {
							$response = ['requ' => $pwd];
						} else {
							$response = ['requ' => 'error'];
						}
					} else {
						$response = ['requ' => 'error'];
					}

					echo wp_json_encode($response);
					wp_die(); // Properly terminate execution
				}
			}
		}

		wp_die('Unauthorized request', '', 403); // Handle unauthorized access
	}

	add_action('wp_ajax_pms_save_setting', 'pms_save_setting');
}

function pms_send_email_help()
{
	if (isset($_POST) && ! empty($_POST)) {
		if (
			isset($_POST['security_nonce'], $_POST['btn_action'], $_POST['form_type'], $_POST['fdbk_email'], $_POST['fdbk_msg']) &&
			wp_verify_nonce(sanitize_text_field($_POST['security_nonce']), 'security_nonce') &&
			is_user_logged_in() &&
			current_user_can('manage_options')
		) {
			$btn_action = sanitize_text_field($_POST['btn_action']);

			if ($btn_action === 'send_email') {
				$subject = str_replace('-', ' ', sanitize_text_field($_POST['form_type']));
				$subject = ucfirst($subject);
				date_default_timezone_set(get_option('timezone_string'));
				$date     = date('d-M-Y H:i');
				$subjects = 'Password Management - ' . $subject . ' - ' . $date;

				$email_from = sanitize_email($_POST['fdbk_email']);
				$headers    = [
					'Content-type: text/html; charset=utf-8',
					'From: ' . $email_from,
				];

				$body = nl2br(esc_html($_POST['fdbk_msg']));

				// Send email
				$sent = wp_mail('coder426@gmail.com', $subjects, $body, $headers);

				if ($sent) {
					echo wp_json_encode('Success');
				} else {
					echo wp_json_encode('Error sending email');
				}

				wp_die(); // Properly terminate execution
			}
		}
	}

	wp_die('Unauthorized request', '', 403); // Handle unauthorized access
}

add_action('wp_ajax_pms_send_email_help', 'pms_send_email_help');
