<?php

namespace Fab\Controller;

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

use Fab\Interfaces\JIT_Interface;
use Fab\Feature\Design;

/**
 * Backend hooks
 *
 * @package    Fab
 * @subpackage Fab/Controller
 */
class Backend extends Base implements JIT_Interface {

    /**
     * Handle plugin upgrade
     *
     * @param array $upgrader_object Upgrader object.
     * @param array $options Options.
     * @return void
     */
    public function upgrade_plugin( $upgrader_object, $options ) {
        try {
            $current_plugin_path_name = plugin_basename( FAB_PLUGIN_FILE_ENTRY );
            if ( 'update' === $options['action'] && 'plugin' === $options['type'] ) {
                foreach ( $options['plugins'] as $each_plugin ) {
                    if ( $each_plugin === $current_plugin_path_name ) {
                        $config = \FAB()->getConfig()->options;

                        // Update options.
                        update_option( 'fab_config', $config );
                    }
                }
            }
        } catch ( \Exception $e ) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log( $e->getMessage() );
        }
    }

    /**
     * Eneque scripts @backend
     *
     * @return  void
     */
    public function backend_enequeue() {
        /** Load Data */
        $options = \Fab\Plugin\Config::getInstance()->getConfig()->options;
        $screen  = \FAB()->Helper->getScreen();
        $screens = array(
            'fab_page_floating-awesome-button-setting',
            'fab_page_floating-awesome-button-templates',
        );
        $types   = array( 'fab' );

        /** Load Core Vendors */
        wp_enqueue_script( 'jquery' );
        wp_enqueue_script( 'jquery-ui-sortable' );
        wp_enqueue_style( 'wp-color-picker' );

        /** Load Inline Script */
        \FAB()->Helper->wp_enqueue_script( 'fab-backend', 'local/fab.js', array(), FAB_VERSION, true );
        wp_localize_script(
            'fab-backend',
            'FAB_PLUGIN',
            apply_filters(
                'fab_backend_enqueue_localize',
                array(
                    'name'           => FAB_NAME,
                    'version'        => FAB_VERSION,
                    'screen'         => FAB_SCREEN,
                    'path'           => json_decode( FAB_PATH ),
                    'premium'        => \Fab\Plugin\Helper::getInstance()->isPremiumPlan(),
                    'upgrade_url'    => \Fab\Plugin\Helper::getInstance()->getUpgradeURL(),
                    'production'     => \FAB()->getConfig()->production,
                    'description'    => \FAB()->getConfig()->description,
                    'fontsJsonUrl'   => plugin_dir_url( __DIR__ . '/../../../..' ) . 'fonts.json',
                    'options'        => $options,
                    'rest_url'       => esc_url_raw( rest_url() ),
                    'defaultOptions' => array(
                        'layout'   => Design::$layout,
                        'template' => Design::$template,
                        'font'     => Design::$font,
                    ),
                    'integrations'   => array(
                        'plugin' => apply_filters( 'fab_plugin_integrations', array() ),
                        'theme'  => apply_filters( 'fab_theme_integrations', array() ),
                    ),
                    'urls'           => array(
                        'upgrade'     => admin_url( 'edit.php?post_type=fab&page=floating-awesome-button-setting-pricing' ),
                        'loading_gif' => FAB_PLUGIN_URL . 'assets/img/loading.gif',
                    ),
                )
            )
        );

        /** Load Vendors */
        if ( isset( $options->fab_animation->enable ) && $options->fab_animation->enable ) {
            \FAB()->Helper->wp_enqueue_style( 'animatecss', 'vendor/animatecss/animate.min.css' );
        }
        if ( in_array( $screen->base, $screens )
            || ( isset( $screen->post->post_type )
            && in_array( $screen->post->post_type, $types ) ) ) {

            \FAB()->Helper->enqueue_vendor( 'backend' );
        }

        // Load Plugin Assets.
        \FAB()->Helper->wp_enqueue_style_sass( 'fab', 'assets/css/backend/style.scss' );
        \FAB()->Helper->wp_enqueue_script_typescript( 'fab', 'assets/ts/backend/plugin.ts', array( 'wp-color-picker' ), FAB_VERSION, true );

        // Load vite.
        if ( defined( 'HMR_DEV' ) && HMR_DEV ) {
            \FAB()->Helper->wp_enqueue_script( 'fab-vite', sprintf( 'http://localhost:%s/@vite/client', HMR_DEV_PORT ), array(), FAB_VERSION, true );
        }
    }

    /**
     * Add setting link in plugin page
     *
     * @param array $links Plugin links.
     * @return  array   Plugin links.
     */
    public function plugin_setting_link( $links ) {
        $slug = sprintf( '%s-setting', \FAB()->getSlug() );
        $text = __( 'Settings', 'floating-awesome-button' );
        return array_merge( $links, array( '<a href="edit.php?post_type=fab&page=' . $slug . '">' . $text . '</a>' ) );
    }

    /**
     * Plugin row meta references
     *
     * @param array  $plugin_meta Plugin meta.
     * @param string $plugin_file Plugin file.
     * @param array  $plugin_data Plugin data.
     * @param string $status Plugin status.
     * @return array Plugin meta.
     */
    public function plugin_row_meta_references( $plugin_meta, $plugin_file, $plugin_data, $status ) {
        if ( strpos( $plugin_file, sprintf( '%s.php', \FAB()->getSlug() ) ) !== false ) {
            $new_links = array(
                'blog'    => sprintf( '<a href="https://artistudio.xyz/blog" target="_blank">%s</a>', __( 'Blog', 'floating-awesome-button' ) ),
                'support' => sprintf( '<a href="https://wordpress.org/support/plugin/floating-awesome-button" target="_blank">%s</a>', __( 'Community Support', 'floating-awesome-button' ) ),
            );

            $plugin_meta = array_merge( $plugin_meta, $new_links );
        }
        return $plugin_meta;
    }

    /**
     * Add script tag attributes, for module scripts
     * - This is vite HMR
     *
     * @param string $tag Script tag.
     * @param string $handle Script handle.
     * @return string
     */
    public function add_script_tag_attributes( $tag, $handle ) {
        // Add module scripts.
        $handles = apply_filters( 'fab_module_scripts', array( 'fab-vite' ) );

        // Add type="module" to script tag.
        if ( in_array( $handle, $handles ) ) {
            $tag = str_replace( ' src=', ' type="module" src=', $tag );
        }

        return $tag;
    }

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

    /**
     * JIT method.
     *
     * @return void
     */
    public static function jit() {
        // Handle plugin upgrade.
        add_action( 'upgrader_process_complete', array( __CLASS__, 'jit_upgrade_plugin' ), 10, 2 );

        // Enqueue backend plugins assets.
        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'jit_backend_enequeue' ), 10, 0 );

        // Add setting link for plugin in plugins page.
        add_action( 'plugin_action_links_floating-awesome-button/floating-awesome-button.php', array( __CLASS__, 'jit_plugin_setting_link' ), 10, 1 );

        // Add references links Documentations & Tutorials.
        add_filter( 'plugin_row_meta', array( __CLASS__, 'jit_plugin_row_meta_references' ), 10, 4 );

        // Customize script loader to load vite HMR.
        add_filter( 'script_loader_tag', array( __CLASS__, 'jit_add_script_tag_attributes' ), 10, 2 );
    }
}
