<?php
/**
 * @package web-livedraw
 * @since 1.0.0
 */

class Exito extends Exito_System
{
    function __construct()
    {
        //
    }

    function run()
    {
        register_nav_menus([
            'menu_mobile' => 'Menu Mobile',
            'menu_header' => 'Menu Header',
            'menu_footer' => 'Menu Footer',
            'menu_sosmed' => 'Menu Social Media',
            'quick_links' => 'Quick Links',
        ]);

        add_action( 'init', [ $this, 'init' ] );
        add_action( 'after_setup_theme', [ $this, 'theme_setup' ] );
        add_action( 'init', [ $this, 'tags_support_all' ] );
        add_action( 'pre_get_posts', [ $this, 'tags_support_query' ] );
        add_action( 'widgets_init', [ $this, 'register_widget_areas' ] );
        add_action( 'wp_ajax_history', [ $this, 'ajax_history' ] );
        add_action( 'wp_ajax_nopriv_history', [ $this, 'ajax_history' ] );
        add_action( 'wp_ajax_livedraw', [ $this, 'ajax_livedraw' ] );
        add_action( 'wp_ajax_nopriv_livedraw', [ $this, 'ajax_livedraw' ] );
        add_action( 'wp_ajax_rtp', [ $this, 'ajax_rtp' ] );
        add_action( 'wp_ajax_nopriv_rtp', [ $this, 'ajax_rtp' ] );
        add_action( 'admin_footer', [ $this, 'remove_taxonomy_fields' ] );
        add_action( 'pasaran_add_form_fields', [ $this, 'add_taxonomy_fields' ] );
        add_action( 'pasaran_edit_form_fields', [ $this, 'edit_taxonomy_fields' ] );
        add_action( 'created_pasaran', [ $this, 'create_taxonomy_data' ] );
        add_action( 'edited_pasaran', [ $this, 'update_taxonomy_data' ] );
        add_action( 'manage_pasaran_custom_column', [ $this, 'manage_taxonomy_column' ], 10, 3 );
        add_action( 'admin_print_footer_scripts', [ $this, 'add_to_post_status_dropdown' ], 8 );
        add_action( 'generate_prediksi', [ $this, 'generate_prediksi_all' ] );
        add_action( 'generate_prediksi_slot', [ $this, 'generate_prediksi_slot_all' ] );
        add_action( 'generate_syair', [ $this, 'generate_syair_all' ] );
        add_action( 'generate_rtp_image', [ $this, 'generate_rtp_image_all' ] );

        add_filter( 'nav_menu_css_class', [ $this, 'nav_class' ], 10, 2 );
        add_filter( 'the_tags', [ $this, 'add_class_the_tags' ], 10, 1 );
        add_filter( 'excerpt_length', [ $this, 'excerpt_length_limits' ] );
        add_filter( 'excerpt_more', [ $this, 'excerpt_more_link' ] );
        add_filter( 'next_posts_link_attributes', [ $this, 'posts_link_attributes' ] );
        add_filter( 'previous_posts_link_attributes', [ $this, 'posts_link_attributes' ] );
        add_filter( 'manage_edit-pasaran_columns', [ $this, 'manage_taxonomy_columns' ] );
        add_filter( 'manage_edit-pasaran_sortable_columns', [ $this, 'manage_taxonomy_sortable_columns' ] );
        add_filter( 'terms_clauses', [ $this, 'filter_terms_clauses' ], 10, 3 );
        add_filter( 'display_post_states', [ $this, 'display_archive_state' ] );
    }

    function init()
    {
        $this->register_pasaran_taxonomy();

        register_post_status( 'contoh', [
            'label'                     => 'Contoh',
            'public'                    => false,
            'exclude_from_search'       => false,
            'show_in_admin_all_list'    => true,
            'show_in_admin_status_list' => true,
            'label_count'               => _n_noop( 'Contoh <span class="count">(%s)</span>', 'Contoh <span class="count">(%s)</span>' ),
        ] );
    }

    function theme_setup()
    {
        add_theme_support( 'custom-logo' );
        add_theme_support( 'custom-background' );
        add_theme_support( 'post-thumbnails' );
        add_theme_support( 'title-tag' );
        
        load_theme_textdomain( TXTDOMAIN );
    }

    function web_logo( $class = null )
    {
        $img_logo  = wp_get_attachment_image_src( get_theme_mod( 'custom_logo' ) , 'full' );
        $img_class = ( $class == null ) ? '' : ' ' . $class;
        return '<img alt="Logo" class="web-logo' . $img_class . '" src="' . ($img_logo == null ? '' : $img_logo[0]) . '">';
    }

    function nav_class( $classes, $item )
    {
        if ( in_array( 'current-menu-item', $classes ) ) { $classes[] = 'active current '; }
        return $classes;
    }

    function add_class_the_tags( $html )
    {
        $postid = get_the_ID();
        $html   = str_replace( '<a', '<a class="badge badge-dark"', $html );
        return $html;
    }

    function add_taxonomy_fields()
    {
        ?>
            <div class="form-field">
                <label for="sort-order">Sort Order</label>
                <input type="number" name="sort_order" id="sort-order">
                <p>Sort order untuk daftar nama pasaran.</p>
            </div>
        <?php
    }

    function edit_taxonomy_fields()
    {
        $terms = $_GET['tag_ID'];
        $value = get_term_meta( $terms, 'sort-order', true );
        ?>
            <tr class="form-field">
                <th scope="row"><label for="sort-order">Sort Order</label></th>
                <td><input type="number" name="sort_order" id="sort-order" value="<?php echo $value; ?>" size="40">
                <p>Sort order untuk daftar nama pasaran.</p>
            </tr>
        <?php
    }

    function tags_support_all()
    {
        register_taxonomy_for_object_type( 'post_tag', 'page' );
    }

    function tags_support_query( $wp_query )
    {
        if ( $wp_query->get( 'tag' ) ) $wp_query->set( 'post_type', 'any' );
    }

    function excerpt_length_limits( $length )
    {
        return 20;
    }

    function excerpt_more_link( $more )
    {
        return '';
    }

    function posts_link_attributes()
    {
        return 'class="btn btn-sm btn-custom"';
    }

    function register_widget_areas()
    {
        register_sidebar([
            'name'          => 'Header Banner',
            'id'            => 'header_banner',
            'description'   => 'List of header banner',
            'before_widget' => '',
            'after_widget'  => '',
            'before_title'  => '<div class="d-none">',
            'after_title'   => '</div>',
        ]);
        register_sidebar([
            'name'          => 'Footer Banner',
            'id'            => 'footer_banner',
            'description'   => 'List of footer banner',
            'before_widget' => '',
            'after_widget'  => '',
            'before_title'  => '<div class="d-none">',
            'after_title'   => '</div>',
        ]);
    }

    function register_pasaran_taxonomy()
    {
        $text = 'pasaran';
        $name = 'Pasaran';
        $args = [
            'hierarchical'      => true,
            'labels'            => [
                'name'               => __( $name, 'taxonomy general name', TXTDOMAIN ),
                'singular_name'      => __( $name, 'taxonomy singular name', TXTDOMAIN ),
                'search_items'       => __( 'Search ' . $name, TXTDOMAIN ),
                'all_items'          => __( 'All ' . $name, TXTDOMAIN ),
                'parent_item'        => __( 'Parent ' . $name, TXTDOMAIN ),
                'parent_item_colon'  => __( 'Parent ' . $name . ' :', TXTDOMAIN ),
                'edit_item'          => __( 'Edit ' . $name, TXTDOMAIN ),
                'update_item'        => __( 'Update ' . $name, TXTDOMAIN ),
                'add_new_item'       => __( 'Add New ' . $name, TXTDOMAIN ),
                'new_item_name'      => __( 'New ' . $name . ' Name', TXTDOMAIN ),
                'not_found'          => __( 'Data '.$name.' kosong, silahkan buat baru.', TXTDOMAIN ),
                'not_found_in_trash' => __( 'Tidak ada Data '.$name.' di kotak sampah.', TXTDOMAIN ),
                'menu_name'          => __( $name, TXTDOMAIN ),
            ],
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => $text ),
        ];
     
        register_taxonomy( $text, array( 'page' ), $args );
    }

    function remove_taxonomy_fields()
    {
        global $current_screen;

        if ( $current_screen->id == 'edit-pasaran' ) {
            ?>
                <script type="text/javascript">
                    jQuery(document).ready(function ($) {
                        $("#tag-slug").parent().remove();
                        $("#parent").parent().remove();
                        $("#tag-description").parent().remove();
                        $("#description").parent().remove();
                        $('tr[class="form-field term-slug-wrap"]').remove();
                        $('tr[class="form-field term-parent-wrap"]').remove();
                        $('tr[class="form-field term-description-wrap"]').remove();
                    });
                </script>
            <?php
        }
    }

    function manage_taxonomy_columns( $columns )
    {
        unset( $columns['description'] );
        unset( $columns['slug'] );
        unset( $columns['posts'] );

        $output = [];

        foreach ( $columns as $key => $val ) {
            if ( $key == 'name' ) {
                $output['sort-order'] = 'Sort Order';
            }
            $output[$key] = $val;
        }

        return $output;
    }

    function manage_taxonomy_sortable_columns( $columns )
    {
        $columns['sort-order'] = 'sort-order';

        return $columns;
    }

    function manage_taxonomy_column( $string, $columns, $term_id )
    {
        switch ( $columns ) {
            case 'sort-order':
                echo get_term_meta( $term_id, 'sort-order', true );
            break;
        }
    }

    function create_taxonomy_data( $term_id )
    {
        update_term_meta( $term_id, 'sort-order', intval( $_POST['sort_order'] ) );
        
        $this->generate_page_pasaran( $_POST['tag-name'], intval( $_POST['sort_order'] ) );
    }

    function update_taxonomy_data( $term_id )
    {
        update_term_meta( $term_id, 'sort-order', intval( $_POST['sort_order'] ) );

        $this->update_page_pasaran( $_POST['tag-name'], intval( $_POST['sort_order'] ) );
    }

    function filter_terms_clauses( $pieces, $taxonomies, $args )
    {
        global $pagenow, $wpdb; 
    
        // Require ordering
        $orderby = ( isset( $_GET['orderby'] ) ) ? trim( sanitize_text_field( $_GET['orderby'] ) ) : ''; 
        if ( empty( $orderby ) ) { return $pieces; }
    
        // set taxonomy
        $taxonomy = $taxonomies[0];
    
        // only if current taxonomy or edit page in admin           
        if ( !is_admin() || $pagenow !== 'edit-tags.php' || !in_array( $taxonomy, [ 'pasaran' ] ) ) { return $pieces; }
    
        // and ordering matches
        if ( $orderby === 'sort-order' ) {
            $pieces['join']    .= ' INNER JOIN ' . $wpdb->termmeta . ' AS tm ON t.term_id = tm.term_id ';
            $pieces['where']   .= ' AND tm.meta_key = "sort-order"';
            $pieces['orderby']  = ' ORDER BY tm.meta_value ';
        }
    
        return $pieces;
    }

    function ajax_history()
    {
        if ( isset( $_POST['action'] ) && $_POST['action'] == 'history' && isset( $_POST['page'] ) ) {
            $numb = 0;
            $list = $this->get_history( $_POST['page'] );
            $data = [];
    
            foreach ( $list as $item ) :
                if ( $numb <= 5 ) :
                    $data[$numb] = $item;
                    $numb++;
                endif;
            endforeach;
    
            echo json_encode( $list );
    
            die();
        }
    }

    function ajax_livedraw()
    {
        if ( isset( $_POST['action'] ) && $_POST['action'] == 'livedraw' && isset( $_POST['pasaran'] ) ) {
            echo json_encode( $this->get_livedraw( $_POST['pasaran'] ), true );

            die();
        }
    }

    function ajax_rtp()
    {
        if ( isset( $_POST['action'] ) && $_POST['action'] == 'rtp' && isset( $_POST['provider'] ) ) {
            $data = rtp_providers();
            $list = $data[$_POST['provider']];
            $json = rtp_games( $list );
    
            echo formatting_rtp( $json, $list );
    
            die();
        }
    }

    function add_to_post_status_dropdown()
    {
        // Must be a valid WP_Post object
		global $post;
		if ( !isset($post) ) return;
		if ( !($post instanceof WP_Post) ) return;
		
		$is_selected = $post->post_status == 'contoh';
		
?>

<script type="text/javascript">
// Single post edit screen, add dropdowns and text to publihs box:
jQuery(function() {
	var expired_selected = <?php echo $is_selected ? 1 : 0; ?>;
	
	var $post_status = jQuery("#post_status");
	var $post_status_display = jQuery("#post-status-display");

	$post_status.append('<option value="contoh">Contoh</option>');
	
	if ( expired_selected ) {
		$post_status.val( 'contoh' );
		$post_status_display.text('Contoh');
	}
});

// Post listing screen: Add quick edit functionality:
jQuery(function() {
	// See: /wp-admin/js/inline-edit-post.js -> Window.inlineEditPost.edit
	var insert_expired_status_to_inline_edit = function(t, post_id, $row) {
		// t = window.inlineEditPost
		// post_id = post_id of the post (eg: div#inline_31042 -> 31042)
		// $row = The original post row <tr> which contains the quick edit button, post title, columns, etc.
		var $editRow = jQuery('#edit-' + post_id); // The quick edit row that appeared.
		var $rowData = jQuery('#inline_' + post_id); // A hidden row that contains relevant post data
		
		var status = jQuery('._status', $rowData).text(); // Current post status
		
		var $status_select = $editRow.find('select[name="_status"]'); // Dropdown to change status
		
		// Add expired status to dropdown, if not present
		if ( $status_select.find('option[value="contoh"]').length < 1 ) {
			$status_select.append('<option value="contoh">Contoh</option>');
		}
		
		// Select expired from dropdown if that is the current post status
		if ( status === 'contoh' ) $status_select.val( 'contoh' );
		
		// View information:
		// console.log( id, $row, $editRow, $rowData, status, $status_select );
	};
	
	// On click, wait for default functionality, then apply our customizations
	var inline_edit_post_status = function() {
		var t = window.inlineEditPost;
		var $row = jQuery(this).closest('tr');
		var post_id = t.getId(this);
		
		// Use next frame if browser supports it, or wait 0.25 seconds
		if ( typeof requestAnimationFrame === 'function' ) {
			requestAnimationFrame(function() { return insert_expired_status_to_inline_edit( t, post_id, $row ); });
		}else{
			setTimeout(function() { return insert_expired_status_to_inline_edit( t, post_id, $row ); }, 250 );
		}
	};
	
	// Bind click event before inline-edit-post.js has a chance to bind it
	jQuery('#the-list').on('click', '.editinline', inline_edit_post_status);
});
</script>

<?php

    }

    function display_archive_state( $states )
    {
        global $post;

        if( $post != null && $post->post_status == 'contoh' ) {
            echo "
                <script>
                    jQuery(document).ready( function() {
                        jQuery( '#post-status-display' ).text( 'Contoh' );
                    });
                </script>
            ";

            return [ 'Contoh' ];
        }

        return $states;
    }
}
