<?php
if (isset($_POST) && !empty($_POST)) {
	$pwdms_import_btn = isset($_POST['pwdms_import_btn']) ? sanitize_text_field($_POST['pwdms_import_btn']) : '';
	$security_nonce = isset($_POST['security_nonce']) ? sanitize_text_field($_POST['security_nonce']) : '';

	if ($pwdms_import_btn) {
		@error_reporting(E_ERROR);
		@set_time_limit(0);
		@ini_set('max_input_time', 3600 * 3);
		@ini_set('max_execution_time', 3600 * 3);

		if ($security_nonce && wp_verify_nonce($security_nonce, 'security_nonce')) {
			$encry_key = get_option('pms_encrypt_key');

			if (!empty($encry_key) && isset($_FILES['pwdms_csvim_upload_file']) && $_FILES['pwdms_csvim_upload_file']['size'] > 0) {
				$fileName = esc_html($_FILES['pwdms_csvim_upload_file']['tmp_name']);
				$file = fopen($fileName, 'r');
				$line = 0;
				$success = false;

				while (($data = fgetcsv($file, 100000, ',', "'")) !== false) {
					if ($line !== 0 && $line < 201) {
						$name = isset($data[0]) ? sanitize_text_field($data[0]) : '';
						$email = isset($data[1]) ? sanitize_email($data[1]) : '';
						$password = isset($data[2]) ? sanitize_text_field($data[2]) : '';
						$url = isset($data[3]) ? esc_url($data[3]) : '';
						$category = isset($data[4]) ? sanitize_text_field($data[4]) : '';
						$category_color = isset($data[5]) ? sanitize_text_field($data[5]) : '';
						$note = isset($data[6]) ? sanitize_textarea_field($data[6]) : '';

						$success = pwdms_custom_create_passwords_from_csv($name, $email, $password, $url, $category, $category_color, $note);
					}
					$line++;
				}
				fclose($file);

				$message = $success ? __('Data imported successfully', 'passwords-manager') : __('Data failed to import', 'passwords-manager');
			}
		} else {
			die('Permission denied');
		}
	}
}

include(PWDMS_INC . 'admin-page/addon/csv-import/pms-csv-import-setting-page/pms_import_html.php');
?>