<?php
class PostTypes
{

  public function __construct()
  {
    add_action('init', array($this, 'iniciar'));
  }

  public function iniciar()
  {

    $typeFiles = scandir(get_template_directory() . '/app/cpt');

    foreach ($typeFiles as $file) {

      if (!strstr($file, '.php') || strstr($file, '--')) continue;

      require_once('cpt/' . $file);
    }
  }

  private function registrar($standards)
  {

    $pTypeConfig = array(

      'labels' => array(
        'name'                  => _x($standards['title'], 'post type general name'),
        'singular_name'         => _x($standards['generic']['singular'], 'post type singular name'),
        'add_new'               => _x('Adicionar ' . $standards['generic']['singular'], 'Novo item'),
        'add_new_item'          => __('Adicionar ' . $standards['generic']['singular']),
        'edit_item'             => __('Editar ' . $standards['generic']['plural']),
        'new_item'              => __('Adicionar ' . $standards['generic']['singular']),
        'view_item'             => __('Ver ' . $standards['generic']['singular']),
        'all_items'             => 'Ver ' . $standards['generic']['plural'],
        'menu_name'             => $standards['title'],
        'featured_image'        => 'Imagem',
        'remove_featured_image' => 'Remover imagem',
        'parent_item_colon'     => '',
      ),

      'menu_icon'         => $standards['icon'],
      'public'            => true,
      'public_queryable'  => true,
      'show_ui'           => true,
      'show_in_nav_menus' => true,
      'has_archive'       => true,
      'menu_position'     => isset($standards['menu_position']) ? $standards['menu_position'] : 5,
      'supports'          => $standards['supports'],
      'rewrite'           => array('slug' => $standards['slug'])
    );

    // Taxonomias customizadas
    if (isset($standards['taxonomia'])) {

      for ($i = 0; $i < count($standards['taxonomia']); $i++) {
        $pTypeConfig['taxonomies'] = array($standards['taxonomia'][$i]['nome_registro']);
        $this->taxonomia($standards['taxonomia'][$i]);
      }
    }

    // Taxonomias padrão do WP (ex: tags)
    if (isset($standards['wp_taxonomies'])) {

      for ($i = 0; $i < count($standards['wp_taxonomies']); $i++) {
        array_push($pTypeConfig['taxonomies'], $standards['wp_taxonomies'][$i]);
      }
    }

    register_post_type($standards['slug'], $pTypeConfig);
  }

  public function taxonomia($config)
  {

    $taxConfig = array(
      'label'             => __($config['titulo']),
      'show_in_nav_menus' => false,
      'hierarchical'      => true,
      'rewrite'           => array('slug' => $config['postType'] . '/' . $config['slug'], 'with_front' => true)
    );

    register_taxonomy($config['nome_registro'], $config['postType'], $taxConfig);
  }
}

$post_types = new PostTypes();