<?php
if(!defined('ABSPATH')){ exit; }

if(!class_exists('WCFE_Install')):

class WCFE_Install extends WCFE_Checkout_Fields_Admin_Utils{
	public $field_factory = NULL;
	
	public function __construct(){
		$this->field_factory = new WCFE_Checkout_Field_Factory();
	}
	
	public static function instance() {      
		if(is_null(self::$_instance)){ 
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	public function install() {
		if(!current_user_can('activate_plugins'))
            return;
			
        $plugin = isset( $_REQUEST['plugin'] ) ? $_REQUEST['plugin'] : '';
        check_admin_referer( "activate-plugin_{$plugin}" );
		
		$this->check_for_premium_settings();
		//$this->copy_old_version_settings_if_any();
		//$this->copy_free_version_settings_if_any();
	}
	
	public function copy_old_version_settings_if_any(){
		
	}
	
	public function check_for_premium_settings(){
		$premium_settings = get_option(self::OPTION_KEY_CUSTOM_SECTIONS);
		if($premium_settings){			
			return;
		}else{			
			$this->copy_free_version_settings_if_any();
		}
	}
	
	public function copy_free_version_settings_if_any(){
		$checkout_sections = array('billing', 'shipping', 'additional');
		
		foreach($checkout_sections as $sname){
			$field_set_key = 'wc_fields_'.$sname;
			$field_set = get_option($field_set_key);
			
			if($field_set && is_array($field_set)){
				$result = $this->prepare_and_save_settings($field_set, $sname);
				if($result){
					delete_option($field_set_key);
				}
			}
		}
	}

	public function prepare_and_save_settings($field_set, $sname){	
		$section = $this->get_checkout_section($sname);
		if(empty($section)){
			$this->prepare_sections_and_fields();
			$section = $this->get_checkout_section($sname);
		}
		$result = false;
		
		if(WCFE_Section_Utils::is_valid_section($section)){
			$section = WCFE_Section_Utils::clear_fields($section);

			if(is_array($field_set)){
				foreach($field_set as $name => $field){
					$type = isset($field['type']) ? $field['type'] : 'text';
					$new_field = WCFE_Field_Utils::create_field($type); 
					$new_field = WCFE_Field_Utils::prepare_field($new_field, $name, $field);
					
					if($type === 'select'){
						$options_json = is_array($new_field->get_property('options')) ? json_encode($new_field->get_property('options')) : '';
						$new_field->set_property('options_json',$options_json);
					}
					
					$new_field = WCFE_Field_Utils::prepare_properties($new_field);
					$section = WCFE_Section_Utils::add_field($section, $new_field);
				}
				$section = WCFE_Section_Utils::sort_fields($section);
				$result = $this->update_section($section);   
			} 
		}
		return $result;
	}
}

endif;