<?php

namespace WPIS;

class EstateEpcLabelShortcode {

    private static $shortcode = 'wpis-epc-label';

    static public function init() {

        $class = new self();

        add_shortcode( self::$shortcode, [$class, 'generateShortcode'] );
    }

    public function generateShortcode($atts = false, $content = null) {

        global $post;

        $filter = true;
        $showUnit = true;
        $supportedFilters = ['false', 'capitalize', 'uppercase', 'decimal', 'number', 'price', 'yes/no'];

        $language = substr( get_bloginfo ( 'language' ), 0, 2 );

        if( !isset($atts['meta']) ){
            return $this->generateError('No meta provided');
        }
        if( isset($atts['wrap']) && !strstr($atts['wrap'], '%s') ){
            return $this->generateError('No string replacement key found, you must add %s in the wrapper');
        };
        if( isset($atts['wrap']) && $content ){
            return $this->generateError('wrap option is not supported if content is used');
        };
        if( $content && !strstr($content, '%s')  ){
            return $this->generateError('No string replacement key found, you must add %s in the wrapper');
        };
        if( isset($atts['format']) && !in_array($atts['format'], $supportedFilters) ){
            return $this->generateError('Format not valid, supported format : ' . implode(', ', $supportedFilters));
        };

        // Fallback to support GridBuilder templates
        if( function_exists('wpgb_get_post') && !empty(wpgb_get_post()->ID) ){
            $post = wpgb_get_post();
        }

        if( isset($atts['format']) ){
            $filter = $atts['format'] === 'false' ? false : $atts['format'];
        }

        if( isset($atts['unit']) && $atts['unit'] === 'false' ){
            $showUnit = false;
        }

        if( !$filter && !$showUnit ){
            $value = EstateProperties::getValue($post->ID, 'wpis_' . $atts['meta'], $language);
        }
        else {
            $value = EstateProperties::getFormattedValue($post->ID, 'wpis_' . $atts['meta'], $language, $filter, $showUnit );
        }

        if( isset($atts['wrap']) ){
            $buffer = sprintf($atts['wrap'], $value);
        }
        elseif( $content ){
            $buffer = sprintf($content, $value);
        }
        else {
            $buffer = $value;
        }

        return $buffer;
    }

    public function generateError( $message ){
        return sprintf('[ %s ]', self::$shortcode) . ' : ' .  $message;
    }
}