<?php

namespace WPIS;

class ProjectPostType {

    static public $postTypeName = 'wpis_projects';
    static public $postTypeMetaPrefix = 'wpis';
    static private $db;

    static public function init() {

        $class = new self();

        self::$db = $GLOBALS['wpdb'];

        if( SettingsManager::get('enableProjectManagementCustomPostType') ){
            self::$postTypeName = SettingsManager::get('projectCustomPostType');
        }
        else {
            add_action( 'init', [$class, 'registerPostType']);
            add_action( 'init', [$class, 'enableChildFiltering']);
            add_filter( 'add_menu_classes', [$class, 'displayPostCount']);
            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'          => __('Projects', 'wpis'),
                    'singular_name' => __('Project', 'wpis'),
                ],
                'public'      => true,
                'has_archive' => true,
                'show_in_rest' => false,
                'rewrite'      => [
                    'slug' => SettingsManager::get('postTypeProjectSlug', self::$postTypeName)
                ],
                'menu_icon'   => 'dashicons-building',
                'supports'  => [
                    'title',
                    'editor',
                    'thumbnail'
                ]
            ]
        );

    }

    public function enableChildFiltering() {
        if ( is_admin() )
            $GLOBALS['wp']->add_query_var( 'post_parent' );
    }

    public function displayPostCount( $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['type-category'] = __( 'Category', 'wpis' );
        $columns['price-range'] = __( 'Price range', 'wpis' );
        $columns['purpose'] = __( 'Status', 'wpis' );
        $columns['reference'] = __( 'Reference', 'wpis' );
        $columns['childsEstateCount'] = __( 'Estate count', 'wpis' );
        $columns['locked'] = '<i class="fa fa-lock"></i>';
        $columns['undeletable'] = '<i class="fa fa-trash"></i>';

        $columnClone = $columns;

        $order = [
            'cb',
            'thumbnail',
            'title',
            'type-category',
            'childsEstateCount',
            'price-range',
            'reference',
            'locked',
            'undeletable',
            'date',
        ];

        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;

        $estateId = get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'id' , true );

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

        $childPostsIds = [];
        foreach( $childPosts as $childPost ){
            $childPostsIds[] = $childPost->ID;
        }

        switch ( $column ) {

            case 'thumbnail' :
                echo get_the_post_thumbnail( $post_id, [50, 50] );
                break;

            case 'type-category' :
                $type = get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'category_label' , true );
                $typeCategory = Tools::ucfirst($type);
                echo $typeCategory;
                break;

            case 'price-range' :
                $price = intval(get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'finance_price' , true ));
                $price = round($price);
                $price = number_format_i18n($price);
                $price = str_replace(',', ' ', $price);
                $currency = get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'finance_currency' , true );

                if( $childPostsIds ) {
                    $minMax = self::$db->get_results(
                        "
                        SELECT MIN(meta_value) as min, MAX(meta_value) as max FROM (
                            SELECT meta_value FROM " . self::$db->posts . " as posts
                            JOIN " . self::$db->postmeta . " as metas ON posts.ID =  metas.post_id
                            WHERE posts.ID IN (" . implode(',', $childPostsIds) . ")
                            AND metas.meta_key = 'wpis_finance_price'
                            AND post_type  = '" . $estatePostTypeName . "'
                        ) minMaxQuery;
                        "
                    );
                    if( isset($minMax[0]) ){
                        $minPrice = number_format_i18n($minMax[0]->min);
                        $minPrice = str_replace(',', ' ', $minPrice);
                        $maxPrice = number_format_i18n($minMax[0]->max);
                        $maxPrice = str_replace(',', ' ', $maxPrice);
                        echo $minPrice . ' ' . $currency . ' à ' . $maxPrice . ' '  . ($currency ?? '€');
                    }
                }
                else {
                    echo 'N/A';
                }
                break;

            case 'reference' :
                $reference = get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'reference' , true );
                echo $reference;
                break;

            case 'locked' :
                $isLocked = get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'locked' , true );
                echo $isLocked ? '<i class="icon-lock-on fas fa-lock"></i>' : '<i class="icon-lock-off fas fa-lock-open"></i>';
                break;

            case 'undeletable' :
                $isUndeletable = get_post_meta( $post_id , self::$postTypeMetaPrefix . '_' . 'undeletable' , true );
                echo $isUndeletable ? '<i class="icon-undeletable-off fas fa-times-circle"></i>' : '<i class="icon-undeletable-on fas fa-check-circle"></i>';
                break;

            case 'childsEstateCount' :
                echo '<a href="/wp-admin/edit.php?post_type=' . $estatePostTypeName . '&post_parent=' . $post_id . '">';
                echo count($childPosts);
                echo '</a>';
                break;
        }
    }
}