<?php

namespace WPIS;

class AgentPostType {

    static public $postTypeName = 'wpis_agents';
    static public $postTypeMetaPrefix = 'wpis';

    static public function init() {

        $class = new self();

        if( SettingsManager::get('enableAgentManagementCustomPostType') ){
            self::$postTypeName = SettingsManager::get('agentCustomPostType');
        }
        else {
            add_action( 'init', [$class, 'registerPostType']);
            add_filter( 'add_menu_classes', [$class, 'addMenuPostCount']);
            add_filter( 'manage_' . self::$postTypeName .  '_posts_columns', [$class, 'setCustomColumns'] );
            add_action( 'manage_' . self::$postTypeName .  '_posts_custom_column' , [$class, 'applyCustomColumns'], 10, 2 );
        }
    }

    public function registerPostType(){

        register_post_type(
            self::$postTypeName,
            [
                'labels'      => [
                    'name'          => __('Agents', 'wpis'),
                    'singular_name' => __('Agent', 'wpis'),
                ],
                'public'      => true,
                'has_archive' => true,
                'show_in_rest' => false,
                'rewrite'      => [
                    'slug' => SettingsManager::get('postTypeAgentSlug', self::$postTypeName)
                ],
                'menu_icon'   => 'dashicons-admin-users',
                'supports'  => [
                    'title',
                    'editor',
                    'thumbnail'
                ]
            ]
        );

    }

    public function addMenuPostCount( $menu ) {
        $count = wp_count_posts(  self::$postTypeName, 'readable' );
        $count = $count->publish;

        foreach($menu as $index => $item){
            if( $item[2] === 'edit.php?post_type=' . self::$postTypeName){
                $item[0] .= '<span class="wpis_adminPostCount">' . $count . '</span>' ;
                $menu[$index] = $item;
            }
        }

        return $menu;
    }

    public function setCustomColumns($columns) {

        $columns['thumbnail'] = __( 'Image', 'wpis' );
        $columns['managed_estates'] = __( 'Managed estate count', 'wpis' );

        $columnClone = $columns;

        $order = [
            'cb',
            'thumbnail',
            'title',
            'managed_estates'
        ];

        usort($columns, function ($a, $b) use ($order) {
            if( isset($columns) ){
                $pos_a = array_search($columns[$a], $order);
                $pos_b = array_search($columns[$b], $order);
                return $pos_a - $pos_b;
            }
        });

        $columnsMapped = [];

        foreach( $order as $i => $value ){
            $columnsMapped[$order[$i]] = $columnClone[$value];
        }

        return $columnsMapped;
    }

    public function applyCustomColumns( $column, $post_id ) {

        $estatePostTypeName =  SettingsManager::get('enableImportCustomPostType') ? SettingsManager::get('customPostType') : EstatePostType::$postTypeName;

        $childPosts = query_posts([
            'post_type' => $estatePostTypeName,
            'posts_per_page' => -1,
            'meta_query' => [
                [
                  'key'     => self::$postTypeMetaPrefix . '_' . 'agent_firstname',
                  'compare' => '=',
                  'value'   => get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'agent_firstname' , true ),
                  'type'    => 'CHAR',
                ]
            ]
        ]);

        switch ( $column ) {
            case 'thumbnail' :
                // echo get_the_post_thumbnail( $post_id, [50, 50] );
                $picture = get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'agent_picture' , true );
                echo '<img src=' . $picture .' height="50">';
                break;
            case 'managed_estates' :
                echo count($childPosts);
                break;
        }
    }

}