<?php

namespace Blazemedia\Affiliation\AdminUserInterface\Buttons;

use Blazemedia\Affiliation\API\CachedApi;

/*
 *  Class AffiliateParse Button ( nuovo )
 *  
 *  Bottone e UI per la creazione degli shortcode dei link
 */
class AffiliateParseButton extends Button {

    function __construct() { 
        
        /** 
         * Set the name of the plugin 
         * >> affiliation_button.js
         * 
         * and the name of the ajax endpoint to call into plugin
         * >> affiliation_button_action
         */
        parent::__construct( 'affiliation_parse_button', 'affiliation_parse_button_action' , 'dialog-AffiliateParseButton.html');       
    }

    
    public function addFieldsToDialog() : array { return [

            [
                'name' => 'ApiRenderingManager',
                'value' => BLZ_API_RENDERING_MANAGER
            ],
            [
                'name' => 'ApiLinkProvider',
                'value' => BLZ_API_LINK_PROVIDER
            ],
            [
                'name'  => 'formatId',
                'value' => $this->getFormatId('button','pbtn')
            ],
            [
                'name'  => 'home_url',
                'value' => get_home_url()
            ],
        ]; 
    }


    public function getFormatId( string $type, string $code ) {

        $api = CachedApi::getInstance();

        $action = [ 'button'=>'buttons' ][ $type ];

        $buttons = json_decode( $api->get( BLZ_API_FORMAT_PROVIDER."{$action}/") );

        if( !is_array($buttons) ) {

            echo '<div>Errore di comunicazione con il server. Riprovare </div>'; die;
        }

        $buttons = array_filter( $buttons, function( $button ) use( $code ) {
                return $button->code == $code;
            } 
        );

        return array_shift( $buttons )->id;        
    }    
}