<?php

/*
  Plugin Name: Constructor de formularios
  Plugin URI: http://vegacorp.me
  Description:
 */

if (!class_exists('VG_CF7_Form_Builder_Core')) {

	class VG_CF7_Form_Builder_Core {

		static private $instance = false;
		var $textname = 'vg_cf7_form_builder';
		static $dir = __DIR__;
		static $file = __FILE__;

		private function __construct() {
			
		}

		function init() {
			add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'), 10);
			add_action('wpcf7_after_save', array($this, 'after_cf7_save'));
			add_filter('wpcf7_editor_panels', array($this, 'add_form_builder_panel'));
			add_action('wpcf7_after_save', array($this, 'after_cf7_copy'), 99);
		}

		/**
		 * Array map for a multimensional array
		 * @param str $f
		 * @param array $xs
		 * @return array
		 */
		function _array_map_recursive($f, $xs, $keys = 'all', $args = array()) {
			$out = array();

			if (is_array($xs)) {
				foreach ($xs as $k => $x) {
					if (!empty($keys) && is_array($keys)) {
						if (!is_array($x) && !in_array($k, $keys) || is_int($k) && !is_array($x)) {
							$out[$k] = $x;
							continue;
						}
					}
					if (is_array($x)) {
						$out[$k] = $this->_array_map_recursive($f, $x, $keys);
					} elseif (is_string($x)) {
						$out[$k] = call_user_func_array($f, array_merge(array($x), $args));
					} else {
						$out[$k] = $x;
					}
				}
			} else {
				$out = $xs;
			}
			return $out;
		}

		function _sanitize($var) {
			if (is_array($var)) {
				$var = $this->_array_map_recursive('wp_kses_post', $var);
			} elseif (is_string($var)) {
				$var = wp_kses_post($var);
			}
			return $var;
		}

		function after_cf7_copy($form) {
			$new_form_id = $form->id();
			$old_form_id = isset($_GET['post']) ? (int) $_GET['post'] : 0;
			if (!$old_form_id || !$new_form_id) {
				return;
			}
			update_post_meta($new_form_id, 'vg_form_builder_fields', get_post_meta($old_form_id, 'vg_form_builder_fields', true));
			update_post_meta($new_form_id, 'vg_two_columns', get_post_meta($old_form_id, 'vg_two_columns', true));
		}

		function after_cf7_save($form) {
			if (!isset($_REQUEST['vg_form_builder_fields'])) {
				$_REQUEST['vg_form_builder_fields'] = '';
			}

			update_post_meta($form->id(), 'vg_form_builder_fields', $this->_sanitize($_REQUEST['vg_form_builder_fields']));

			$vg_two_columns = (!isset($_REQUEST['vg_two_columns']) || $_REQUEST['vg_two_columns'] !== 'yes') ? '' : 'yes';
			update_post_meta($form->id(), 'vg_two_columns', $this->_sanitize($vg_two_columns));
		}

		/**
		 * Creates or returns an instance of this class.
		 *
		 * @return  Foo A single instance of this class.
		 */
		static function get_instance() {
			if (null == VG_CF7_Form_Builder_Core::$instance) {
				VG_CF7_Form_Builder_Core::$instance = new VG_CF7_Form_Builder_Core();
				VG_CF7_Form_Builder_Core::$instance->init();
			}
			return VG_CF7_Form_Builder_Core::$instance;
		}

		function __set($name, $value) {
			$this->$name = $value;
		}

		function __get($name) {
			return $this->$name;
		}

		function enqueue_assets($hook) {
			if (strpos($hook, 'wpcf7') === false) {
				return;
			}
			wp_enqueue_script('wp-cf7-builder-formBuilder', plugins_url('/assets/vendor/form-builder/form-builder.min.js', __FILE__), array('jquery', 'jquery-ui-core', 'jquery-ui-sortable'), '1.0', true);
			wp_enqueue_script('wp-cf7-builder-formRender', plugins_url('/assets/vendor/form-builder/form-render.min.js', __FILE__), array('jquery'), '1.0', true);
			//Agregando opcion para mostrar editor de codigo
			wp_enqueue_script('wp-cf7-builder-control-trumbowyg', plugins_url('/assets/vendor/form-builder/control_plugins/textarea.trumbowyg.min.js', __FILE__), array('jquery'), '1.0', true);

			//Cargando estilos creados con js
			if (is_dir(__DIR__ . '/form-styles')) {
				//Cargando estilos de tipo buttonized, los utilizamos en la parte del admin
				wp_register_style('wp-cf7-formBuilder-style-buttonized', plugins_url('/form-styles/style-formBuilder/style-buttonized.css', __FILE__));
				wp_enqueue_style('wp-cf7-formBuilder-style-buttonized');
			}

			wp_enqueue_script('wp-cf7-builder-init', plugins_url('/assets/js/init.js', __FILE__), array('jquery'), '1.0', true);
			//Pasando url de plugin para mostrar previews de imagenes con jquery
			wp_localize_script('wp-cf7-builder-init', 'wpCf7ScriptUrl', array(
				'pluginUrl' => plugins_url('', self::$file),
			));


			//Adding plugin css
			wp_register_style('wp-cf7-builder-css', plugins_url('/assets/css/cf7_style.css', __FILE__));
			wp_enqueue_style('wp-cf7-builder-css');

			wp_register_style('wp-cf7-fontawesome', plugins_url('/assets/css/all.min.css', __FILE__));
			wp_enqueue_style('wp-cf7-fontawesome');


			$form_id = (isset($_GET['post'])) ? (int) $_GET['post'] : null;
			$is_new_form = empty($form_id);

			if ($form_id) {
				$form_fields = json_decode(get_post_meta($form_id, 'vg_form_builder_fields', true), true);
			}
			if (empty($form_fields)) {
				$form_fields = array(array(
						'label' => "Name",
						'placeholder' => "Your name",
						'name' => "first-name",
						'type' => "text"
					),
					array(
						'label' => "Email",
						'placeholder' => "Your email",
						'name' => "wpCf7Email",
						'type' => "text",
						'extension' => "email"
					),
					array(
						'label' => "Message",
						'placeholder' => "Your message",
						'name' => "message",
						'type' => "textarea"
					),
					array(
						'label' => "Button",
						'type' => "button",
						'subtype' => "submit",
						'name' => "button",
				));
			}

			$disabled_fields = array('autocomplete');
			$form_builder_settings = apply_filters('vgcf7b_form_builder_settings', array(
				'dontUseOldEditorWarning' => __('<div class="error">Note. You shouldn´t use this tab when using the form builder because it will get overwritten. This tab is available for old forms that were created without the form builder.</div>', $this->textname),
				'upgradeLink' => '',
				'isNewForm' => $is_new_form,
				'defaultFields' => $form_fields,
				'disabledActionButtons' => array('data', 'save'),
				'disabledAttrs' => array(
					'access',
					'description',
					'maxlength',
					/* Lo desabilite porque lo necesitamos para generar el editor de texto */
					/* 'subtype', */
					'style',
					'inline',
					'toggle',
					'other',
				),
				'disableFields' => $this->_sanitize($disabled_fields),
				'i18n' => array(
					'locale' => str_replace('_', '-', get_locale()),
					'location' => plugins_url('/assets/vendor/form-builder/languages/', __FILE__)
				),
				'texts' => array(
					'width' => __('Width', $this->textname),
					'default_value' => __('Default value', $this->textname),
					'user_login_name' => __("User's login name", $this->textname),
					'user_email' => __("User's email address", $this->textname),
					'user_url' => __("User's site URL", $this->textname),
					'user_first_name' => __("User's first name", $this->textname),
					'user_last_name' => __("User's last name", $this->textname),
					'user_nickname' => __("User's nickname", $this->textname),
					'user_display_name' => __("User's display name", $this->textname),
					'type' => __("Type", $this->textname),
					'cols' => __("Cols", $this->textname),
					'filetypes' => __("Filetypes", $this->textname),
					'limit' => __("Limit", $this->textname),
					'step' => __("Step", $this->textname),
					'value' => __("Value", $this->textname),
					'paragraph' => __("Paragraph", $this->textname),
					'url' => __("URL", $this->textname),
					'email' => __("Email", $this->textname),
					'old_form' => __('Old form', $this->textname),
					'repeated_fields_notice' => __("There are repeated fields please check if you want to remove them", $this->textname),
				)
			));

			wp_localize_script('wp-cf7-builder-init', 'vgcf7b_form_builder_settings', $form_builder_settings);
		}

		function render_form_builder_panel($form) {
			$form_id = $form->id();

			$vg_two_columns = get_post_meta($form_id, 'vg_two_columns', true);
			$is_two_columns_disabled = apply_filters('vgcf7b_two_columns_disabled', ' ', $form_id);
			$two_columns_after = apply_filters('vgcf7b_two_columns_after', '', $form_id);
			include __DIR__ . '/views/metabox.php';
		}

		function add_form_builder_panel($panels) {
			$new_panels = array();
			$new_panels['vg-form-builder-panel'] = array(
				'title' => __('Form builder', $this->textname),
				'callback' => array($this, 'render_form_builder_panel'));

			return array_merge($new_panels, $panels);
		}

	}

}

if (!function_exists('VG_CF7_Form_Builder_Core_Obj')) {

	function VG_CF7_Form_Builder_Core_Obj() {
		return VG_CF7_Form_Builder_Core::get_instance();
	}

}

VG_CF7_Form_Builder_Core_Obj();
