<?php
/**
 * Creativedog | Timber Theme
 *
 * @package  WordPress
 * @subpackage  Creativedog Timber
 */


/* Plugins */

require_once get_template_directory() . '/inc/class-tgm-plugin-activation.php';

add_action( 'tgmpa_register', 'creativedog_register_required_plugins' );

function creativedog_register_required_plugins() {
	$plugins = array(
		 // This is an example of how to include a plugin from the WordPress Plugin Repository.
		 array(
			 'name'         => 'ACF Pro', // The plugin name.
			 'slug'         => 'advanced-custom-fields-pro', // The plugin slug (typically the folder name).
			 'source'       => 'https://dev.creativedog.agency/wp-plugins/advanced-custom-fields-pro.zip', // The plugin source.
			 'required'     => false, // If false, the plugin is only 'recommended' instead of required.
			 'external_url' => 'https://dev.creativedog.agency/wp-plugins/advanced-custom-fields-pro.zip', // If set, overrides default API URL and points to an external URL.
		 ),
		 array(
			 'name'      => 'CPT UI',
			 'slug'      => 'custom-post-type-ui',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Contact Form 7',
			 'slug'      => 'contact-form-7',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Flamingo',
			 'slug'      => 'flamingo',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Mailchimp - CF7',
			 'slug'      => 'contact-form-7-mailchimp-extension',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Admin Menu Editor',
			 'slug'      => 'admin-menu-editor',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'User Role Editor',
			 'slug'      => 'user-role-editor',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Duplicate Post',
			 'slug'      => 'duplicate-post',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Post Types Order',
			 'slug'      => 'post-types-order',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Woo Commerce',
			 'slug'      => 'woocommerce',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'WC - Mercado Pago',
			 'slug'      => 'woocommerce-mercadopago',
			 'required'  => false,
		 ),
		 array(
			 'name'        => 'Wordpress SEO by Yoast',
			 'slug'        => 'wordpress-seo',
			 'is_callable' => 'wpseo_init',
		 ),
		 array(
			 'name'      => 'Polylang',
			 'slug'      => 'polylang',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'WP Admin No Show',
			 'slug'      => 'wp-admin-no-show',
			 'required'  => false,
		 ),
		 array(
			 'name'      => 'Under Construction',
			 'slug'      => 'under-construction-page',
			 'required'  => false,
		 ),
	);

	$config = array(
		'id'           => 'tgmpa',                 // Unique ID for hashing notices for multiple instances of TGMPA.
		'default_path' => '',                      // Default absolute path to bundled plugins.
		'menu'         => 'tgmpa-install-plugins', // Menu slug.
		'parent_slug'  => 'themes.php',            // Parent menu slug.
		'capability'   => 'edit_theme_options',    // Capability needed to view plugin install page, should be a capability associated with the parent menu used.
		'has_notices'  => true,                    // Show admin notices or not.
		'dismissable'  => true,                    // If false, a user cannot dismiss the nag message.
		'dismiss_msg'  => '',                      // If 'dismissable' is false, this message will be output at top of nag.
		'is_automatic' => false,                   // Automatically activate plugins after installation or not.
		'message'      => '',                      // Message to output right before the plugins table.
	);

	tgmpa( $plugins, $config );
}

if ( ! function_exists( 'creativedog_timber_theme_setup' ) ){
	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 *
	 * Note that this function is hooked into the after_setup_theme hook, which
	 * runs before the init hook. The init hook is too late for some features, such
	 * as indicating support for post thumbnails.
	 */
	function creativedog_timber_theme_setup() {
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 * If you're building a theme based on Creativedog |Timber Theme, use a find and replace
		 * to change 'creativedog_timber_theme' to the name of your theme in all the template files.
		 */
		load_theme_textdomain( 'creativedog_timber_theme', get_template_directory() . '/languages' );

		// Add default posts and comments RSS feed links to head.
		add_theme_support( 'automatic-feed-links' );

		/*
		 * Let WordPress manage the document title.
		 * By adding theme support, we declare that this theme does not use a
		 * hard-coded <title> tag in the document head, and expect WordPress to
		 * provide it for us.
		 */
		add_theme_support( 'title-tag' );

		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 *
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support( 'post-thumbnails' );

		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support( 'html5', array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
		) );

		// Set up the WordPress core custom background feature.
		add_theme_support( 'custom-background', apply_filters( 'creativedog_timber_theme_custom_background_args', array(
			'default-color' => 'ffffff',
			'default-image' => '',
		) ) );

		// Add theme support for selective refresh for widgets.
		add_theme_support( 'customize-selective-refresh-widgets' );

		/**
		 * Add support for core custom logo.
		 *
		 * @link https://codex.wordpress.org/Theme_Logo
		 */
		add_theme_support( 'custom-logo', array(
			'height'      => 250,
			'width'       => 250,
			'flex-width'  => true,
			'flex-height' => true,
		) );
	}

}

add_action( 'after_setup_theme', 'creativedog_timber_theme_setup' );

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function creativedog_timber_theme_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'creativedog_timber_theme_content_width', 640 );
}

add_action( 'after_setup_theme', 'creativedog_timber_theme_content_width', 0 );

/**
 * Enqueue scripts and styles.
 */
function creativedog_timber_theme_scripts() {
  /* CSS */
  wp_enqueue_style( 'creativedog_timber_theme-style', get_stylesheet_uri() );
  wp_enqueue_style( 'creativedog_timber_theme-css', get_template_directory_uri().'/assets/css/app.css' );
  /* JS */
  wp_enqueue_script( 'creativedog_timber_theme-vendor', get_template_directory_uri() . '/assets/js/vendor.js', array('jquery'), '20180313', true );
  wp_enqueue_script( 'creativedog_timber_theme-main', get_template_directory_uri() . '/assets/js/main.js', array('jquery'), '20200722', true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}

add_action( 'wp_enqueue_scripts', 'creativedog_timber_theme_scripts' );

/* Composer */
require_once( __DIR__ . '/vendor/autoload.php' );

/* Implement the Custom Header feature.*/
require get_template_directory() . '/inc/custom-header.php';

/* Custom template tags for this theme. */
require get_template_directory() . '/inc/template-tags.php';

/* Functions which enhance the theme by hooking into WordPress. */
require get_template_directory() . '/inc/template-functions.php';

/* Customizer additions. */
require get_template_directory() . '/inc/customizer.php';

/* Load Jetpack compatibility file. */
if ( defined( 'JETPACK__VERSION' ) ) {
	require get_template_directory() . '/inc/jetpack.php';
}

/* Woocommerce Support */

add_action( 'after_setup_theme', 'woocommerce_support' );

function woocommerce_support() {
  add_theme_support( 'woocommerce' );
}

/* Creativedog Blog Dashboard */

add_action('wp_dashboard_setup', 'my_dashboard_widgets');

function my_dashboard_widgets() {
   global $wp_meta_boxes;
   // quita widgets innecesarios, y principalmente los widgets de noticias, pues ya está el tuyo
   // var_dump( $wp_meta_boxes['dashboard'] ); // se usa para obtener todos los ID de los widgets
   unset(
        $wp_meta_boxes['dashboard']['normal']['core']['dashboard_plugins'],
        $wp_meta_boxes['dashboard']['side']['core']['dashboard_secondary'],
        $wp_meta_boxes['dashboard']['side']['core']['dashboard_primary']
   );
   // añade el widget propio de escritorio
   wp_add_dashboard_widget( 'dashboard_custom_feed', 'Creativedog | Blog', 'dashboard_custom_feed_output' ); //añade una nueva fuente RSS
}

function dashboard_custom_feed_output() {
     echo '<div class="rss-widget">';
     wp_widget_rss_output(array(
          'url' => 'https://creativedog.agency/blog/feed/',
          'title' => 'Creativedog | Blog',
          'items' => 3,
          'show_summary' => 1,
          'show_author' => 0,
          'show_date' => 1
     ));
     echo "</div>";
}

/* Sessions */

session_start();

/* Timber */

$timber = new Timber\Timber();

if ( ! class_exists( 'Timber' ) ) {
	add_action( 'admin_notices', function() {
		echo '<div class="error"><p>Timber not activated. Make sure you activate the plugin in <a href="' . esc_url( admin_url( 'plugins.php#timber' ) ) . '">' . esc_url( admin_url( 'plugins.php' ) ) . '</a></p></div>';
	});

	add_filter('template_include', function( $template ) {
		return get_stylesheet_directory() . '/assests/static/no-timber.html';
	});

	return;
}

/**
 * Sets the directories (inside your theme) to find .twig files
 */
Timber::$dirname = array( 'app/views' );

/**
 * By default, Timber does NOT autoescape values. Want to enable Twig's autoescape?
 * No prob! Just set this value to true
 */
Timber::$autoescape = false;

include("classes/CDTimber.php");

new CDTimber();

/* Set Dynamic Templates */

if( function_exists('acf_add_options_page') ) {
	acf_add_options_sub_page(array(
		'page_title' 	=> 'Templates',
		'menu_title' 	=> 'Templates',
		'parent'     => 'edit.php?post_type=page'
	));
}

if( function_exists('acf_add_local_field_group') ){

	acf_add_local_field_group(array (
		'key' => 'group_5bdc8673ed386',
		'title' => 'Templates',
		'fields' => array (
			array (
				'key' => 'field_5bdc8694aaf55',
				'label' => 'Templates',
				'name' => 'options_templates',
				'type' => 'repeater',
				'value' => NULL,
				'instructions' => '',
				'required' => 0,
				'conditional_logic' => 0,
				'wrapper' => array (
					'width' => '',
					'class' => '',
					'id' => '',
				),
				'collapsed' => '',
				'min' => 0,
				'max' => 0,
				'layout' => 'block',
				'button_label' => 'Add Template',
				'sub_fields' => array (
					array (
						'key' => 'field_5bdc86e5aaf56',
						'label' => 'Name',
						'name' => 'name',
						'type' => 'text',
						'value' => NULL,
						'instructions' => '',
						'required' => 0,
						'conditional_logic' => 0,
						'wrapper' => array (
							'width' => '',
							'class' => '',
							'id' => '',
						),
						'default_value' => '',
						'placeholder' => '',
						'prepend' => '',
						'append' => '',
						'maxlength' => '',
					),
				),
			),
		),
		'location' => array (
			array (
				array (
					'param' => 'options_page',
					'operator' => '==',
					'value' => 'acf-options-templates',
				),
			),
		),
		'menu_order' => 0,
		'position' => 'normal',
		'style' => 'default',
		'label_placement' => 'top',
		'instruction_placement' => 'label',
		'hide_on_screen' => '',
		'active' => 1,
		'description' => '',
	));
}

function cd_get_page_templates() {
  $templates = array();
	if( function_exists('get_field') ){
		$templates_list = get_field('options_templates', 'option');
		if($templates_list){
			foreach ($templates_list as $template) {
				$templates[sanitize_title($template['name'])] = $template['name'];
			}
		}
	}
  return $templates;
}

include("classes/PageTemplater.php");

PageTemplater::get_instance( cd_get_page_templates() );

/* CD Controller & Autoloader */

function cd_get_controller_class($controller_string){
	return str_replace( array('_','-'), '', ucwords($controller_string, '_-'));
}

include("classes/CDController.php");

if(!function_exists('cd_autoloader')){
	function cd_autoloader( $class, $dir = null ) {
    if ( is_null( $dir ) ){
      $dir = get_template_directory().'/app/controllers';
		}
    foreach ( scandir( $dir ) as $file ) {
      // directory?

      if ( is_dir( $dir.'/'.$file ) && substr( $file, 0, 1 ) !== '.' ){
        cd_autoloader( $class, $dir.'/'.$file.'/' );
			}

      // php file?
      if ( substr( $file, 0, 2 ) !== '._' && preg_match( "/.php$/i" , $file ) ) {

        // filename matches class?
        if ( str_replace( '.php', '', $file ) == $class || str_replace( '.class.php', '', $file ) == $class ) {
					require $dir . $file;
        }
      }
    }
  }
}

spl_autoload_register('cd_autoloader');

/* Ajax Functions */

include("classes/CDAjaxHandler.php");

add_action('wp_ajax_nopriv_cd_ajax_request', 'cd_ajax_handler');
add_action('wp_ajax_cd_ajax_request', 'cd_ajax_handler');

function cd_ajax_handler(){
	$ajax_handler = new CDAjaxHandler();
	$ajax_handler->action($_POST['_controller'], $_POST['_method']);
}

/*Theme Functions */

require get_template_directory() . '/theme-functions.php';
