<?php

defined( 'ABSPATH' ) || exit;

class Play_Post_Type {

    protected static $_instance = null;

    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

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

        $terms = apply_filters( 'play_taxonomy_columns', [ 'genre', 'artist', 'mood', 'activity', 'station_tag', 'product_tag' ] );

        foreach ( $terms as $key => $term ) {
            add_action( $term . '_add_form_fields', array( $this, 'edit_term_fields' ) );
            add_action( $term . '_edit_form_fields', array( $this, 'edit_term_fields' ) );
            add_filter( 'manage_edit-' . $term . '_columns', array( $this, 'term_columns' ), 10 );
            add_filter( 'manage_' . $term . '_custom_column', array( $this, 'term_column' ), 10, 3 );
        }

        add_action( 'created_term', array( $this, 'save_term_fields' ), 10, 3 );
        add_action( 'edit_term', array( $this, 'save_term_fields' ), 10, 3 );

        do_action( 'play_block_post_type_init', $this );
    }

    public function register() {
        // register station post type
        register_post_type(
            'station',
            apply_filters(
                'play_register_post_type_station',
                array(
                    'labels'       => $this->get_labels( 'هم ترانه', 'هم ترانه' ),
                    'public'       => true,
                    'has_archive'  => 'stations',
                    'rewrite'      => array( 'slug' => 'station', 'with_front' => true ),
                    'show_in_rest' => true,
                    'supports'     => array( 'title', 'editor', 'author', 'thumbnail', 'comments', 'custom-fields' ),
                    'menu_icon'    => plugin_dir_url( dirname( __FILE__ ) ) . 'build/icon.station.svg'
                )
            )
        );

        register_taxonomy(
            'artist',
            apply_filters( 'play_register_post_taxonomy_artist_types', array( 'station', 'product' ) ),
            apply_filters(
                'play_register_post_taxonomy_artist',
                array(
                    'labels'            => $this->get_labels( 'هنرمند', 'هنرمندان' ),
                    'rewrite'           => array( 'slug' => 'artist' ),
                    'show_in_rest'      => true,
                    'hierarchical'      => false,
                    'show_ui'           => true,
                    'show_admin_column' => false,
                    'capabilities'      => array(
                        'assign_terms' => 'read'
                    ),
                    'sort'              => true,
                    'args'              => array(
                        'orderby' => 'term_order',
                    )
                )
            )
        );

        register_taxonomy(
            'genre',
            apply_filters( 'play_register_post_taxonomy_genre_types', array( 'station' ) ),
            apply_filters(
                'play_register_post_taxonomy_genre',
                array(
                    'labels'            => $this->get_labels( 'ژانر', 'ژانرها' ),
                    'rewrite'           => array( 'slug' => 'genre' ),
                    'show_in_rest'      => true,
                    'hierarchical'      => true,
                    'show_ui'           => true,
                    'show_admin_column' => true,
                    'capabilities'      => array(
                        'assign_terms' => 'read'
                    )
                )
            )
        );

        register_taxonomy(
            'mood',
            apply_filters( 'play_register_post_taxonomy_mood_types', array( 'station' ) ),
            apply_filters(
                'play_register_post_taxonomy_station_mood',
                array(
                    'labels'            => $this->get_labels( 'حالت', 'حالت ها' ),
                    'rewrite'           => array( 'slug' => 'mood' ),
                    'show_in_rest'      => true,
                    'hierarchical'      => false,
                    'show_ui'           => true,
                    'show_admin_column' => true
                )
            )
        );

        register_taxonomy(
            'activity',
            apply_filters( 'play_register_post_taxonomy_activity_types', array( 'station' ) ),
            apply_filters(
                'play_register_post_taxonomy_station_activity',
                array(
                    'labels'            => $this->get_labels( 'فعالیت', 'فعالیت ها' ),
                    'rewrite'           => array( 'slug' => 'activity' ),
                    'show_in_rest'      => true,
                    'hierarchical'      => false,
                    'show_ui'           => true,
                    'show_admin_column' => true
                )
            )
        );

        register_taxonomy(
            'station_tag',
            apply_filters( 'play_register_post_taxonomy_station_tag_types', array( 'station' ) ),
            apply_filters(
                'play_register_post_taxonomy_station_tag',
                array(
                    'labels'            => $this->get_labels( 'برجسب', 'برچسب ها' ),
                    'rewrite'           => array( 'slug' => 'station-tag' ),
                    'show_in_rest'      => true,
                    'hierarchical'      => false,
                    'show_ui'           => true,
                    'show_admin_column' => true,
                    'capabilities'      => array(
                        'assign_terms' => 'read'
                    )
                )
            )
        );
    }

    public function get_labels( $singular, $plural = '' ) {
        $locale = get_locale();
        if ( $plural == '' ) {
            $plural = $singular;
        }
        $labels = array(
            'name'                       => $plural,
            'singular_name'              => $singular,
            'search_items'               => sprintf( __( 'جستجو %s' ), $plural ),
            'all_items'                  => sprintf( __( 'همه %s' ), $plural ),
            'parent_item'                => sprintf( __( 'اصلی %s' ), $plural ),
            'parent_item_colon'          => sprintf( __( 'اصلی %s:' ), $plural ),
            'edit_item'                  => sprintf( __( 'ویرایش %s' ), $singular ),
            'update_item'                => sprintf( __( 'برزورسانی %s' ), $singular ),
            'add_new_item'               => sprintf( __( 'افزودن جدید %s' ), $singular ),
            'add_new'                    => __( 'افزودن جدید' ),
            'new_item'                   => sprintf( __( 'افزودن جدید %s' ), $singular ),
            'view_item'                  => sprintf( __( 'مشاهده %s' ), $singular ),
            'popular_items'              => sprintf( __( 'محبوب %s' ), $plural ),
            'new_item_name'              => sprintf( __( 'جدید %s نام' ), $singular ),
            'separate_items_with_commas' => sprintf( __( 'جدا کنید با %s کاما' ), $plural ),
            'add_or_remove_items'        => sprintf( __( 'افزودن یا حذف %s' ), $plural ),
            'choose_from_most_used'      => sprintf( __( 'یک مورد را باید انتخاب کنید. %s' ), $plural ),
            'not_found'                  => sprintf( __( 'هیچ %s یافت نشد' ), $plural ),
            'not_found_in_trash'         => sprintf( __( 'هیچ %s در زباله دان یافت نشد...' ), $plural ),
            'menu_name'                  => $plural,
            'name_admin_bar'             => $singular
        );

        return apply_filters( 'play_' . strtolower( $singular ) . '_labels_locale', $labels, $locale );
    }

    public function edit_term_fields( $term ) {
        wp_enqueue_media();
        $thumbnail_id = 0;
        if ( isset( $term->term_id ) ) {
            $thumbnail_id = absint( get_term_meta( $term->term_id, 'thumbnail_id', true ) );
        }
        $wrap   = '<div class="form-field term-thumbnail-wrap"><label>Thumbnail</label>%s</div>';
        $el     = '<img src="%s" width="60px" height="60px" style="background: #fff;"><input type="hidden" name="thumbnail_id" value="' . $thumbnail_id . '"><button type="button" class="button upload-btn">Upload</button>';
        $holder = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
        $image  = $holder;
        if ( isset( $term->term_id ) ) {
            $wrap = '<tr class="form-field term-thumbnail-wrap"><th scope="row" valign="top"><label>Thumbnail</label></th><td>%s</td></tr>';
            if ( $thumbnail_id ) {
                $image = wp_get_attachment_thumb_url( $thumbnail_id );
            }
        }
        echo sprintf( $wrap, sprintf( $el, $image ) );
        ?>
        <script type="text/javascript">
            (function ($) {
                'use strict';
                var media;
                $(document).on('click', '.upload-btn', function (e) {
                    e.preventDefault();
                    if (media) {
                        media.open();
                        return;
                    }
                    var that = $(this);
                    media = wp.media({title: 'Choose an image', multiple: false})
                        .open()
                        .on('select', function (e) {
                            var obj = media.state().get('selection').first().toJSON();
                            var thumbnail = obj.sizes.thumbnail || obj.sizes.full;
                            that.siblings('img').attr('src', thumbnail.url);
                            that.prev().val(obj.id);
                        });
                });
                $(document).ajaxComplete(function (event, request, options) {
                    $('div.term-thumbnail-wrap img').attr('src', '<?php echo $holder; ?>');
                });
            })(jQuery);
        </script>
        <?php
    }

    public function save_term_fields( $term_id, $tt_id = '', $taxonomy = '' ) {
        if ( isset( $_POST[ 'thumbnail_id' ] ) ) {
            update_term_meta( $term_id, 'thumbnail_id', absint( $_POST[ 'thumbnail_id' ] ) );
        }
    }

    public function term_columns( $columns ) {
        $new = array();
        foreach ( $columns as $key => $title ) {
            if ( $key == 'description' ) {
                $new[ 'thumb' ] = 'Thumbnail';
            }
            $new[ $key ] = $title;
        }

        return $new;
    }

    public function term_column( $columns, $column, $id ) {
        if ( 'thumb' === $column ) {
            $thumbnail_id = (int) get_term_meta( $id, 'thumbnail_id', true );
            $image        = '';
            if ( $thumbnail_id ) {
                $thumb = wp_get_attachment_thumb_url( $thumbnail_id );
                $image = '<img src="' . esc_url( $thumb ) . '" class="wp-post-image" height="48" width="48" />';
            }
            $columns .= $image;
        }

        return $columns;
    }

}

Play_Post_Type::instance();
