<?php
/*
**Get password data in datatable
*/

if (!defined('ABSPATH')) {
	exit; // Exit if accessed directly
}

if (! function_exists('get_new_pass')) {
	function get_new_pass()
	{
		if (!current_user_can('manage_custom_data')) {
			wp_die(__('You do not have permission to manage this data.', 'passwords-manager'));
		}

		global $wpdb, $posts;
		$prefix = $wpdb->prefix;

		// Sanitize content to avoid any potential XSS vulnerability
		$content = sanitize_text_field(get_the_content());

		// Check if the request contains any data and sanitize
		if (isset($_POST) && !empty($_POST)) {
			// Use WordPress nonces to verify request
			if (isset($_POST['security_nonce']) && wp_verify_nonce(sanitize_text_field($_POST['security_nonce']), 'security_nonce')) {

				// Sanitize and validate inputs
				$category_name = isset($_POST['cat_name']) ? sanitize_text_field($_POST['cat_name']) : '';
				$startLimit = isset($_POST['start']) ? filter_var($_POST['start'], FILTER_VALIDATE_INT) : 0;
				$lengthLimit = isset($_POST['length']) ? filter_var($_POST['length'], FILTER_VALIDATE_INT) : 10;

				// Ensure category_name is sanitized
				if (!empty($category_name)) {
					$get_cate = $wpdb->get_var($wpdb->prepare("SELECT id FROM {$prefix}pms_category WHERE category LIKE %s", '%' . $wpdb->esc_like($category_name) . '%'));
					$get_cate = absint($get_cate);
					$pass_rec = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$prefix}pms_passwords WHERE category_id = %d LIMIT 0, 10", $get_cate));	
					$pass_c	=	count($pass_rec);
				} else {
					$query = "SELECT * FROM {$prefix}pms_passwords";
					$pass_rec = $wpdb->get_results($wpdb->prepare($query));
					$pass_c	=	count($pass_rec);
					// Sanitize search value
					$searchVal = isset($_POST['search']['value']) ? sanitize_text_field($_POST['search']['value']) : '';
					if (!empty($searchVal)) {
						$query .= $wpdb->prepare(' WHERE user_name LIKE %s', '%' . ucfirst($searchVal) . '%');
					}

					// Sanitize order
					$data_order = isset($_POST['order'][0]['dir']) ? sanitize_text_field($_POST['order'][0]['dir']) : 'ASC';
					if (!empty($data_order)) {
						$query .= ' ORDER BY pass_id ' . $data_order;
					}

					// Validate limits
					if (isset($lengthLimit) && $lengthLimit != -1 && isset($startLimit)) {
						$query .= ' LIMIT %d, %d';
						$pass_rec = $wpdb->get_results($wpdb->prepare($query, $startLimit, $lengthLimit));
					} else {
						$query .= ' LIMIT 0, 10';
						$pass_rec = $wpdb->get_results($wpdb->prepare($query));
					}
					
				}

				$data = array();
				$rowCount = $startLimit;
				foreach ($pass_rec as $row) {
					$rowCount++;

					$id = absint($row->pass_id);
					$cId = absint($row->category_id);

					// Fetch category from the category table
					$query = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$prefix}pms_category WHERE id = %d", $cId));
					if ($query) {
						$category = esc_html($query->category);
						$category_color = esc_attr($query->category_color);
					} else {
						continue; // Skip if category is not found
					}

					$category_name = ucfirst($category);

					$sub_array = array();
					$sub_array[] = absint($rowCount);
					$sub_array[] = ucfirst(esc_html($row->user_name));
					$sub_array[] = esc_html($row->user_email);
					$sub_array[] = '<input id="user_pwd' . esc_html($id) . '" name="user_pwd" type="password" value="' . esc_html($row->user_password) . '" class="pass_inp border-0" readonly="readonly" style="box-shadow: none; background: none;">';
					$sub_array[] = '<style>.colorcode' . $rowCount . '.tag::before{ border-right: 10px solid ' . $category_color . ';}</style><span class="colorcode' . $rowCount . ' tag" style="background-color:' . $category_color . '">' . esc_html($category_name) . '</span>';
					$sub_array[] = '<a href="' . esc_url($row->url) . '" target="_blank" data-bs-toggle="tooltip" data-bs-placement="top" title="' . esc_url($row->url) . '"><i class="fas fa-link"></i></a>';
					$sub_array[] = '
                        <div class="share">
                            <div class="label"><i class="fas fa-ellipsis-v"></i></div>
                            <div class="social icon first"><a href="javascript:void(0);" data-id="' . esc_html($id) . '" id="s_' . esc_html($id) . '" class="decrypt" onclick="getpwd(this)" title="View password"><i class="fa fa-eye text-success"></i></a></div>
                            <div class="social icon"><a href="#" name="update" id="' . esc_html($id) . '" class="update" title="Edit password"><span class="dashicons dashicons-edit text-warning"></span></a></div>
                            <div class="social icon"><a href="#" name="dlt" class="dlt" id="' . esc_html($id) . '" title="Delete password"><span class="dashicons dashicons-trash text-danger"></span></a></div>
                            <div class="social icon"><a href="#" name="note_preview" id="' . esc_html($id) . '" class="note_preview" title="Preview your note"><span class="dashicons dashicons-clipboard"></span></a></div>
                            <div class="social icon"><a href="javascript:void(0);" data-clipboard-action="copy" data-clipboard-target="#user_pwd' . esc_html($id) . '" id="' . esc_html($id) . '" class="copy_clipboard" title="Password copy to clipboard"><span class="dashicons dashicons-admin-page"></span></a></div>
                            <div class="social icon last"><a href="javascript:void(0);" id="' . esc_html($id) . '" class="clonepass" title="Duplicate Password"><i class="fas fa-clone text-warning"></i></a></div>
                        </div>
                    ';

					$data[] = $sub_array;
				}

				// Prepare and output response
				$output = array(
					"recordsTotal" => filter_var($pass_c, FILTER_VALIDATE_INT),
					"recordsFiltered" => filter_var($pass_c, FILTER_VALIDATE_INT),
					"data" => $data
				);
				echo json_encode($output);
				die;
			}
		}
	}
}

//add new password
if (! function_exists('post_new_pass')) {
	function post_new_pass()
	{
		if (!current_user_can('manage_custom_data')) {
			wp_die(__('You do not have permission to manage this data.', 'passwords-manager'));
		}
		if (isset($_POST) && !empty($_POST)) {
			// Extract and sanitize POST data
			$btn_action = isset($_POST['btn_action']) ? sanitize_text_field($_POST['btn_action']) : '';
			$security_nonce = isset($_POST['security_nonce']) ? sanitize_text_field($_POST['security_nonce']) : '';

			// Verify nonce
			if (wp_verify_nonce($security_nonce, 'security_nonce')) {
				global $wpdb;
				$prefix = $wpdb->prefix;

				// Handle Add New Password
				if ($btn_action == 'Add') {
					$user_name = isset($_POST['user_name']) ? sanitize_text_field($_POST['user_name']) : '';
					$user_email = isset($_POST['user_email']) ? sanitize_email($_POST['user_email']) : '';
					$pass_cate = isset($_POST['pass_cat']) ? filter_var($_POST['pass_cat'], FILTER_VALIDATE_INT) : 0;
					$encry_pass = isset($_POST['ency']) ? sanitize_text_field($_POST['ency']) : '';
					$user_note = isset($_POST['user_note']) ? sanitize_textarea_field($_POST['user_note']) : '';
					$user_url = isset($_POST['user_url']) ? esc_url_raw($_POST['user_url']) : '';

					// Validate required fields
					if (empty($user_name) || empty($user_email) || empty($pass_cate)) {
						echo json_encode(['error' => 'Missing required fields']);
						die;
					}

					// Insert new password record
					$table_name = $prefix . "pms_passwords";
					$insert_result = $wpdb->insert(
						$table_name,
						[
							'user_name' => $user_name,
							'user_email' => $user_email,
							'user_password' => $encry_pass,
							'category_id' => $pass_cate,
							'note' => $user_note,
							'url' => $user_url,
						],
						['%s', '%s', '%s', '%d', '%s', '%s']
					);

					if ($insert_result) {
						echo json_encode(['success' => 'Password added successfully']);
					} else {
						echo json_encode(['error' => 'Failed to add password']);
					}
				}
				// Handle Edit Password
				elseif ($btn_action == 'Edit') {
					$pass_id = isset($_POST['pass_id']) ? absint($_POST['pass_id']) : 0;
					$user_name = isset($_POST['user_name']) ? sanitize_text_field($_POST['user_name']) : '';
					$user_email = isset($_POST['user_email']) ? sanitize_email($_POST['user_email']) : '';
					$pass_cate = isset($_POST['pass_cat']) ? filter_var($_POST['pass_cat'], FILTER_VALIDATE_INT) : 0;
					$encry_pass = isset($_POST['ency']) ? sanitize_text_field($_POST['ency']) : '';
					$user_note = isset($_POST['user_note']) ? sanitize_textarea_field($_POST['user_note']) : '';
					$user_url = isset($_POST['user_url']) ? esc_url_raw($_POST['user_url']) : '';

					// Validate required fields
					if (empty($user_name) || empty($user_email) || empty($pass_cate) || empty($pass_id)) {
						echo json_encode(['error' => 'Missing required fields']);
						die;
					}

					// Update password record
					$table_name = $prefix . "pms_passwords";
					$update_result = $wpdb->update(
						$table_name,
						[
							'user_name' => $user_name,
							'user_email' => $user_email,
							'user_password' => $encry_pass,
							'category_id' => $pass_cate,
							'note' => $user_note,
							'url' => $user_url,
						],
						['pass_id' => $pass_id],
						['%s', '%s', '%s', '%d', '%s', '%s'],
						['%d']
					);

					if ($update_result !== false) {
						echo json_encode(['success' => 'Password updated successfully']);
					} else {
						echo json_encode(['error' => 'Failed to update password']);
					}
				}
				// Handle Delete Password
				elseif ($btn_action == 'Delete') {
					$pass_id = isset($_POST['pass_id']) ? absint($_POST['pass_id']) : 0;

					if (empty($pass_id)) {
						echo json_encode(['error' => 'Invalid password ID']);
						die;
					}

					// Delete password record
					$table_name = $prefix . "pms_passwords";
					$delete_result = $wpdb->delete($table_name, ['pass_id' => $pass_id], ['%d']);

					if ($delete_result) {
						echo json_encode(['success' => 'Password deleted successfully']);
					} else {
						echo json_encode(['error' => 'Failed to delete password']);
					}
				} else {
					echo json_encode(['error' => 'Invalid action']);
				}
			} else {
				echo json_encode(['error' => 'Nonce verification failed']);
			}
		}
		die;
	}
}


/*
**Fetch category detail in database
*/
if (! function_exists('edit_pass')) {
	function edit_pass()
	{
		if (!current_user_can('manage_custom_data')) {
			wp_die(__('You do not have permission to manage this data.', 'passwords-manager'));
		}
		global $wpdb;

		// Verify if $_POST is set and not empty
		if (isset($_POST) && !empty($_POST)) {
			// Validate and sanitize inputs
			$pass_id = isset($_POST['pass_id']) ? absint($_POST['pass_id']) : 0;
			$security_nonce = isset($_POST['security_nonce']) ? sanitize_text_field($_POST['security_nonce']) : '';

			// Verify nonce
			if (empty($pass_id) || !wp_verify_nonce($security_nonce, 'security_nonce')) {
				wp_send_json_error(['message' => 'Invalid request'], 400);
				die;
			}

			// Encryption key validation
			$key_qry  = get_option('pms_encrypt_key');
			$stng_key = sanitize_text_field($key_qry);

			if (class_exists('Encryption')) {
				$Encryption = new Encryption();
			} else {
				wp_send_json_error(['message' => 'Encryption class not found'], 500);
				die;
			}

			// Secure query execution
			$table_name = $wpdb->prefix . 'pms_passwords';
			$query = $wpdb->get_results(
				$wpdb->prepare("SELECT * FROM {$table_name} WHERE pass_id = %d", $pass_id),
				ARRAY_A
			);

			// Process the result
			if ($query && count($query) > 0) {
				$row = $query[0]; // Single row expected
				$output = [
					'user_name'    => esc_html($row['user_name']),
					'user_email'   => sanitize_email($row['user_email']),
					'user_password' => $Encryption->decrypt(sanitize_text_field($row['user_password']), $stng_key),
					'user_category' => absint($row['category_id']),
					'user_note'    => esc_textarea($row['note']),
					'user_url'     => esc_url($row['url']),
				];

				wp_send_json_success($output, 200);
			} else {
				wp_send_json_error(['message' => 'No records found'], 404);
			}
		} else {
			wp_send_json_error(['message' => 'No data received'], 400);
		}
		die;
	}
}



/**
 **decrypt key
 */
if (! function_exists('decrypt_pass')) {
	function decrypt_pass()
	{
		if (!current_user_can('manage_custom_data')) {
			wp_die(__('You do not have permission to manage this data.', 'passwords-manager'));
		}
		global $wpdb;
		$prefix = $wpdb->prefix;

		// Ensure POST data is set
		if (isset($_POST) && !empty($_POST)) {
			// Sanitize and assign POST data to variables
			$security_nonce = isset($_POST['security_nonce']) ? sanitize_text_field($_POST['security_nonce']) : '';
			$saction = isset($_POST['saction']) ? sanitize_text_field($_POST['saction']) : '';
			$user_pwd = isset($_POST['user_pwd']) ? sanitize_text_field($_POST['user_pwd']) : '';
			$did = isset($_POST['did']) ? absint($_POST['did']) : 0; // Decrypt ID

			// Verify nonce for security
			if (!wp_verify_nonce($security_nonce, 'security_nonce')) {
				echo json_encode(['error' => 'Nonce verification failed']);
				die;
			}

			// Check if encryption class exists
			if (class_exists('Encryption')) {
				$Encryption = new Encryption();
			} else {
				echo json_encode(['error' => 'Encryption class not found']);
				die;
			}

			// Decrypt action
			if ($saction == 'decrypt' && !empty($user_pwd)) {
				$key_qry = get_option('pms_encrypt_key');
				$stng_key = esc_html($key_qry);

				// Decrypt the password securely
				$dcryppwd = $Encryption->decrypt($user_pwd, $stng_key);
				echo esc_html($dcryppwd);
				die;
			}

			// Encrypt action
			if ($saction == 'encrypt' && $did > 0) {
				// Prepare and execute SQL query safely
				$query = $wpdb->get_results(
					$wpdb->prepare("SELECT user_password FROM {$prefix}pms_passwords WHERE pass_id = %d", $did)
				);

				// Check if data exists and process
				if (!empty($query)) {
					$ecryppwd = $query[0]->user_password;
					echo esc_html($ecryppwd);
				} else {
					echo json_encode(['error' => 'No password found for the provided ID']);
				}
				die;
			}
		}

		// If we reach this point, return an error
		echo json_encode(['error' => 'Invalid request']);
		die;
	}
}


/**
 **clone password
 */
if (! function_exists('clone_password')) {
	function clone_password()
	{
		if (!current_user_can('manage_custom_data')) {
			wp_die(__('You do not have permission to manage this data.', 'passwords-manager'));
		}
		global $wpdb;
		$prefix = $wpdb->prefix;

		// Check if the POST request is set and not empty
		if (isset($_POST) && !empty($_POST)) {
			// Sanitize and validate input
			$security_nonce = isset($_POST['security_nonce']) ? sanitize_text_field($_POST['security_nonce']) : '';
			$pass_id = isset($_POST['pass_id']) ? absint($_POST['pass_id']) : 0;

			// Verify nonce for security
			if (!wp_verify_nonce($security_nonce, 'security_nonce')) {
				echo json_encode(['error' => 'Nonce verification failed']);
				die;
			}

			// Check if pass_id is valid
			if ($pass_id > 0) {
				// Retrieve the password data securely
				$query = $wpdb->get_row(
					$wpdb->prepare("SELECT * FROM {$prefix}pms_passwords WHERE pass_id = %d", $pass_id),
					ARRAY_A
				);

				if ($query) {
					// Clone the password record
					$table_name = $prefix . "pms_passwords";
					$final_rslt = $wpdb->insert(
						$table_name,
						array(
							'user_name'     => sanitize_text_field($query['user_name']),
							'user_email'    => sanitize_email($query['user_email']),
							'user_password' => sanitize_text_field($query['user_password']),
							'category_id'   => absint($query['category_id']),
							'note'           => sanitize_textarea_field($query['note']),
							'url'            => esc_url_raw($query['url']),
						),
						array('%s', '%s', '%s', '%d', '%s', '%s')
					);

					// Check if insertion was successful
					if ($final_rslt) {
						echo "success";
					} else {
						echo "failed";
					}
				} else {
					echo json_encode(['error' => 'Password record not found']);
				}
			} else {
				echo json_encode(['error' => 'Invalid pass_id']);
			}
			die;
		}
	}
}

/*
**Add actions category detail
*/
add_action('wp_ajax_get_new_pass', 'get_new_pass');
add_action('wp_ajax_nopriv_get_new_pass', 'get_new_pass');
add_action('wp_ajax_post_new_pass', 'post_new_pass');
add_action('wp_ajax_edit_pass', 'edit_pass');
add_action('wp_ajax_clone_pass', 'clone_password');
add_action('wp_ajax_decrypt_pass', 'decrypt_pass');
add_action('wp_ajax_nopriv_decrypt_pass', 'decrypt_pass');
