<?php

namespace Fab\Controller;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

use Fab\Interfaces\JIT_Interface;
use Fab\View;
use Fab\Helper\FAB_Template;

/**
 * Templates controller
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class Templates extends Base implements JIT_Interface {

    /**
     * Register submenu page
     *
     * @return void
     */
    public function register_submenu_page() {
        add_submenu_page(
            'edit.php?post_type=fab',
            __( 'Add New FAB', 'floating-awesome-button' ),
            __( 'Add New FAB', 'floating-awesome-button' ),
            'manage_options',
            'floating-awesome-button-templates',
            array( $this, 'page_template' ),
            2
        );
    }

    /**
     * Remove add new fab submenu
     *
     * @return void
     */
    public function remove_add_new_fab_submenu() {
        global $submenu;

        // Check if the 'fab' post type submenu exists.
        if ( isset( $submenu['edit.php?post_type=fab'] ) ) {
            // Loop through the submenu items to find the "Add New" link.
            foreach ( $submenu['edit.php?post_type=fab'] as $key => $item ) {
                // Check if the submenu item is the "Add New" link.
                if ( 'post-new.php?post_type=fab' === $item[2] ) {
                    // Remove the "Add New" submenu item.
                    unset( $submenu['edit.php?post_type=fab'][ $key ] );
                    break; // Exit the loop once the item is found.
                }
            }
        }
    }

    /**
     * Page Template
     *
     * @return void
     */
    public function page_template() {
        // Make sure REST API endpoint is loaded, for some reason it's not loaded in submenu page, this could be come from WP error.
        if ( ! did_action( 'rest_api_init' ) ) {
            \Fab\Api\Templates::get_instance()->register_rest_routes();
        }

        // Add custom thank you page.
        add_filter( 'admin_footer_text', array( \Fab\Controller\Custom_Footer::get_instance(), 'get_admin_footer_text' ) );

        // Get all json files in templates folder.
        $templates = glob( FAB_PLUGIN_PATH . 'templates/*.json' );
        $templates = array_map(
            function ( $file ) {
                return str_replace( '.json', '', basename( $file ) );
            },
            $templates
        );
        $templates = \Fab\Helper\FAB_Template::getInstance()->transform_metabox_templates( $templates );

        // Localize templates.
        \FAB()->Helper->wp_enqueue_script_component( 'fab-templates-component', 'assets/components/templates/main.js', array(), FAB_VERSION, false );
        wp_localize_script(
            'fab-templates-component',
            'FAB_TEMPLATES',
            array(
                'nonce'       => wp_create_nonce( 'wp_rest' ),
                'templates'   => apply_filters( 'fab_templates', $templates ),
                'url'         => array(
                    'contact'       => admin_url( 'edit.php?post_type=fab&page=floating-awesome-button-setting-contact' ),
                    'documentation' => \FAB()->Helper->get_documentation( '' ), // We set empty string because we will generate it dynamically in frontend.
                    'templatehub'   => TEMPLATEHUB_URL,
                ),
                'loading_gif' => FAB_PLUGIN_URL . 'assets/img/loading.gif',
                'labels'      => array(
                    'loading'                     => __( 'Loading...', 'floating-awesome-button' ),
                    'add_new'                     => __( 'Add New', 'floating-awesome-button' ),
                    'learn_more'                  => __( 'Learn More', 'floating-awesome-button' ),
                    'add_integration'             => __( 'Add Integration', 'floating-awesome-button' ),
                    'import'                      => __( 'Import', 'floating-awesome-button' ),
                    'import_title'                => __( 'Import Template', 'floating-awesome-button' ),
                    'import_description'          => __( 'Import your custom template', 'floating-awesome-button' ),
                    'download_title'              => __( 'Download Template', 'floating-awesome-button' ),
                    'download_more'               => __( 'Download more templates', 'floating-awesome-button' ),
                    'page'                        => __( 'Page', 'floating-awesome-button' ),
                    'of'                          => __( 'of', 'floating-awesome-button' ),
                    'templates_total'             => __( 'templates total', 'floating-awesome-button' ),
                    'next'                        => __( 'Next', 'floating-awesome-button' ),
                    'previous'                    => __( 'Previous', 'floating-awesome-button' ),
                    'no_results'                  => __( 'No templates found matching your search.', 'floating-awesome-button' ),
                    'request_template'            => __( 'Request Template', 'floating-awesome-button' ),
                    'request_template_persuasion' => __( 'Can\'t find what you\'re looking for? Let us know and we\'ll help create it.', 'floating-awesome-button' ),
                    'upgrade'                     => __( 'Required Upgrade', 'floating-awesome-button' ),
                ),
            )
        );

        // Render template.
        View::RenderStatic( 'Backend.templates' );
    }

    /**
     * Custom fab page title action url
     *
     * @param string $url The url.
     * @param string $path The path.
     * @param int    $blog_id The blog id.
     * @return string
     */
    public function custom_fab_page_title_action_url( $url, $path, $blog_id ) {
        // Check if we're on the edit.php page for the 'fab' post type.
        if ( 'post-new.php?post_type=fab' === $path ) {
            $url = admin_url( 'edit.php?post_type=fab&page=floating-awesome-button-templates' );
        }
        return $url;
    }

    /**
     * Localize templates url
     *
     * @param array $localize The localize.
     * @return array
     */
    public function localize_templates_url( $localize ) {
        $localize['templates_url'] = admin_url( 'edit.php?post_type=fab&page=floating-awesome-button-templates' );
        return $localize;
    }

    /*
    |--------------------------------------------------------------------------
    | Fulfill implemented interface contracts
    |--------------------------------------------------------------------------
     */

    /**
     * JIT method.
     *
     * @return void
     */
    public static function jit() {
        // Localize templates url.
        add_filter( 'fab_backend_enqueue_localize', array( __CLASS__, 'jit_localize_templates_url' ) );

        // Register new submenu page.
        add_action( 'admin_menu', array( __CLASS__, 'jit_register_submenu_page' ) );

        // Change submenu add new fab page title action url.
        add_action( 'admin_menu', array( __CLASS__, 'jit_remove_add_new_fab_submenu' ) );

        // Custom add new fab page title action url.
        add_filter( 'admin_url', array( __CLASS__, 'jit_custom_fab_page_title_action_url' ), 10, 3 );
    }
}
