<?php

namespace CarDealerPress\Includes\Functions;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Transfer.
 * This class contains functions to transfer the settings/options
 * from the legacy version of the plugin.
 */

use CarDealerPress\Includes\Database\Alter_Tables;
use CarDealerPress\Includes\Database\Company_Handler;
use CarDealerPress\Includes\Database\Inserts;
use CarDealerPress\Includes\Database\Inventory_Handler;
use CarDealerPress\Includes\Database\Requests;
use CarDealerPress\includes\helpers\helpers;
use CarDealerPress\Includes\Helpers\Option;
use CarDealerPress\Includes\Helpers\Remote_Requests;
use CarDealerPress\Includes\Init\Default_Options;


class Transfer {
	use Logger;

	private $db_request;
	private $db_companies;

	public function __construct() {
		$this->run();
	}
	// FIXME TODO remove cdp_parallel_call cron
	// Cron reschedule event error for hook: cdp_parallel_call, Error code: could_not_set, Error message:
	// The cron event list could not be saved., Data: {"schedule":"hourly","args":

	public function run() {
		if ( get_option( 'cardealerpress_settings' ) && ! get_option( 'cdp_transfer_options' ) ) {
			$this->append_log( array( 'message' => 'CDP Message: CarDealerPress found, transferring options' ) );
			$this->transfer_settings_one_time();
			$this->populate_db();
			$this->transfer_maps();
			// delete_option('cdp_transfer_options'); // TODO: This should stay. Remove in future.
			// TODO: Legacy to be removed in future.
			// delete_option( 'cardealerpress_settings' );
			// delete_option( 'cardealerpress_extender_settings' );
			delete_site_transient( 'dt_geo_data' );
			delete_site_transient( 'cdp_dealer_names' );
		}
	}

	public function transfer_settings_one_time() {
		if ( ! get_option( 'cdp_transfer_options' ) ) {
			$cdp_settings      = get_option( 'cardealerpress_settings' );
			$cdp_admin_options = get_option( 'cdp_admin_options' );
			$cdp_theme_options = get_option( 'cdp_theme_options' );

			$company_id                = $cdp_settings['vehicle_management_system']['company_information']['id'];
			$this->db_request          = new Requests();
			$this->db_companies        = $this->db_request->cdp_company_request( $company_id );
			$host                      = $cdp_settings['vehicle_management_system']['host'];
			$discourage_seo_visibility = $cdp_settings['alt_settings']['discourage_seo_visibility'];
			$debug_plugin_info         = $cdp_settings['alt_settings']['debug_plugin_info'];
			$color_mapping             = $cdp_settings['vehicle_management_system']['color_mapping'];
			$prices                    = $cdp_settings['vehicle_management_system']['theme']['price_text'];
			$social                    = $cdp_settings['vehicle_management_system']['social'];
			$per_page                  = $cdp_settings['vehicle_management_system']['theme']['per_page'];
			$saleclass                 = $cdp_settings['vehicle_management_system']['saleclass'];
			$default_no_image          = $cdp_settings['vehicle_management_system']['data']['default_no_image'];
			$makes_new                 = $cdp_settings['vehicle_management_system']['data']['makes_new'];
			$custom_contact            = $cdp_settings['vehicle_management_system']['custom_contact'];
			$disclaimer                = $this->db_request->cdp_disclaimer_request();
			$theme_name                = $cdp_settings['vehicle_management_system']['theme']['name'];
			$show_standard_eq          = $cdp_settings['vehicle_management_system']['theme']['show_standard_eq'];
			$display_tags              = $cdp_settings['vehicle_management_system']['theme']['display_tags'];
			$display_geo               = $cdp_settings['vehicle_management_system']['theme']['display_geo'];
			$add_geo_zip               = $cdp_settings['vehicle_management_system']['theme']['add_geo_zip'];
			$geo_options               = $cdp_settings['vehicle_management_system']['theme']['geo_options'];

			$display_dealer_name       = $cdp_settings['vehicle_management_system']['theme']['display_dealer_contact_name'];
			$display_dealer_phone      = $cdp_settings['vehicle_management_system']['theme']['display_dealer_contact_phone'];
			$display_dealer_address    = $cdp_settings['vehicle_management_system']['theme']['display_dealer_contact_address'];
			$display_dealer_city_state = $cdp_settings['vehicle_management_system']['theme']['display_dealer_contact_city_state'];

			$display_similar      = $cdp_settings['vehicle_management_system']['theme']['display_similar'];
			$display_bodystyle    = $cdp_settings['vehicle_management_system']['theme']['display_bodystyle'];
			$display_drivetrain   = $cdp_settings['vehicle_management_system']['theme']['display_drivetrain'];
			$display_mpg          = $cdp_settings['vehicle_management_system']['theme']['display_mpg'];
			$display_transmission = $cdp_settings['vehicle_management_system']['theme']['display_transmission'];
			// $detail_format = ($cdp_settings['vehicle_management_system']['theme']['detail_format'] == 0) ? 'Default':'Style 2'; # TODO not found??

			$default_image_tab = ( 0 === intval( $cdp_settings['vehicle_management_system']['theme']['default_image_tab'] ) ) ? 'Photo' : 'Video';
			$default_info_tab  = ( 0 === intval( $cdp_settings['vehicle_management_system']['theme']['default_info_tab'] ) ) ? 'Description' : 'Options';

			$list_form_button         = $cdp_settings['vehicle_management_system']['theme']['list_form_button'];
			$list_info_button         = $cdp_settings['vehicle_management_system']['theme']['list_info_button'];
			$list_gform_id            = $cdp_settings['vehicle_management_system']['theme']['list_gform_id'];
			$detail_gform_id          = $cdp_settings['vehicle_management_system']['theme']['detail_gform_id'];
			$hide_saleclass           = $cdp_settings['vehicle_management_system']['theme']['hide_saleclass'];
			$hide_features            = $cdp_settings['vehicle_management_system']['theme']['hide_features'];
			$hide_vehicleclass        = $cdp_settings['vehicle_management_system']['theme']['hide_vehicleclass'];
			$hide_certified_saleclass = $cdp_settings['vehicle_management_system']['theme']['hide_certified_saleclass'];
			$saved_vehicles           = $cdp_settings['vehicle_management_system']['theme']['saved_vehicles'];
			$forms                    = $cdp_settings['vehicle_management_system']['theme']['forms'];

			$tags     = $cdp_settings['vehicle_management_system']['tags'];
			$sort     = $cdp_settings['vehicle_management_system']['sort'];
			$banners  = $cdp_settings['vehicle_management_system']['banners'];
			$scripts  = $cdp_settings['vehicle_management_system']['scripts'];
			$styles   = $cdp_settings['vehicle_management_system']['styles'];
			$keywords = $cdp_settings['vehicle_management_system']['keywords'];
			$loan     = $cdp_settings['vehicle_management_system']['theme']['loan'];
			$emails   = $cdp_settings['vehicle_management_system']['theme']['emails']; // might have to convert fn_views 278

			// ADMIN.
			$cdp_admin_options['admin']['general']['company_id']                = $company_id;
			$cdp_admin_options['admin']['general']['vdp_url_identifier']        = 'vin';
			$cdp_admin_options['admin']['general']['discourage_seo_visibility'] = $discourage_seo_visibility;
			$cdp_admin_options['admin']['general']['debug_plugin_info']         = $debug_plugin_info;
			$cdp_admin_options['admin']['help']['host']                         = $host;
			$cdp_admin_options['admin']['database']['company']['current']       = '6.0.2206.01'; // legacy version updates were in the multi_request file.
			$cdp_admin_options['admin']['database']['inventory']['current']     = '6.1.2301.00';

			// THEME general.
			$cdp_theme_options['theme']['general']['name']   = $theme_name;
			$cdp_theme_options['theme']['general']['social'] = $social;

			// override.
			$cdp_theme_options['theme']['overrides']['disclaimer']                   = $disclaimer;
			$cdp_theme_options['theme']['overrides']['custom_contact']['phone']      = $custom_contact['phone'];
			$cdp_theme_options['theme']['overrides']['custom_contact']['name']       = $custom_contact['contact_name'];
			$cdp_theme_options['theme']['overrides']['custom_contact']['breadcrumb'] = $custom_contact['breadcrumb'];
			$cdp_theme_options['theme']['overrides']['custom_contact']['street']     = $custom_contact['street'];
			$cdp_theme_options['theme']['overrides']['custom_contact']['city']       = $custom_contact['city'];
			$cdp_theme_options['theme']['overrides']['custom_contact']['zip']        = $custom_contact['zip'];

			$cdp_theme_options['theme']['overrides']['per_page']  = $per_page;
			$cdp_theme_options['theme']['overrides']['saleclass'] = $saleclass;
			// $cdp_theme_options['theme']['overrides']['makes_new']['included'] = $makes_new; # TODO, need to call all makes, before transfering, which won't work. might ignore.
			$cdp_theme_options['theme']['overrides']['default_no_image'] = $default_no_image;

			if ( ! empty( $emails['dealers'] ) ) {
				$emails['dealers'] = $this->numeric_to_text(
					array(
						'array'  => $emails['dealers'],
						'field'  => 'saleclass',
						'values' => array( 'all', 'new', 'used' ),
					)
				);
				foreach ( $emails['dealers'] as $row => $email ) {
					if ( 'N' === $email['is_adf'] ) {
						$emails['dealers'][ $row ]['is_adf'] = 'no';
					} else {
						$emails['dealers'][ $row ]['is_adf'] = 'yes';
					}
				}
				$cdp_theme_options['theme']['automall_emails'] = $emails;
			}

			$cdp_theme_options['theme']['inventory_display']['tags']['custom'] = $tags['data'];

			if ( 'string' === gettype( $tags['exclude'] ) ) {
				$exclude_tags = explode( ',', $tags['exclude'] );
			} else {
				$exclude_tags = $tags['exclude'];
			}
			// @codingStandardsIgnoreStart
			$cdp_theme_options['theme']['inventory_display']['tags']['exclude'] = $exclude_tags;
			// @codingStandardsIgnoreEnd

			$cdp_theme_options['theme']['inventory_display']['banners']            = $banners;
			$cdp_theme_options['theme']['inventory_display']['payment_calculator'] = $loan;

			$cdp_theme_options['theme']['inventory_display']['list']['general']['display_dealer_name']  = $display_dealer_name;
			$cdp_theme_options['theme']['inventory_display']['list']['general']['display_dealer_phone'] = $display_dealer_phone;
			if ( $display_dealer_address ) {
				$cdp_theme_options['theme']['inventory_display']['list']['general']['display_address_options'] = 'full';
			}
			if ( $display_dealer_city_state ) {
				$cdp_theme_options['theme']['inventory_display']['list']['general']['display_address_options'] = 'city_state';
			}
			$cdp_theme_options['theme']['inventory_display']['tags']['display_tags']                = $display_tags;
			$cdp_theme_options['theme']['inventory_display']['general']['saved_vehicles']           = $saved_vehicles;
			$cdp_theme_options['theme']['inventory_display']['general']['both']['styles']['inject'] = $styles['inject'];

			$cdp_theme_options['theme']['inventory_display']['prices']['text'] = $prices;

			$legacy_price = array(
				'was_now'        => 'on',
				'strike_through' => 'on',
				'show_used'      => 'on',
				'show_new'       => 'on',
			);
			$cdp_theme_options['theme']['inventory_display']['prices']['display']      = $legacy_price;
			$cdp_theme_options['theme']['inventory_display']['prices']['text']['new']  = $this->recursive_change_key(
				$cdp_theme_options['theme']['inventory_display']['prices']['text']['new'],
				array(
					'default_price'  => 'call_for_price',
					'standard_price' => 'price',
				)
			);
			$cdp_theme_options['theme']['inventory_display']['prices']['text']['used'] = $this->recursive_change_key(
				$cdp_theme_options['theme']['inventory_display']['prices']['text']['used'],
				array(
					'default_price'  => 'call_for_price',
					'standard_price' => 'price',
				)
			);

			$cdp_theme_options['theme']['inventory_display']['list']['general']['buttons']['form']['name']     = $list_form_button;
			$cdp_theme_options['theme']['inventory_display']['list']['general']['buttons']['form']['gform_id'] = $list_gform_id;
			$cdp_theme_options['theme']['inventory_display']['list']['general']['buttons']['vdp_link']['name'] = $list_info_button;

			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['display_bodystyle']        = $display_bodystyle;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['display_drivetrain']       = $display_drivetrain;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['display_mpg']              = $display_mpg;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['display_transmission']     = $display_transmission;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['hide_saleclass']           = $hide_saleclass;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['hide_features']            = $hide_features;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['hide_vehicleclass']        = $hide_vehicleclass;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['hide_certified_saleclass'] = $hide_certified_saleclass;

			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'] = $display_geo;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['add_geo_zip'] = $add_geo_zip;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['geo_options'] = $geo_options;
			$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['color_mapping']             = $color_mapping;
			$cdp_theme_options['theme']['inventory_display']['list']['keywords']                                    = $keywords;
			// @codingStandardsIgnoreStart
			$cdp_theme_options['theme']['inventory_display']['list']['keywords']['exclude']                         = explode( ',', $keywords['exclude'] );
			// @codingStandardsIgnoreEnd
			$cdp_theme_options['theme']['inventory_display']['list']['keywords']['pot']                             = explode( ',', $keywords['pot'] );

			$cdp_theme_options['theme']['inventory_display']['list']['sort']['default'] = $sort['default'];
			$sort_data = $sort['data'];
			$cdp_theme_options['theme']['inventory_display']['list']['sort']['custom'] = $this->recursive_change_key(
				$sort_data,
				array(
					'sort' => 'sort_value',
					'tags' => 'tag',
				)
			);

			$cdp_theme_options['theme']['inventory_display']['list']['scripts']['inject'] = $scripts['inject']['list'];

			$cdp_theme_options['theme']['inventory_display']['detail']['scripts']['inject'] = $scripts['inject']['detail'];
			$cdp_theme_options['theme']['inventory_display']['detail']['detail_format']     = 'Default';
			// $cdp_theme_options['theme']['inventory_display']['detail']['detail_format'] = $detail_format; // # TODO fix me, not found
			$detail = array( 'display_similar', 'default_image_tab', 'default_info_tab', 'show_standard_eq' );
			foreach ( $detail as $key ) {
				$cdp_theme_options['theme']['inventory_display']['detail']['general'][ $key ] = $$key;
			}

			$scripts_converted = $this->convert_data( $scripts['data'] );
			$cdp_theme_options['theme']['inventory_display']['script_assets'] = $scripts_converted;

			$styles_converted = $this->convert_data( $styles['data'] );
			$cdp_theme_options['theme']['inventory_display']['style_assets'] = $styles_converted;

			if ( $detail_gform_id ) {
				// TODO title pulls from GF Title, depends on inventory
				$converted_legacy = array(
					'id'        => $detail_gform_id,
					'button'    => 'on',
					'title'     => '',
					'saleclass' => 'all',
				);
				array_unshift( $forms, $converted_legacy );
			}
			$forms = $this->numeric_to_text(
				array(
					'array'  => $forms,
					'field'  => 'saleclass',
					'values' => array( 'all', 'new', 'used' ),
				)
			);

			$cdp_theme_options['theme']['inventory_display']['detail']['forms'] = $forms;

			if ( get_option( 'cardealerpress_extender_settings' ) ) {
				$results           = $this->get_extender_settings( $cdp_admin_options, $cdp_theme_options );
				$cdp_admin_options = $results['admin'];
				$cdp_theme_options = $results['theme'];
			}
			// merge current options with default.
			$cdp_admin = array_replace_recursive( Default_Options::$default_options_admin, $cdp_admin_options );
			$cdp_theme = array_replace_recursive( Default_Options::$default_options_theme, $cdp_theme_options );
			add_option( 'cdp_admin_options', $cdp_admin );
			add_option( 'cdp_theme_options', $cdp_theme );
			add_option( 'cdp_transfer_options', 1 );
		}
	}

	public function get_extender_settings( $cdp_admin_options, $cdp_theme_options ) {
		$cdp_settings = get_option( 'cardealerpress_settings' );
		$ext_settings = get_option( 'cardealerpress_extender_settings' );
		$imports      = $this->db_request->cdp_admin_get_custom_imports();
		if ( ! empty( $imports ) ) {
			foreach ( $imports as $import ) {
				$filters          = maybe_unserialize( $import['data_value'] );
				$renamed_filters  = array(
					'saleclass'      => $this->numeric_to_text_single_field(
						array(
							'current' => $filters['saleclass'],
							'values'  => array( 'all', 'new', 'used' ),
						)
					),
					'makes'          => $filters['make']['value'],
					'make_qualifier' => $this->numeric_to_text_single_field(
						array(
							'current' => $filters['make']['symbol'],
							'values'  => array( 'equal', 'not equal' ),
						)
					),
					'years'          => $filters['year']['value'],
					'year_qualifier' => $this->numeric_to_text_single_field(
						array(
							'current' => $filters['year']['symbol'],
							'values'  => array( 'equal', 'not equal', 'greater than', 'less than' ),
						)
					),
				);
				$import_filters[] = array_merge( array( 'dealer_id' => $import['dealer_id'] ), $renamed_filters );
			}
			$cdp_admin_options['admin']['advanced']['import_filters'] = $import_filters;
		}

		$advanced_dealers = array();
		$company_id       = $cdp_admin_options['admin']['general']['company_id'];
		foreach ( $this->db_companies as $db_dealer ) {
			if ( $db_dealer['dealer_id'] !== $company_id ) {
				$advanced_dealers[] = array( 'company_id' => $db_dealer['dealer_id'] );
			}
		}
		$cdp_admin_options['admin']['advanced']['dealers'] = $advanced_dealers;
		$show_saleclass_tag                                = $ext_settings['show_saleclass_tag'];
		$search_view                                       = $ext_settings['search_view'];
		$srp_view             = $ext_settings['srp_view'];
		$no_results_form      = $ext_settings['no_results_form'] ?? '0';
		$no_results_form_text = $ext_settings['no_results_form_text'] ?? 'Sorry, no results found. Please modify your selection in the filters above, remove existing filters';
		$price_range          = $ext_settings['price_range'];
		$odometer_range       = $ext_settings['odometer_range'];
		$extras               = $ext_settings['extras'];
		$maps                 = $ext_settings['maps'];
		$list_title_heading   = $ext_settings['list_title_heading'];
		$google_tags          = $ext_settings['google_tags'];

		$cdp_theme_options['theme']['general']['name'] = 'flamingo';

		$cdp_theme_options['theme']['inventory_display']['general']['both']['extra_boxes']['box_two']   = $extras['box_two'];
		$cdp_theme_options['theme']['inventory_display']['general']['both']['extra_boxes']['box_three'] = $extras['box_three'];
		$cdp_theme_options['theme']['inventory_display']['general']['both']['extra_boxes']['box_four']  = $extras['box_four'];

		$cdp_theme_options['theme']['inventory_display']['list']['general']['list_title_heading']   = $list_title_heading;
		$cdp_theme_options['theme']['inventory_display']['list']['general']['no_results_form']      = $no_results_form;
		$cdp_theme_options['theme']['inventory_display']['list']['general']['no_results_form_text'] = $no_results_form_text;

		$cdp_settings = get_option( 'cardealerpress_settings' );
		$scripts      = $cdp_settings['vehicle_management_system']['scripts'];
		if ( array_key_exists( 'list_ajax', $scripts['inject'] ) ) {
			$cdp_theme_options['theme']['inventory_display']['list']['scripts']['ajax'] = $scripts['inject']['list_ajax'];
		}
		$geo_display = $cdp_settings['vehicle_management_system']['theme']['geo_display'];
		$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['geo_search']['display_geo'] = $geo_display;

		$cdp_theme_options['theme']['inventory_display']['detail']['maps']['key']                 = $maps['key'];
		$cdp_theme_options['theme']['inventory_display']['detail']['maps']['display']             = $maps['display'];
		$cdp_theme_options['theme']['inventory_display']['detail']['maps']['custom'][0]['dealer'] = $maps['default'];
		if ( ! empty( $maps['custom'] ) ) {
			$row = 1;
			foreach ( $maps['custom'] as $map ) {
				$cdp_theme_options['theme']['inventory_display']['detail']['maps']['custom'][ $row ]['dealer'] = $map;
				$row += 1;
			}
		}

		$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['show_saleclass_tag'] = $show_saleclass_tag;
		$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['search_view']        = $search_view;
		$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['srp_view']           = $srp_view;
		$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['price_range']        = $price_range;
		$cdp_theme_options['theme']['inventory_display']['list']['search_filters']['general']['odometer_range']     = $odometer_range;

		$cdp_admin_options['admin']['general']['google_tags'] = $google_tags;

		return array(
			'admin' => $cdp_admin_options,
			'theme' => $cdp_theme_options,
		);

	}

	public function make_table_cdp_compaines_blog_specific() {
		// need to create blog specific tables,
		// don't think need to transfer any data
		// but probably would need to run the company handler after creation
	}

	public function make_table_cdp_datablog_specific() {

	}

	public function populate_db() {
		$company = $this->db_companies;
		if ( empty( $company ) ) { // Will return empty on legacy themes, not Flamingo.
			new Alter_Tables();
			$inserts = new Inserts();
			$this->append_log( array( 'message' => 'CDP Message: Populating cdp_data and cdp_companies with id: ' . helpers::company_id() . ' as part of Transfer process.' ) );
			// Adds Dealer to cdp_data and cdp_companies table.
			$inserts->cdp_data_and_cdp_companies( helpers::company_id() );
			( new Company_Handler() )->init_company_handler(
				array(
					'company_id' => helpers::company_id(),
					'purge'      => true,
				)
			);
			// Run import handler.
			$this->append_log( array( 'message' => 'CDP Message: Populating inventory tables with data for id: ' . helpers::company_id() . ' as part of Transfer process.' ) );
			( new Inventory_Handler() )->init_inventory_handler( helpers::company_id() );
		} else {
			// Need to update db table with seo information.
			new Alter_Tables();
			( new Company_Handler() )->init_company_handler(
				array(
					'company_id' => helpers::company_id(),
					'purge'      => true,
				)
			);
		}
	}

	public function transfer_maps() {
		$cdp_theme_options = get_option( 'cdp_theme_options' );
		$map_key           = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'detail',
				'maps',
				'key',
			)
		);
		$maps              = Option::check_for_option(
			'cdp_theme_options',
			array(
				'theme',
				'inventory_display',
				'detail',
				'maps',
				'custom',
			)
		);
		if ( ! empty( $map_key ) && ! empty( $maps ) ) {
			foreach ( $maps as $row_id => $dealer ) {
				$geocodes = ( new Maps() )->map_population( $map_key, $dealer['dealer']['dealer_id'] );
				foreach ( $geocodes as $index => $data ) {
					$dealer_geo = array(
						'dealer'  => $dealer['dealer'],
						'geocode' => $data['geocode'],
					);
					$cdp_theme_options['theme']['inventory_display']['detail']['maps']['custom'][ $row_id ] = $dealer_geo;
				}
			}
			update_option( 'cdp_theme_options', $cdp_theme_options );
		}
	}

	public function numeric_to_text_single_field( $args ) {
		$data   = $args['current'];
		$values = $args['values'];
		switch ( $data ) {
			case 0:
				return $values[0];
			case 1:
				return $values[1];
			case 2:
				return $values[2];
			case 3:
				return $values[3];
		}
	}

	public function numeric_to_text( $args ) {
		$data   = $args['array'];
		$field  = $args['field']; // saleclass or page
		$values = $args['values'];
		foreach ( $data as $key => $row ) {
			switch ( $row[ $field ] ) {
				case 0:
					$data[ $key ][ $field ] = $values[0];
					break;
				case 1:
					$data[ $key ][ $field ] = $values[1];
					break;
				case 2:
					$data[ $key ][ $field ] = $values[2];
					break;
			}
		}

		return $data;
	}

	public function convert_data( $data ) {
		$converted = $this->numeric_to_text(
			array(
				'array'  => $data,
				'field'  => 'saleclass',
				'values' => array( 'all', 'new', 'used' ),
			)
		);
		$converted = $this->numeric_to_text(
			array(
				'array'  => $converted,
				'field'  => 'page',
				'values' => array( 'all', 'list', 'detail' ),
			)
		);
		$converted = $this->numeric_to_text(
			array(
				'array'  => $converted,
				'field'  => 'location',
				'values' => array( 'header', 'footer' ),
			)
		);

		return $converted;
	}


	// $arr => original array
	// $set => array containing old keys as keys and new keys as values
	public function recursive_change_key( $arr, $set ) {
		if ( is_array( $arr ) && is_array( $set ) ) {
			$new_array = array();
			foreach ( $arr as $array_key => $array_value ) {
				$key               = array_key_exists( $array_key, $set ) ? $set[ $array_key ] : $array_key;
				$new_array[ $key ] = is_array( $array_value ) ? $this->recursive_change_key( $array_value, $set ) : $array_value;
			}

			return $new_array;
		}

		return $arr;
	}
}
