<?php
add_action('wp_ajax_pwdms_export_detail_list', 'pwdms_export_detail_list');
function pwdms_export_detail_list()
{
	global $wpdb;

	if (isset($_POST['from_data']) && !empty($_POST['from_data']) && is_array($_POST['from_data'])) {
		$from_data = $_POST['from_data'];

		if (
			isset($from_data['security_nonce']) &&
			wp_verify_nonce(sanitize_text_field($from_data['security_nonce']), 'security_nonce') &&
			is_user_logged_in() &&
			current_user_can('administrator')
		) {
			$pwdms_document_title = isset($from_data['pwdms_document_title']) ? esc_html($from_data['pwdms_document_title']) : '';
			$pwdms_csv_category = isset($from_data['pwdms_csv_category']) ? array_map('absint', explode(',', $from_data['pwdms_csv_category'])) : [];

			error_reporting(E_ERROR);

			if (!session_id()) {
				session_start();
			}

			$time_start = microtime(true);
			ini_set('max_input_time', 3600 * 3);
			ini_set('max_execution_time', 3600 * 3);
			set_time_limit(0);

			$per_page = apply_filters('pwdms_csv_export_per_page_limit', 66);
			$page = max(1, absint($_POST['page_num']));

			$placeholders = implode(',', array_fill(0, count($pwdms_csv_category), '%d'));
			$query = $wpdb->prepare(
				"SELECT * FROM {$wpdb->prefix}pms_passwords 
                JOIN {$wpdb->prefix}pms_category ON {$wpdb->prefix}pms_category.id = {$wpdb->prefix}pms_passwords.category_id
                WHERE {$wpdb->prefix}pms_category.id IN ($placeholders) 
                LIMIT 200",
				$pwdms_csv_category
			);

			$export_res = $wpdb->get_results($query, OBJECT);

			if ($page == 1) {
				unset($_SESSION['pwdms_csv_array']);
				$_SESSION['pwdms_csv_array'] = [];
			} else {
				$csv_array = isset($_SESSION['pwdms_csv_array']) && is_array($_SESSION['pwdms_csv_array'])
					? $_SESSION['pwdms_csv_array']
					: [];
			}

			foreach ($export_res as $res) {
				$pwdms_name_array = isset($from_data['col_pwdms_name']) ? [__('Name', 'pwdms') => esc_html($res->user_name)] : [];
				$pwdms_email_array = isset($from_data['col_pwdms_email']) ? [__('Email', 'pwdms') => esc_html($res->user_email)] : [];
				$pwdms_password_array = isset($from_data['col_pwdms_password']) ? [
					__('Password', 'pwdms') => esc_html(
						(new Encryption())->decrypt(sanitize_text_field($res->user_password), esc_html(get_option('pms_encrypt_key')))
					)
				] : [];
				$pwdms_category_array = isset($from_data['col_pwdms_category']) ? [__('Category', 'pwdms') => esc_html($res->category)] : [];
				$pwdms_category_color_array = isset($from_data['col_pwdms_category']) ? [__('Category Color', 'pwdms') => esc_html($res->category_color)] : [];
				$pwdms_url_array = isset($from_data['col_pwdms_url']) ? [__('URL', 'pwdms') => esc_url($res->url)] : [];
				$pwdms_note_array = isset($from_data['col_pwdms_desc']) ? [__('Note', 'pwdms') => esc_textarea($res->note)] : [];

				$pwdms_csv_array[] = array_merge(
					$pwdms_name_array,
					$pwdms_email_array,
					$pwdms_password_array,
					$pwdms_url_array,
					$pwdms_category_array,
					$pwdms_category_color_array,
					$pwdms_note_array
				);

				$_SESSION['pwdms_csv_array'] = $pwdms_csv_array;
			}

			$time_end = microtime(true);
			$execution_time = $time_end - $time_start;
			$found_data = count($export_res);
			$response = [
				'page' => $page + 1,
				'done' => $page * $per_page >= $found_data,
				'execution_time' => $execution_time,
				'found_posts' => $found_data,
			];

			wp_send_json_success($response);
		}
	}
}


add_action('wp_ajax_pwdms_export_csv', 'pwdms_export');
function pwdms_export()
{
	// Verify nonce for security, check if user is logged in and is an admin
	if (isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field($_GET['_wpnonce']), 'security_nonce') && is_user_logged_in() && current_user_can('administrator')) {
		// Start session if not already started
		if (!session_id()) {
			session_start();
		}

		// Error reporting based on debug mode
		if (defined('pwdms_DEBUG') && pwdms_DEBUG) {
			error_reporting(E_ALL);
			ini_set('display_errors', 1);
		} else {
			error_reporting(0);
		}

		// Get the CSV data from session
		$array = $_SESSION['pwdms_csv_array'];
		if (count($array) == 0) {
			return null;
		}

		// Generate CSV content
		ob_start();
		$df = fopen('php://output', 'w');
		fputcsv($df, array_keys(reset($array)));
		foreach ($array as $row) {
			fputcsv($df, $row);
		}
		fclose($df);

		// Set filename and headers for CSV download
		if (isset($_GET['document_title']) && !empty(sanitize_text_field($_GET['document_title']))) {
			$filename = sanitize_text_field($_GET['document_title']) . '.csv';
			$now = gmdate("D, d M Y H:i:s");
			header("Expires: Tue, 03 Jul 2020 06:00:00 GMT");
			header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
			header("Last-Modified: {$now} GMT");
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Disposition: attachment;filename={$filename}");
			header("Content-Transfer-Encoding: binary");

			flush();
			@readfile($filename);
			exit;
		}
	}
}
