<?php
if(!class_exists('Chronosly_Settings'))
{
	class Chronosly_Settings
	{
		/**
		 * Construct the plugin object
		 */
        public $settings_menu;
        public $addons_menu;
        public $addons_settings;
		public function __construct()
		{
			// register actions
            add_action('admin_menu', array(&$this, 'admin_init'));
            add_action( 'admin_menu', array( $this, 'go_welcome' ) );
            add_action( 'chronosly-addon-head', array( $this, 'chronosly_addon_head' ) );
            add_action( 'chronosly-addon-foot', array( $this, 'chronosly_addon_foot' ) );

            //add_action('admin_menu', array(&$this, 'add_menu'));
            add_action( 'admin_enqueue_scripts', array(&$this,'admin_template') );
            add_action( 'wp_ajax_chronosly_clean_old_templates_on_events', array(&$this,'clean_old_templates_on_events') );
			add_action( 'wp_ajax_chronosly_change_folder_permissions', array(&$this,'change_folder_permissions') );

		} // END public function __construct

        /**
         * hook into WP's admin_init action hook
         */
        public function admin_init()
        {
        	// register your plugin's settings
        	register_setting('chronosly-group', 'chronosly-settings');
        	if(!get_option("chronosly-settings")){
				$settings = array(
                    //urls config
					"chronosly-slug" => "events",
                    "chronosly-history-slug" => "events",
                    "chronosly-organizer-slug" => "organizers",
                    "chronosly-organizer-history-slug" => "organizers",
                    "chronosly-place-slug" => "places",
                    "chronosly-place-history-slug" => "places",
                    "chronosly-calendar-slug" => "calendar",
                    "chronosly-calendar-history-slug" => "calendar",
                    "chronosly-category-slug" => "event_categories",
                    "chronosly-category-history-slug" => "event_categories",
                    "chronosly-tag-slug" => "event_tags",
                    "chronosly-tag-history-slug" => "event_tags",
                    "chronosly-event-list-url" => "",
                    "chronosly-organazires-list-url" => "",
                    "chronosly-places-list-url" => "",
                    "chronosly-categories-list-url" => "",
                    "chronosly-calendar-url" => "",
                     "chronosly-event-list-title" => "Events list",
                    "chronosly-organizers-list-title" => "Organizers list",
                    "chronosly-places-list-title" => "Places list",
                    "chronosly-categories-list-title" => "Category list",

                    //templates config
                    "chronosly_tipo_perfil" => "1",
                    "chronosly_template_default" => "default",
                    "chronosly_template_default_active" => "",
                    "chronosly_calendar_template_default" => "default",
                    "chronosly_titles_template_default" => "default",
                    "chronosly_category_color" => "#1BBC9D",
                    "chronosly_sale_color" => "#ff9711",
                    "chronosly_font_color" => "#fff",
                    "chronosly_font_family" => "Arial",
                    "chronosly_font_size" => "14",
                    "chronosly_background_color" => "#fff",
                    "chronosly_background_round" => "15",
                    "chronosly_padding" => "10",
                    "chronosly_margin" => "10",
                    "chronosly_box_background_color" => "#fff",
                    "chronosly_box_background_round" => "15",
                    "chronosly_box_border_color" => "#fff",
                    "chronosly_box_border_size" => "2",
                    "chronosly_box_border_style" => "solid",
                    "chronosly_box_padding" => "10",
                    "chronosly_box_margin" => "10",
                    "chronosly_events_order" => "name",
                    "chronosly_events_orderdir" => "ASC",
                    "chronosly_category_order" => "name",
                    "chronosly_category_orderdir" => "ASC",
                    "chronosly_organizers_order" => "name",
                    "chronosly_organizers_orderdir" => "ASC",
                    "chronosly_places_order" => "name",
                    "chronosly_places_orderdir" => "ASC",
                    "chronosly_format_date_time" => "d-m-y H:i",
                    "chronosly_format_time" => " H:i",
                    "chronosly_format_date" => "d-m-y",
                    "chronosly_full_datetime_separator" => "to",
                    "chronosly_currency" => "&#x20AC;",
                    "chronosly_template_max" => "1000",
                    "chronosly_template_min" => "",
                    "chronosly_dad_event_title_link" => "1",
                    "chronosly_dad_organizer_title_link" => "1",
                    "chronosly_dad_place_title_link" => "1",
                    "chronosly_dad_category_title_link" => "1",
                    "chronosly_dad_tag_title_link" => "1",
                    "chronosly_dad_link_action" => "1",
                    "chronosly_dad_link_new_window" => "1",
                    "chronosly_dad_link_nofollow" => "0",
                    "chronosly_dad_readmore" => "Change me",
                    "chronosly_dad_buy_tiket" => "Buy",
                    "chronosly_dad_cat_separator" => ", ",
                    "chronosly_dad_tag_separator" => ", ",
                   // "chronosly_dad_img_width" => "40%",
                    //"chronosly_dad_gallery_box" => "Change me",
                    //"chronosly_dad_tikets_box" => "Change me",
                    "chronosly_dad_gmap_zoom" => "16",
                    "chronosly_dad_show_load_template" => "1",
                   // "chronosly_dad_show_save_template" => "1",
                    "chronosly_dad_show_load_view" => "1",
                   /* "chronosly_paint_show_vars" => "1",
                    "chronosly_paint_show_text" => "1",
                    "chronosly_paint_show_back" => "1",
                    "chronosly_paint_show_space" => "1",
                    "chronosly_paint_show_border" => "1",
                    "chronosly_paint_show_custom" => "1",
                    "chronosly_paint_show_custom_all" => "1",*/
                    "chronosly_show_past_events" => "0",
                    //"chronosly_show_filters_on_events" => "1",
                    //"chronosly_show_filters_on_categories" => "1",
                    //"chronosly_show_filters_on_tags" => "1",
                   // "chronosly_show_filters_on_organizers" => "1",
                   // "chronosly_show_filters_on_places" => "1",
                   // "chronosly_show_filters_on_calendar" => "1",
                   // "chronosly_show_help" => "1",
                    "chronosly_featured_first" => "1",
                    "chronosly_week_start" => "2",
                    "chronosly_core_autoupdate" => "0",
                    "chronosly_addons_autoupdate" => "0",
                    "chronosly_templates_autoupdate" => "0",
                    "chronosly_license" => "",
                    "chronosly_tickets" => 1,
                    "chronosly_template_editor" => 1,
                    "chronosly_organizers" => 1,
                    "chronosly_places" => 1,
                    "chronosly_organizers_addon" => 1,
                    "chronosly_places_addon" => 1,
                    "chronosly_list_events_select" => 1,
                    "chronosly_list_events_start" => "",
                    "chronosly_list_events_end" => "",
                    "chronosly_event_list_format" => "year",
                    "chronosly_event_list_time" => "",
                    "chronosly_events_x_page" => "15",
                    "chronosly_organizers_x_page" => "10",
                    "chronosly_places_x_page" => "10",
                    "chronosly-allow-flush" => 1,
                    "chronosly-show-repeats-organizer" => 1,
                    "chronosly_organizers_events_range" => "year",
                    "chronosly-show-repeats-place" => 1,
                    "chronosly_places_events_range" => "year",
                    "chronosly-base-templates-id" => 0,
                    "chronosly-events-base-templates-id" => 0,
                    "chronosly-organizers-base-templates-id" => 0,
                    "chronosly-places-base-templates-id" => 0,
                    "chronosly-calendar-base-templates-id" => 0,
                    "chronosly-category-templates-id" => 0,
                    "chronosly-events-single-base-templates-id" => 0,
                    "chronosly-organizers-single-base-templates-id" => 0,
                    "chronosly-places-single-base-templates-id" => 0,
                    "chronosly-category-single-templates-id" => 0,
                    "chronosly-disable-gmap-js" => 0,
                    "chronosly-disable-custom-scroll-js" => 0,
                    "chronosly_gmap_api" => "AIzaSyCoJ1LTZYbEDsrplwSf7b_sj3k1-bZ6sAk",
                    "jquery-admin-disable" => 0,
                    "disable_cache" => 0,
                    "hide_past_on_calendar" => 0,
                    "disable_slide_on_show" => 0,
                    "chronosly-events-flushed" => 0,
                    "chronosly-organizers-flushed" => 0,
                    "chronosly-places-flushed" => 0,
                    "chronosly-calendar-flushed" => 0,
                    "chronosly-cats-flushed" => 0,
                    "chronosly-tags-flushed" => 0,
                    "chronosly_admin_memory_limit" => 0,
                    "chronosly-display-ogmetas" => 0,
                    "chronosly_sell_tikets" => 0,
                    "chronosly_hide_navigation_title" => 0,
                    "chronosly_hide_navigation_calendar" => 0,
                    "chronosly_hide_navigation_calendar_left" => 0,
                    "chronosly_hide_navigation_calendar_right" => 0,
                    "disable_slide_motion" => 0,
                    "disable_the_content" => 0,
                    "show_calendar_by" => "year",


				);
				update_option('chronosly-settings', serialize($settings));
            } else{

                $settings = unserialize(get_option("chronosly-settings"));
                if(!isset( $settings["chronosly-event-list-title"])) $settings["chronosly-event-list-title"] = "Events list";
                if(!isset( $settings["chronosly-organizers-list-title"])) $settings["chronosly-organizers-list-title"] = "Organizers list";
                if(!isset( $settings["chronosly-places-list-title"])) $settings["chronosly-places-list-title"] = "Places list";
                if(!isset( $settings["chronosly-categories-list-title"])) $settings["chronosly-categories-list-title"] = "Category list";
                if(!isset( $settings["show_calendar_by"])) $settings["show_calendar_by"] = "year";
                if(!isset( $settings["chronosly_category_order"])) {
                    $settings["chronosly_category_order"] = "name";
                    $settings["chronosly_category_orderdir"] = "ASC";
                    $settings["chronosly_organizers_order"] = "name";
                    $settings["chronosly_organizers_orderdir"] = "ASC";
                    $settings["chronosly_places_order"] = "name";
                    $settings["chronosly_places_orderdir"] = "ASC";
                }
                if(!isset( $settings["chronosly_organizers_addon"])) $settings["chronosly_organizers_addon"] = 1;
                if(!isset( $settings["chronosly_places_addon"])) $settings["chronosly_places_addon"] = 1;
                if(!isset( $settings["chronosly_sale_color"])) $settings["chronosly_sale_color"] = "#ff9711";
                if(!isset( $settings["chronosly_gmap_api"])) $settings["chronosly_gmap_api"] = "AIzaSyBBNKHpoeMaA0okUsvrYjRWrni2-bktAEM";
                if(file_exists(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."post-types".DIRECTORY_SEPARATOR."post_type_chronosly_organizer.php")){
                     $settings["chronosly_organizers_addon"] =  $settings["chronosly_places_addon"] = 1;
                }

                update_option('chronosly-settings', serialize($settings));
            }
            //add settings menus
            $configs = array();
            $this->settings_menu = apply_filters("chronosly_config_page_menu_item", $configs);
            //add addons settings menus
            $addons = array();
            $this->addons_settings = apply_filters("chronosly_addons_settings_item", $addons);
            $addons = array();
            $this->addons_menu = apply_filters("chronosly_addons_settings_menu_item", $addons);

            $this->add_menu();

        } // END public static function activate





        /* return an array counting the addons that needs update */
        public function get_addons_need_update(){
            $update = 0;
            $addon = array();
            foreach($this->addons_settings as $k){
                $class = new $k;
                if(isset($class->settings) and is_array($class->settings)){$sets = $class->settings;}
                else {$class->addon_settings(1);$sets = $class->settings;}
               // print_r($sets);
                if(floatval($sets["needed_version"]) > floatval($sets["version"])){
                    $update++;
                    $addon[$class->id] = $class->name;
                }
            }
            return array("count"=>$update, "names"=>$addon);
        }

        /**
         * add a menu
         */
        public function add_menu()
        {
            global $settings_page_hook_suffix, $profile_page_hook_suffix, $template_edit_page_hook_suffix, $template_status_page_hook_suffix,
                   $addons_config_page_hook_suffix,$status_page_hook_suffix,$lang_page_hook_suffix,$support_page_hook_suffix;
            // Add a page to manage this plugin's settings

            $updates_count = $this->get_addons_need_update();
          //print_r($updates_count);
            $updates_count = $updates_count["count"];
            $settings_page_hook_suffix =   add_menu_page(
        	    'Chronosly Settings',
        	    'Chronosly'.' <span class="update-plugins count-'.$updates_count.'"><span class="plugin-count">'.$updates_count.'</span></span>',
        	    'manage_options',
        	    'chronosly',
        	    array(&$this, 'plugin_settings_page'),
                CHRONOSLY_URL."css/img/menu-ico.png"
        	);

            $settings_page_hook_suffix =   add_submenu_page(
                'chronosly',
        	    'Chronosly Settings',
                __('Settings',"chronosly"),
                'manage_options',
        	    'chronosly',
        	    array(&$this, 'plugin_settings_page')
        	);

            $profile_page_hook_suffix =  add_submenu_page(
                'chronosly',
        	    'Chronosly Settings',
        	    __('Change profile',"chronosly"),
        	    'manage_options',
        	    'chronosly_profile',
        	    array(&$this, 'plugin_welcome_page')
        	);

            $template_edit_page_hook_suffix =  add_submenu_page(
                'chronosly',
        	    'Chronosly Settings',
        	    __('Edit Templates',"chronosly"),
        	    'manage_options',
        	    'chronosly_edit_templates',
        	    array(&$this, 'template_edit_page')
        	);
            $template_status_page_hook_suffix =  add_submenu_page(
                'chronosly',
        	    'Chronosly Settings',
        	    __('Templates status',"chronosly"),
        	    'manage_options',
        	    'chronosly_templates_status',
        	    array(&$this, 'templates_status')
        	);
            $addons_config_page_hook_suffix =  add_submenu_page(
                'chronosly',
        	    'Chronosly Settings',
        	    __('Addons settings',"chronosly").' <span class="update-plugins count-'.$updates_count.'"><span class="plugin-count">'.$updates_count.'</span></span>',
        	    'manage_options',
        	    'chronosly_addons_configs',
        	    array(&$this, 'addons_settings_page')
        	);


            $support_page_hook_suffix =  add_submenu_page(
                'chronosly',
        	    'Chronosly Settings',
        	    __('Support',"chronosly"),
        	    'manage_options',
        	    'chronosly_support',
        	    array(&$this, 'plugin_support_page')
        	);

        } // END public function add_menu()

        public function go_welcome(){
            if ( ! get_transient( '_chronosly_welcome' )  )
                return;

            // Delete the redirect transient
            delete_transient( '_chronosly_welcome' );
            wp_safe_redirect( admin_url( 'admin.php?page=chronosly_profile' ) );
            exit;
        }

        /**
         * Menu Callback
         */
        public function plugin_settings_page()
        {
            global $Post_Type_Chronosly;

            if(!current_user_can('manage_options'))
        	{
        		wp_die(__('You do not have sufficient permissions to access this page.'));
        	}
            //colorpicker

            wp_register_script( 'chronosly-spectrum', CHRONOSLY_URL.'js/spectrum/spectrum.js', array( 'jquery' ));
            wp_enqueue_script('chronosly-spectrum');
            wp_register_style( 'chronosly-spectrum-css', CHRONOSLY_URL.'js/spectrum/spectrum.css');
            wp_enqueue_style('chronosly-spectrum-css');


            if(isset($_POST['chronosly_nonce'])) {
                //save vars
                if ( wp_verify_nonce( $_POST['chronosly_nonce'], "chronosly_save_settings" ) ){
                    Chronosly_Cache::clear_cache();
                    $vars = array();
                    foreach($_POST as $pf=>$pv){
                        if(stripos($pf, "history-slug") !== FALSE){
                            $prev = str_replace("history-", "", $pf);
                            $hist = explode(",", $pv);
                            //save a history of slugs to make 301 redirects
                            if($vars[$prev] and !in_array($vars[$prev], $hist)) $vars[$pf] = $pv.",".$vars[$prev];
                            else  $vars[$pf] = $pv;
                        }
                        else $vars[$pf] = $pv;
                    }
                    update_option('chronosly-settings', serialize($vars));


                } else {
                    die( __( 'Action failed. Please refresh the page and retry.', 'chronosly' ) );
                }

            }
            else if(isset($_REQUEST["update_core"])){
                if( !current_user_can('manage_options'))
                {
                    wp_die(__('You do not have sufficient permissions to access this page.'));
                }
                $ext = new Chronosly_Extend;
                echo $ext->update_core(1);
                Chronosly_Cache::clear_cache();

            } else if(isset($_REQUEST["create_base"])){

                if( !current_user_can('manage_options'))
                {
                    wp_die(__('You do not have sufficient permissions to access this page.'));
                }
                                    Chronosly_Cache::clear_cache();

                $settings = unserialize(get_option('chronosly-settings'));

                if(!$settings["chronosly-base-templates-id"]){
                    $args = array(
                        "post_title" => "Events base",
                        'post_status'      => 'publish',
                        "post_type" => 'page',
                        "post_content" => '[chronoslybase]',
                        "post_parent"  => 0,
                    );

                    $settings["chronosly-base-templates-id"] = wp_insert_post ($args);
                    update_option('chronosly-settings', serialize($settings));
                    echo  "<div class='bubblegreen'>The Chronosly base has been created.</div>";
                } else {
                    echo  "<div class='bubblegreen'>The Chronosly base is already created.</div>";
                }


        } else if(isset($_REQUEST["delete_base"])){
            if( !current_user_can('manage_options'))
            {
            wp_die(__('You do not have sufficient permissions to access this page.'));
            }
                                Chronosly_Cache::clear_cache();

            $settings = unserialize(get_option('chronosly-settings'));

            if($settings["chronosly-base-templates-id"]){
                wp_delete_post($settings["chronosly-base-templates-id"]);

                $settings["chronosly-base-templates-id"] = 0;
                update_option('chronosly-settings', serialize($settings));
                echo  "<div class='bubblegreen'>The Chronosly base has been removed.</div>";
            } else {
                echo  "<div class='bubblegreen'>The Chronosly base is already removed.</div>";
            }
         } else if(isset($_REQUEST["wc_create_all"])){
            $settings = unserialize(get_option('chronosly-settings'));
            if(!$settings["chronosly_sell_tikets"]) {
                echo  "<div class='bubbleerror'>Sell WooCommerce Tickets must be enabled</div>";
            }
            else if(!class_exists( 'WooCommerce' )) echo  "<div class='bubbleerror'>Woocommerce plugin is required</div>";
            else if($this->create_wc_products()){
                echo  "<div class='bubblegreen'>Woocommerce tickets created</div>";
            } else echo  "<div class='bubbleerror'>Problems creating Woocommerce tickets</div>";
         }

            flush_rewrite_rules();
            $vars = unserialize(get_option("chronosly-settings"));

            $this->print_settings_menu();
            $vars = unserialize(get_option("chronosly-settings"));
            $templates_options = $Post_Type_Chronosly->template->get_templates_options(0, $vars["chronosly_template_default"]);
            $templates_calendar_options = $Post_Type_Chronosly->template->get_templates_options(0, $vars["chronosly_calendar_template_default"]);
            $templates_titles_options = $Post_Type_Chronosly->template->get_templates_options(0, $vars["chronosly_titles_template_default"]);
            $currency = $Post_Type_Chronosly->template->currency_selector($vars['chronosly_currency']);
            $status = $this->get_core_status();
            $templates_licenses = $this->get_template_licenses();
             $foldersPermissions = $this->get_folder_permissions();
        	// Render the settings template
        	include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."settings.php");
        }

        public function get_template_licenses(){
            global $Post_Type_Chronosly;
            $ret = "";
            $m_templates = $Post_Type_Chronosly->template->load_template_settings($Post_Type_Chronosly->template->get_templates_options(1), 1);
            if(!count($m_templates)) return "";
            $sets = unserialize(get_option("chronosly-settings"));
            foreach($m_templates as $t=>$cont){
                // print_r($cont);
                if($t != "default") $ret .= "<label>".$t." ".__("license", "chronosly")."</label><input type='text' name='chronosly-settings_templates_license_$t' value='".$sets["chronosly-settings_templates_license_$t"]."' /><br/>";

            }
            return $ret;
        }



        public function print_settings_menu(){
            echo '<div style="clear:both;margin-top:20px;"></div>';
            echo "<div class='settings-menu'>";
            foreach($this->settings_menu as $k=>$v){
                echo "<a class='set-menu' href='admin.php?page=$k".__($v, "chronosly")."</a>";
            }
            echo "</div>";
        }

        public function addons_settings_page(){
            echo "<div style='clear:both;margin-top:20px;'></div>";
            $this->print_addons_menu();
            include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."addons-settings.php");

        }

        public function print_addons_menu(){
            global $Post_Type_Chronosly;

            $Post_Type_Chronosly->inicia_scripts();
            echo "<div class='addons-menu'>";
            $current = "";
            if(isset($_REQUEST['page']) and  "chronosly_addons_configs" == $_REQUEST['page']) $current =" current";
            echo "<a class='set-menu$current' href='admin.php?page=chronosly_addons_configs' >".__("Main page", "chronosly")."</a>";
            foreach($this->addons_menu as $k=>$v){
                $current = "";
                if(isset($_REQUEST['page']) and $k == $_REQUEST['page']) $current =" current";
                echo "<a class='set-menu$current' href='admin.php?page=$k' >".__($v, "chronosly")."</a>";
            }
            echo "</div>";
        }

        public function print_addons_main_page(){


            echo "<div class='addons-main-page'>";

            foreach($this->addons_settings as $k){
                $class = new $k;
                if(isset($class->settings) and is_array($class->settings)){$sets = $class->settings;}
                else {$class->addon_settings(1);$sets = $class->settings;}
                //print_r($class->settings);
                if(floatval($sets["needed_version"]) > floatval($sets["version"])) $update = 1;
                echo "<div class='addon{$class->id} addon";
                if($update) echo " needupdate";
                if(isset($class->settings_url)) $sets_url = "href='admin.php?page=$class->settings_url'";
                echo "'>
                            <a {$sets_url}><div class='icon'></div></a>
                            <div class='title'><a {$sets_url}>{$class->name}</a></div>
                            <div class='description'><a {$sets_url}>{$class->description}</a></div>
                            <div class='version'><p>".__("Version", "chronosly")." {$sets["version"]}</p>";
                                 if($update) echo "<a href='admin.php?page=chronosly_addons_configs&update_addon=1&addon={$class->id}' class='update'>".__("required update to", "chronosly")." {$sets["needed_version"]}</a>";
                                 if($class->id != "organizers_and_places") echo "<a href='admin.php?page=chronosly_addons_configs&delete={$class->id}' class='update'>".__("Delete", "chronosly")."</a>";
                            echo "</div>

                </div>";
            }
            echo "</div>";
        }

        public function chronosly_addon_head($addon){

            echo '<div style="clear:both;margin-top:20px;"></div>';

            $this->print_addons_menu();

            echo '<div class="wrapch right">';
            if(!current_user_can('manage_options'))
            {
                wp_die(__('You do not have sufficient permissions to access this page.'));
            }

            if(isset($_POST['chronosly_nonce'])) {
                //uploading templates

                if ( wp_verify_nonce( $_POST['chronosly_nonce'], "chronosly_addon_save_settings" )){
                    Chronosly_Cache::clear_cache();
                    $vars2 = unserialize(get_option('chronosly_settings_'.$addon));
                        $vars = array();
                        foreach($_POST as $pf=>$pv){
                           if(is_array($pv)) $vars[$pf] = serialize($pv);
                           else $vars[$pf] = $pv;
                        }
                        //ponemos los parametros que no tiene el form
                        $vars["version"] = $vars2["version"];
                        $vars["needed_version"] = $vars2["needed_version"];
                        $vars["templates_auto_updated"] = $vars2["templates_auto_updated"];
                        update_option('chronosly_settings_'.$addon, serialize($vars));


                }
            }


              echo '<form method="post" action="" enctype="multipart/form-data">';
                wp_nonce_field( "chronosly_addon_save_settings", 'chronosly_nonce' );
        }

        public function chronosly_addon_foot($addon=null){
            echo '<br/><input class="submit" type="submit" value="'.__("Save", "chronosly").'" />';
            echo "</form></div>";
        }

        public function print_addons_status(){
            $ex = new Chronosly_Extend;
            $addons = $ex->get_addons_feed();

            echo "<div class='version'>";
            if(is_array($addons) or is_object($addons)){
                foreach($addons as $ad){
                    $c = $this->addons_settings[$ad->id];
                    if(class_exists($c)) $class = new $c;
                    else continue;
                    if(isset($class->settings) and is_array($class->settings)){$sets = $class->settings;}
                    else {$class->addon_settings(1);$sets = $class->settings;}
                    // echo $ad->version;
                    if($ad->version != $sets["version"]){
                        echo "<a class='update' href='admin.php?page=chronosly_addons_configs&update_addon=1&addon={$class->id}'><b>{$class->name}</b> ".__("newer version", "chronosly")." ".$ad->version."</a><br/>";
                    }



                }
            }
            echo "</div>";
        }

        public function plugin_welcome_page()
        {
        	if(!current_user_can('manage_options'))
        	{
        		wp_die(__('You do not have sufficient permissions to access this page.'));
        	}

        	// Render the settings template
            include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."welcome.php");
        }


        public function langs_page()
        {
        	if(!current_user_can('manage_options'))
        	{
        		wp_die(__('You do not have sufficient permissions to access this page.'));
        	}

        	// Render the settings template
            include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."langs.php");
        }

        public function template_edit_page()
        {
            global $Post_Type_Chronosly;
        	if(!current_user_can('manage_options'))
        	{
        		wp_die(__('You do not have sufficient permissions to access this page.'));
        	}

            if(isset($_POST['chronosly_nonce'])) {
                //uploading templates

                if ( wp_verify_nonce( $_POST['chronosly_nonce'], "chronosly_addons_upload" )){

                    if(!empty($_FILES['chronosly_addon']['name'])) {
                        Chronosly_Cache::clear_cache();
                        //print_r($_FILES['chronosly_addon']);
                        // Setup the array of supported file types. In this case, it's just PDF.
                        $supported_types = array('application/zip',"multipart/x-zip", "application/octet-stream");

                        // Get the file type of the upload
                        $arr_file_type = wp_check_filetype(basename($_FILES['chronosly_addon']['name']));
                        $uploaded_type = $arr_file_type['type'];

                        // Check if the type is supported. If not, throw an error.
                        if(in_array($uploaded_type, $supported_types)) {

                            // Use the WordPress API to upload the file
                            $upload = wp_upload_bits($_FILES['chronosly_addon']['name'], null, file_get_contents($_FILES['chronosly_addon']['tmp_name']));

                            if(isset($upload['error']) && $upload['error'] != 0) {
                                echo '<div class="bubbleerror">'.__(sprintf('There was an error uploading your file. The error is: %s' , "chronosly"), $upload['error'])."</div>";
                            } else {
                                WP_Filesystem();
                                $destination_path = CHRONOSLY_TEMPLATES_PATH;
                                $upload['file'] = str_replace(array("/", "\\"), DIRECTORY_SEPARATOR, $upload['file']);
                                $unzipfile = unzip_file( $upload['file'], $destination_path);
                                unlink( $upload['file'] );
                                if ( $unzipfile ) {
                                    $names = explode(DIRECTORY_SEPARATOR,  $upload['file']);
                                    $name = str_replace(".zip", "",$names[count($names)-1]);
                                    //volvemos a construir los addons
                                    Chronosly_Extend::rebuild_template_addons( $name);
                                    wp_redirect("admin.php?page=chronosly_edit_templates&installed=$name");

                                } else {
                                   echo '<div class="bubbleerror">'.__("There was an error installing this template.", "chronosly");
                                    if($unzipfile->errors["mkdir_failed_pclzip"]) echo "<br/>".__("Chronosly couldn't create folder, check permissions on chronosly/custom-templates/ folder", "chronosly");
                                    echo "</div>";
                                }
                            }

                        } else {
                            echo '<div class="bubbleerror">'.__("The file type that you've uploaded is not a Chronosly Template ZIP.", "chronosly")."</div>";
                        } // end if/else

                    } // end if


                }
            }

            $Post_Type_Chronosly->inicia_scripts();
            $vistas = array(
                "dad1" => __("All events list view", "chronosly"),
                "dad2" => __("Single event view", "chronosly"),
                "dad3" => __("Calendar view", "chronosly"),
                "dad4" => __("Category events list view", "chronosly"),
                "dad5" => __("Organizer events list view", "chronosly"),
                "dad6" => __("Place events list view", "chronosly"),
                "dad7" => __("All organizers list view", "chronosly"),
                "dad8" => __("Single organizer view", "chronosly"),
                "dad9" => __("All places list view", "chronosly"),
                "dad10" => __("Single place view", "chronosly"),
                "dad11" => __("All categories list view", "chronosly"),
                "dad12" => __("Single category view", "chronosly"),
           /*     "dad13" =>__("Calendar year","chronosly" ),
                "dad14" =>__("Calendar month","chronosly" ),
                "dad15" =>__("Calendar week","chronosly" ),*/
            );

            $query = new WP_Query('post_type=chronosly&posts_per_page=1');
            if($query->have_posts() ){
                 $query->the_post();
                $pid = get_the_ID();
              }
            $settings = unserialize(get_option("chronosly-settings"));
            /* for addons updating code */
            $views= "";
            if(isset($_REQUEST["viewstoedit"])) $views = explode("|", $_REQUEST["viewstoedit"]);
            if(isset($_REQUEST["addon"]) and $_REQUEST["autoupdate"]){
                //update all templates

                if($Post_Type_Chronosly->template->full_update_templates_by_addon($_REQUEST["addon"], $views)){

                    $mensage = "<div class='bubblegreen'>".__("Your templates are now updated to use the addon, but you have to manualy edit all templates that you have updated inside an event edit page", "chronosly")."</div><br/>";


                }


            }

            $templates_options = $Post_Type_Chronosly->template->get_templates_options(0, $settings['chronosly_template_default']);
            // Render the settings template
            $print = 1;
            include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."template-editor.php");
            $style= "back";
            if(isset($_REQUEST['addon'])) $style = "back-addon";//not loading the dad elements when whe are editing a addon templates
            $Post_Type_Chronosly->template->print_template("", "dad1", "", "", $style );
            $print = 2;
            include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."template-editor.php");

        }



        public function get_core_status(){
            //global $Chronosly_curl;
            //$actual_version = $Chronosly_curl->get_url("core_version");
            $actual_version = CHRONOSLY_VERSION;
            $extend = new Chronosly_Extend();
            $cont = $extend->get_external_content($extend->core_update_url."?key=status","json");
            if(!$cont["error"]) $actual_version = $cont["content"]->version;
            if(CHRONOSLY_VERSION == $actual_version){
                return "<div class='version'><div class='frase'>".__("You have the latest version of Chronosly", "chronosly")."</div><span class='ok'>".__("Current Version","chronosly")." ".$actual_version."</span></div>";
            } else {
                return "<div class='version'><div class='frase'>".__("You have an older version of Chronosly, update it for get the latests features.", "chronosly")."</div><a href='admin.php?page=chronosly&update_core=1#tabs-5' class='update'>".__("UPDATE", "chronosly")." ".CHRONOSLY_VERSION." ".__("to", "chronosly")." ".$actual_version."</a></div>";

            }
        }

            public function templates_status(){
            global $Post_Type_Chronosly;
            if(!current_user_can('manage_options'))
            {
                wp_die(__('You do not have sufficient permissions to access this page.'));
            }

            wp_register_script( 'chronosly_js_setting', CHRONOSLY_URL .'/js/settings_page.js', array( 'jquery' ), '1.0.0' );
            wp_enqueue_script( 'chronosly_js_setting' );


            wp_register_script( 'chronosly_js_chart', CHRONOSLY_URL .'/js/chartjs/Chart.js', array( 'jquery' ), '1.0.0' );
            wp_enqueue_script( 'chronosly_js_chart' );
            wp_register_script( 'chronosly_js_chart_legend', CHRONOSLY_URL .'/js/chartjs/legend/src/legend.js', array( 'jquery' ), '1.0.0' );
            wp_enqueue_script( 'chronosly_js_chart_legend' );
            wp_register_script( 'chronosly-spectrum', CHRONOSLY_URL.'js/spectrum/spectrum.js', array( 'jquery' ));
            wp_enqueue_script('chronosly-spectrum');
            wp_register_style( 'chronosly-spectrum-css', CHRONOSLY_URL.'js/spectrum/spectrum.css');
            wp_enqueue_style('chronosly-spectrum-css');

            wp_register_style( 'chronosly-custom_wp_admin_css', CHRONOSLY_URL .'/css/admin_template1.css', false, '1.0.0' );
            wp_enqueue_style( 'chronosly-custom_wp_admin_css' );
            $status = $Post_Type_Chronosly->template->template_status();
            $print_status =  json_encode($this->print_templates_status($status));
            $translation_array	= array(
                "templates_items" => $print_status,
                "without" => __("Without","chronosly"),
                "category" => __("Category","chronosly"),
                "organizer" => __("Organizer","chronosly"),
                "place" => __("Place","chronosly"),
                "event" => __("Event","chronosly"),
                "template" => __("Template","chronosly"),
                "dad1" => __("All events list view", "chronosly"),
                "dad2" => __("Single event view", "chronosly"),
                "dad3" => __("Calendar view", "chronosly"),
                "dad4" => __("Category events list view", "chronosly"),
                "dad5" => __("Organizer events list view", "chronosly"),
                "dad6" => __("Place events list view", "chronosly"),
                "dad7" => __("All organizers list view", "chronosly"),
                "dad8" => __("Single organizer view", "chronosly"),
                "dad9" => __("All places list view", "chronosly"),
                "dad10" => __("Single place view", "chronosly"),
                "dad11" => __("All categories list view", "chronosly"),
                "dad12" => __("Single category view", "chronosly"),
                "bd_template" => __("Individualy edited","chronosly"),
                "title_chart" => __("Chart representation of template usage","chronosly"),
            );
            wp_localize_script( 'chronosly_js_setting', 'translated', $translation_array );
            include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."templates-status.php");

        }

        public function plugin_support_page(){
            if(!current_user_can('manage_options'))
            {
                wp_die(__('You do not have sufficient permissions to access this page.'));
            }

            // Render the settings template
            include(CHRONOSLY_PATH.DIRECTORY_SEPARATOR."metaboxes".DIRECTORY_SEPARATOR."settings".DIRECTORY_SEPARATOR."support.php");
        }

          public function print_templates_status($status=null){
            $ret = array();
             $sets = unserialize(get_option("chronosly-settings"));
            $dads = array("dad1","dad2","dad3","dad4","dad5","dad6","dad7","dad8","dad9","dad10","dad11","dad12");
            if(!isset($status)) return;
            foreach($status as $id=>$ev){
                $return = array();
                if(isset($ev["ev-to"])) $data = $ev["ev-to"][0];
                $title = $ev["title"];
                $cat_ids = $cat_names = array();
                if(isset($ev["cats_vars"])){
                    foreach($ev["cats_vars"] as $cat){
                        $cat_ids[] = $cat->term_id;
                        $cat_names[] = $cat->name;

                    }
                }
                $cat_id = @implode("|",$cat_ids);
                $cat_n = @implode("|",$cat_names);
                if(!$cat_id) $cat_id = $cat_n=  "";
                foreach($ev as $k=>$t){
                    if(!$t) continue;
                    if(in_array($k, $dads)){

                        $return[]= array("view"=>$k, "templ"=>$t, "cats"=>$cat_id, "cats-n"=>$cat_n, "id"=>$id, "name"=>$title, "data"=>$data);
                    }
                }

                if(!count($return)){
                    foreach ($dads as $dad) {
                        $return[]= array("view"=>$dad, "templ"=>$sets["chronosly_template_default"], "cats"=>$cat_id, "cats-n"=>$cat_n, "id"=>$id, "name"=>$title, "data"=>$data);

                    }
                }

                $ret= array_merge($ret, $return);

            }
            return $ret;
        }


		public function admin_template($hook=null){
			//load the template acording to mode
            global $settings_page_hook_suffix, $profile_page_hook_suffix, $template_edit_page_hook_suffix, $template_status_page_hook_suffix,
                   $addons_config_page_hook_suffix,$status_page_hook_suffix,$lang_page_hook_suffix,$support_page_hook_suffix;
            if( $hook != $settings_page_hook_suffix and $hook != $profile_page_hook_suffix and $hook != $support_page_hook_suffix) return;


            $settings = unserialize(get_option("chronosly-settings"));

            wp_register_style( 'chronosly-custom_wp_admin_css', CHRONOSLY_URL .'/css/admin_template1.css', false, '1.0.0' );
			wp_enqueue_style( 'chronosly-custom_wp_admin_css' );


            wp_enqueue_script('jquery-ui-core');
            wp_enqueue_script( 'jquery-ui-datepicker');

            wp_enqueue_script('jquery-ui-tabs');
            wp_enqueue_script('jquery-ui-tooltip');
            wp_enqueue_script('jquery-ui-resizable');
            wp_enqueue_script('jquery-ui-draggable');


            wp_register_style( 'chronosly-admin-jquery-ui-css', CHRONOSLY_URL.'css/smoothness/jquery-ui-1.10.4.custom.css');
            wp_enqueue_style('chronosly-admin-jquery-ui-css');
            //colorpicker
            wp_register_script( 'chronosly-spectrum', CHRONOSLY_URL.'js/spectrum/spectrum.js', array( 'jquery' ));
            wp_enqueue_script('chronosly-spectrum');
            wp_register_style( 'chronosly-spectrum-css', CHRONOSLY_URL.'js/spectrum/spectrum.css');
            wp_enqueue_style('chronosly-spectrum-css');


            wp_register_script( 'chronosly_js_setting', CHRONOSLY_URL .'/js/settings_page.js', array( 'jquery' ), '1.0.0' );
			wp_enqueue_script( 'chronosly_js_setting' );

             wp_register_script( 'chronosly-admin', CHRONOSLY_URL.'js/admin.js', array( 'jquery' ));
            $translation_array  = array(
                "days" => __("days", "chronosly"),
                "weeks" => __("weeks", "chronosly"),
                "months" => __("months", "chronosly"),
                "year" => __("year", "chronosly"),
                "color_cancel" => __("Cancel", "chronosly"),
                "color_choose" => __("Choose", "chronosly"),
                "stop_prev" => __("Slower preview", "chronosly"),
                "start_prev" => __("Faster preview", "chronosly"),
                "overwritted" => __("overwritted", "chronosly"),
                "specify_name" => __("You have to specify a name or select a template to update", "chronosly"),
                "wrong_name" => __("The name have incorrect characters, only are alowed chars between a-z,A-Z,0-9 and - or _", "chronosly"),
                "succes" => __("Saved successfully", "chronosly"),
                "duplicate_succes" => __("Cloned successfully", "chronosly"),
                "save_url" => CHRONOSLY_URL."ev-functions/save_template.php",
                "guardamos" => $settings["chronosly_template_default"],
                'ajaxurl' => admin_url( 'admin-ajax.php' )

            );
            wp_localize_script( 'chronosly-admin', 'translated1', $translation_array );

             wp_enqueue_script('chronosly-admin');


        }

         public function create_wc_products(){
            $like = '{"name":"wcid"';
            $args = array(
                'post_type' => "chronosly",
                'meta_query' => array(array("key" => "tickets", "value" => $like, 'compare' => 'NOT LIKE')),
            );

            try{

                $res = new WP_Query($args);
                foreach($res->posts as $r){
                    Post_Type_Chronosly::create_wc_tickets($r->ID, $r);
                }

            }

            catch(Exception $e){

               return 0;

            }
            return 1;
        }

        public function clean_old_templates_on_events(){
            global $wpdb;
                $wpdb->query( 
                $wpdb->prepare( 
                "
                UPDATE ".$wpdb->postmeta." m
                SET m.meta_value = %s 
                WHERE 
                exists(Select p.ID FROM ".$wpdb->posts." p where p.ID = m.post_id AND post_type like %s)
                AND (m.meta_key like %s OR m.meta_key like %s) 
                ",  "", "%chronosly%" ,"dad%", "lang" )
                
            );
            die(__("Templates on events cleared", "chronosly"));

        }

        public function get_folder_permissions(){
            $templates = is_writable(CHRONOSLY_TEMPLATES_PATH);
            $addons = is_writable(CHRONOSLY_ADDONS_PATH);
            if($addons) $ret .= '<label> '.__("Addons folder is writable", "chronosly").'</label><br/>';
            else $ret .= '<label style="color:#DD0000"> '.__("Addons folder is not writable", "chronosly").'</label><br/>';
             if($templates) $ret .= '    <label> '.__("Templates folder is writable", "chronosly").'</label><br/>';
             else   $ret .= ' <label style="color:#DD0000"> '.__("Templates folder is writable", "chronosly").'</label><br/>';
            return $ret;

        }

          public function change_folder_permissions(){
            $templates = chmod(CHRONOSLY_TEMPLATES_PATH, 777);
            $addons = chmod(CHRONOSLY_ADDONS_PATH, 777);
            die($this->get_folder_permissions());

        }

		// END public function plugin_settings_page()



    } // END
} // END


