<?php


use Amadeus\Core\Traits\GutenbergBlocks;
use Amadeus\Core\Shortcode;
use Timber\Menu as TimberMenu;
use Timber\Site as TimberSite;
use Timber\Timber;


if (!class_exists('Timber\Timber')) {
    add_action('admin_notices', function () {
        echo '<div class="error"><p>amadeus CORE 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() . '/static/no-timber.html';
    });

    return;
}

Timber::$dirname = array('views');

class MEGSite extends TimberSite
{
    use GutenbergBlocks;

    protected $themeSlug = 'meg';

    function __construct()
    {
        add_theme_support('post-formats', array('aside', 'gallery', 'status', 'video'));
        add_theme_support('post-thumbnails');
        add_theme_support('menus');
        add_theme_support('automatic-feed-links');
        add_theme_support('html5', array('comment-list', 'comment-form', 'search-form', 'gallery', 'caption'));
        add_theme_support('title-tag');
        add_theme_support('customize-selective-refresh-widgets');
        add_theme_support('gutenberg');

        add_filter('timber_context', array($this, 'addToContext'));

        add_action('widgets_init', [$this, 'registerWidgetAreas']);

        add_action('wp_enqueue_scripts', [$this, 'registerScripts'], 1, 1);
        add_action('wp_enqueue_scripts', [$this, 'registerStyles'], 2, 13);
        add_action('admin_enqueue_scripts', [$this, 'registerAdminScripts'], 999, 0);
        add_action('wp_enqueue_scripts', [$this, 'deregisterStyles'], 999, 0);
        add_action('login_enqueue_scripts', [$this, 'registerLoginStyles']);

        add_action('init', [$this, 'custom_post_type'], 0);
        add_action('init', [$this, 'registerShortcodes'], 0);
        add_action('init', [$this, 'onInit']);

        add_filter('amadeus_team_template', function ($template) {
            return 'shortcodes/team.twig';
        });
        add_filter('amadeus_job_template', function ($template) {
            return 'shortcodes/jobs.twig';
        });


        add_filter('amadeus_team_queryargs', function ($args) {
            $modified_args = $args;
            $modified_args['meta_key'] = 'nachname';
            $modified_args['orderby'] = 'meta_value';
            $modified_args['order'] = 'ASC';
            return $modified_args;
        });

        $this->addUpdater();

        parent::__construct();


        add_action('after_setup_theme', [$this,'custom_image_size']);
    }

    public function custom_image_size()
    {
        update_option('image_default_align', 'center' );
        update_option('image_default_size', 'large' );
    }

    function onInit()
    {
        new Shortcode('map',[$this,'renderMap']);
        new Shortcode('map',[$this,'renderMap']);


        $this->registerGutenbergBlock('news', [$this, 'renderNewsBlock']);
        $this->registerGutenbergBlock('news-featured', [$this, 'renderNewsFeaturedlock']);
    }


    function addToContext($context)
    {
        $context['site'] = $this;

        $context['primary'] = new TimberMenu('primary');
        $context['footer'] = new TimberMenu('footer');
        $context['bottom'] = new TimberMenu('bottom');

        $context['languages'] =  apply_filters( 'wpml_active_languages', NULL, 'orderby=id&order=desc' );



        $context['footer'] = [
            'footer_1' => Timber::get_widgets('footer-1'),
            'footer_2' => Timber::get_widgets('footer-2'),
            'footer_3' => Timber::get_widgets('footer-3')
        ];


        return $context;
    }

    function myfoo($text)
    {

        return $text;
    }

    function add_to_twig($twig)
    {
        /* this is where you can add your own functions to twig */
        $twig->addExtension(new Twig_Extension_StringLoader());

        return $twig;
    }


    public function renderNewsBlock()
    {
        $context['site'] = $this;

        $args = [
            'post_type' => 'post',
            'posts_per_page' => 3,
            'post_status' => 'publish',
            'ignore_sticky_posts' => 1
        ];

        $context['posts'] = Timber::get_posts($args);

        return Timber::compile('blocks/amds-news.twig', $context);
    }

    public function renderNewsFeaturedlock()
    {
        $context['site'] = $this;

        $args = [
            'post_type' => 'post',
            'posts_per_page' => 6,
            'post_status' => 'publish',
            'ignore_sticky_posts' => 1
        ];

        $context['posts'] = Timber::get_posts($args);

        return Timber::compile('blocks/amds-news-featured.twig', $context);
    }

    public function renderMap()
    {

        return Timber::compile('shortcodes/amds-map.twig', []);
    }

    function addUpdater()
    {

        $myUpdateChecker = Puc_v4_Factory::buildUpdateChecker(
            'https://updates.amadeus-agentur.com/?action=get_metadata&slug=' . $this->themeSlug,
            __FILE__, //Full path to the main plugin file or functions.php.
            $this->themeSlug
        );
    }

    public function registerAdminScripts()
    {
        wp_enqueue_style('z-amds-style', get_theme_root_uri() . DIRECTORY_SEPARATOR . $this->themeSlug . '/static/css/admin.css', [],
            wp_get_theme()->get('Version'));
    }

    public function registerScripts()
    {

        wp_enqueue_script('app', get_theme_root_uri() . DIRECTORY_SEPARATOR . $this->themeSlug . '/static/js/app.init.js', [],
            wp_get_theme()->get('Version'), true);
        wp_enqueue_script('app-vendor', get_theme_root_uri() . DIRECTORY_SEPARATOR . $this->themeSlug . '/static/js/app.vendors.js', [],
            wp_get_theme()->get('Version'), true);
    }

    public function registerStyles()
    {

        wp_enqueue_style('dashicons');

        wp_enqueue_style($this->themeSlug . '-style', get_theme_root_uri() . DIRECTORY_SEPARATOR . $this->themeSlug . '/static/css/theme.css', ['wp-block-library'],
            wp_get_theme()->get('Version'));


    }

    public function registerShortcodes() {
        add_shortcode('meg_jobs', [$this, 'sc_display_job_descriptions']);
    }

    public function deregisterStyles()
    {
        wp_dequeue_style('cff');
    }

    public function registerLoginStyles()
    {
        wp_enqueue_style('login-css', get_theme_root_uri() . DIRECTORY_SEPARATOR . $this->themeSlug . '/static/css/login.css', [],
            wp_get_theme()->get('Version'));
    }

    // Register Custom Post Type
    public function custom_post_type() {
        $labels = array(
            'name'                  => 'Teams',
            'singular_name'         => 'Team',
            'menu_name'             => 'Team',
            'name_admin_bar'        => 'Team',
//            'archives'              => __( 'Item Archives', 'text_domain' ),
//            'attributes'            => __( 'Attribute', 'text_domain' ),
//            'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
//            'all_items'             => __( 'All Items', 'text_domain' ),
//            'add_new_item'          => __( 'Add New Item', 'text_domain' ),
            'add_new'               => 'Neu hinzufügen',
            'new_item'              => 'Neu erstellen',
            'edit_item'             => 'Bearbeiten',
            'update_item'           => 'Aktualisieren',
            'view_item'             => 'Vorschau anzeigen',
//            'view_items'            => __( 'View Items', 'text_domain' ),
            'search_items'          => 'Suchen',
            'not_found'             => 'Nicht gefunden',
//            'not_found_in_trash'    => 'Not found in Trash',
            'featured_image'        => 'Mitgliedsfoto',
            'set_featured_image'    => 'Mitgliedsfoto festlegen',
            'remove_featured_image' => 'Mitgliedsfoto entfernen',
//            'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
//            'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
//            'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
//            'items_list'            => __( 'Items list', 'text_domain' ),
//            'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
//            'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
        );
        $args = array(
            'labels'                => $labels,
            'description'           => 'Teammitgliederverwaltung',
//            'labels'                => $labels,
            'supports'              => array( 'title', 'thumbnail' ),
            'taxonomies'            => array( 'category', 'post_tag' ),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => true,
            'menu_position'         => 5,
            'menu_icon'             => 'dashicons-buddicons-buddypress-logo',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => true,
            'exclude_from_search'   => true,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
        );
        register_post_type( 'team', $args );

        $labels = array(
            'name'                  => 'Jobs',
            'singular_name'         => 'Job',
            'menu_name'             => 'Stellenangebote',
            'name_admin_bar'        => 'Stellenangebote',
//            'archives'              => __( 'Item Archives', 'text_domain' ),
//            'attributes'            => __( 'Attribute', 'text_domain' ),
//            'parent_item_colon'     => __( 'Parent Item:', 'text_domain' ),
//            'all_items'             => __( 'All Items', 'text_domain' ),
//            'add_new_item'          => __( 'Add New Item', 'text_domain' ),
            'add_new'               => 'Neu hinzufügen',
            'new_item'              => 'Neu erstellen',
            'edit_item'             => 'Bearbeiten',
            'update_item'           => 'Aktualisieren',
            'view_item'             => 'Vorschau anzeigen',
//            'view_items'            => __( 'View Items', 'text_domain' ),
            'search_items'          => 'Suchen',
            'not_found'             => 'Nicht gefunden',
//            'not_found_in_trash'    => 'Not found in Trash',
            'featured_image'        => 'Artikelbild',
            'set_featured_image'    => 'Artikelbild festlegen',
            'remove_featured_image' => 'Artikelbild entfernen',
//            'use_featured_image'    => __( 'Use as featured image', 'text_domain' ),
//            'insert_into_item'      => __( 'Insert into item', 'text_domain' ),
//            'uploaded_to_this_item' => __( 'Uploaded to this item', 'text_domain' ),
//            'items_list'            => __( 'Items list', 'text_domain' ),
//            'items_list_navigation' => __( 'Items list navigation', 'text_domain' ),
//            'filter_items_list'     => __( 'Filter items list', 'text_domain' ),
        );
        $args = array(
            'labels'                => $labels,
            'description'           => 'Teammitgliederverwaltung',
            'supports'              => array( 'title', 'editor', 'thumbnail', 'revisions', 'post-formats' ),
            'taxonomies'            => array( 'category', 'post_tag' ),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => true,
            'menu_position'         => 5,
            'menu_icon'             => 'dashicons-id-alt',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => false,
            'exclude_from_search'   => false,
            'delete_with_user'      => false,
            'publicly_queryable'    => true,
            'capability_type'       => 'post',
        );
        register_post_type( 'job', $args );
    }

    public function sc_display_job_descriptions( $atts, $content = null ) {
        $params = shortcode_atts( array('category' => 'festanstellung,ausbildung'), $atts, 'meg_jobs' );

        $args = array(
            'post_type' => 'job',
            'post_status' => 'publish',
            'category_name' => $params['category'],
            'orderby' => 'title',
            'order' => 'ASC'
        );

        $string = '';
        $query = new WP_Query( $args );
        if( $query->have_posts() ){
            $string .= '<ul>';
            while( $query->have_posts() ){
                $query->the_post();
                $string .= '<li><a href="' . get_permalink() .'">' . get_the_title() . '</a></li>';
            }
            $string .= '</ul>';
        }
        else {
            $string .= 'Aktuell sind keine freien Stellen verfügbar.';
        }

        wp_reset_query();
        return $string;
    }
}

include 'updater/theme-updater.php';

new MEGSite();
