<?php

// If this file is called directly, abort.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://wondercode.pro/
 * @since      1.0.0
 *
 * @package    YouTube_Automate
 * @subpackage YouTube_Automate/admin
 */
/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    YouTube_Automate
 * @subpackage YouTube_Automate/admin
 * @author     Mcurly <contact@wondercode.pro>
 */
class YTAM_Admin {
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param      string    $plugin_name       The name of this plugin.
     * @param      string    $version    The version of this plugin.
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
        // Menu
        add_action( 'admin_menu', array($this, 'add_settings_menu') );
        add_action( 'admin_init', array($this, 'save_settings') );
        // Adds a settings link to the plugins page
        $exploded_path = explode( '/', str_replace( WP_PLUGIN_DIR . '/', '', __DIR__ ) );
        $plugin_folder_name = reset( $exploded_path );
        add_filter( 'plugin_action_links_' . ytam_fs()->get_plugin_basename(), array(&$this, 'add_link_parameters') );
        /* Gutenberg Block */
        // Scripts for Block & Translations
        add_action( 'init', array(&$this, 'register_ytam_block') );
        add_action( 'enqueue_block_editor_assets', array(&$this, 'enqueue_style_block') );
        // Gutenberg Block : Searching videos with APIs
        add_action( 'wp_ajax_block_searching_videos', array(&$this, 'block_searching_videos') );
        add_action( 'wp_ajax_nopriv_block_searching_videos', array(&$this, 'block_searching_videos') );
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles( $hook ) {
        // Main plugin CSS
        if ( $hook == 'toplevel_page_youtube-automate' ) {
            wp_enqueue_style(
                'ytam-style',
                plugin_dir_url( __FILE__ ) . 'css/youtube-automate-admin.css',
                array(),
                $this->version,
                'all'
            );
            wp_enqueue_style(
                'jquery-ui',
                plugin_dir_url( __FILE__ ) . 'css/jquery-ui.min.css',
                array(),
                $this->version,
                'all'
            );
        }
        // YTAM Admin Dashboard
        if ( $hook == 'toplevel_page_youtube-automate' ) {
            wp_enqueue_style(
                'plugins-bundle',
                plugin_dir_url( __FILE__ ) . 'css/plugins.bundle.css',
                array(),
                $this->version,
                'all'
            );
            wp_enqueue_style(
                'style.bundle',
                plugin_dir_url( __FILE__ ) . 'css/style.bundle.css',
                array(),
                $this->version,
                'all'
            );
            wp_enqueue_style(
                'theme-base-light',
                plugin_dir_url( __FILE__ ) . 'css/themes/layout/header/base/light.css',
                array(),
                $this->version,
                'all'
            );
            wp_enqueue_style(
                'theme-menu-light',
                plugin_dir_url( __FILE__ ) . 'css/themes/layout/header/menu/light.css',
                array(),
                $this->version,
                'all'
            );
            wp_enqueue_style(
                'theme-brand-dark',
                plugin_dir_url( __FILE__ ) . 'css/themes/layout/brand/dark.css',
                array(),
                $this->version,
                'all'
            );
            wp_enqueue_style(
                'theme-aside-dark',
                plugin_dir_url( __FILE__ ) . 'css/themes/layout/aside/dark.css',
                array(),
                $this->version,
                'all'
            );
        }
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts( $hook ) {
        wp_enqueue_script(
            $this->plugin_name,
            esc_url( plugin_dir_url( __FILE__ ) ) . 'js/youtube-automate-admin.js',
            array('jquery'),
            $this->version,
            false
        );
        if ( $hook == 'toplevel_page_youtube-automate' ) {
            wp_enqueue_script(
                'prismjs-bundle',
                plugin_dir_url( __FILE__ ) . 'js/prismjs.bundle.js',
                array('jquery'),
                $this->version,
                true
            );
            wp_enqueue_script(
                'scripts-bundle',
                plugin_dir_url( __FILE__ ) . 'js/scripts.bundle.js',
                array('jquery'),
                $this->version,
                true
            );
            wp_enqueue_script(
                'common-ytam',
                plugin_dir_url( __FILE__ ) . 'js/common-ytam.js',
                array('jquery'),
                $this->version,
                true
            );
        }
    }

    public function enqueue_style_block() {
        wp_enqueue_style(
            'ytam-images-editor-style',
            plugins_url( 'blocks/youtube-automate/build/youtube-automate.css', __FILE__ ),
            array(),
            filemtime( plugin_dir_path( __FILE__ ) . 'blocks/youtube-automate/build/youtube-automate.css' )
        );
    }

    // Add settings sub-menu in the Comments menu
    public function add_settings_menu() {
        add_menu_page(
            esc_html__( 'Easy YouTube Automate Options', 'easy-youtube-automate' ),
            // Page title
            esc_html__( 'Easy YouTube Automate', 'easy-youtube-automate' ),
            // Menu title
            'manage_options',
            // Capability required to access the page
            'youtube-automate',
            // Page slug
            array(&$this, 'show_settings_page'),
            // display the page
            'dashicons-youtube'
        );
    }

    /**
     * Display submenus
     *
     * @since    1.0.0
     */
    public function get_submenu( $title = 'Submenu', $slug = 'dashboard', $icon = 'default.png' ) {
        $url = explode( '?', esc_url_raw( add_query_arg( array() ) ) );
        $no_query_args = $url[0];
        $current_url = remove_query_arg( 'ids_ytam_generation', add_query_arg( 'module', $slug, $this->get_current_url() ) );
        if ( isset( $_GET['module'] ) ) {
            $current_module = sanitize_text_field( $_GET['module'] );
        } else {
            // Default Tab
            $current_module = 'dashboard';
        }
        $item_class = 'menu-item menu-item-submenu ';
        if ( $current_module == $slug ) {
            $item_class .= 'menu-item-open menu-item-here ';
        }
        // Exception with upgrade page
        if ( 'upgrade' == $slug ) {
            $current_url = get_admin_url() . 'admin.php?page=ytam_comments-pricing';
        }
        ?>
		<li class="<?php 
        echo esc_html( $item_class );
        ?>" data-menu-toggle="hover">
		    <a href="<?php 
        echo esc_url( $current_url );
        ?>" class="menu-link">
		        <img src="<?php 
        echo esc_url( plugin_dir_url( __FILE__ ) . '/img/' . $icon );
        ?>" class="icon-dashboard" width="24px" height="24px" />
		        <span class="menu-text"><?php 
        echo esc_html( $title );
        ?></span>
		    </a>
		</li>
	<?php 
    }

    /**
     * Get current url
     *
     * @since    1.0.0
     */
    public function get_current_url() {
        // Sanitize the HTTP_HOST to prevent XSS and other vulnerabilities
        $host = esc_url_raw( $_SERVER['HTTP_HOST'] );
        $requested_url = $host;
        // Sanitize the REQUEST_URI to ensure it does not contain harmful inputs
        $uri = esc_url_raw( $_SERVER['REQUEST_URI'] );
        $requested_url .= $uri;
        return $requested_url;
    }

    /**
     * Save the form values
     *
     * @since    1.0.0
     */
    public function save_settings() {
        // Main settings admin panel
        register_setting( 'YTAM-settings', 'YTAM_settings' );
        // Logs
        register_setting( 'YTAM-logs', 'YTAM_logs' );
        require_once dirname( __FILE__ ) . '/partials/download_log.php';
        require_once dirname( __FILE__ ) . '/partials/delete_log.php';
    }

    private function sanitize_checkbox( $checked ) {
        // Boolean check
        return ( isset( $checked ) && true == $checked ? true : false );
    }

    /**
     * Launch Freemius
     *
     * @since    1.0.0
     */
    public function YTAM_freemius() {
        $ytam_freemius = ytam_fs();
        return $ytam_freemius;
    }

    /**
     * Function that will be called to display the settings page
     *
     * @since    1.0.0
     */
    public function show_settings_page() {
        do_action( 'ytam_before_options_panel' );
        require_once dirname( __FILE__ ) . '/partials/youtube-automate-admin-display.php';
    }

    /**
     * Default values for settings
     *
     * @since    1.0.0
     */
    public function default_options_main_settings( $never_set = FALSE ) {
        $wp_lang = get_bloginfo( 'language' );
        $relevanceLanguage = substr( $wp_lang, 0, 2 );
        $default_options = array(
            'youtube_apikey'    => '',
            'relevanceLanguage' => $relevanceLanguage,
            'order'             => 'relevance',
        );
        return $default_options;
    }

    /**
     * Default values for logs admin tabs
     *
     * @since    1.0.0
     */
    public function default_options_logs_settings( $never_set = FALSE ) {
        $default_options = array(
            'logs_enable' => '',
        );
        return $default_options;
    }

    /**
     * Create file for logs
     *
     * @since    1.0.0
     */
    private function log_file( $check = false ) {
        // Get upload folder
        $upload_dir = wp_upload_dir();
        $upload_base_dir = $upload_dir['basedir'];
        $filename = $upload_base_dir . '/youtube-automate/logs/';
        $files = @scandir( $filename );
        $result = '';
        if ( !empty( $files ) ) {
            foreach ( $files as $key => $value ) {
                if ( !in_array( $value, array('.', '..'), true ) ) {
                    if ( !is_dir( $value ) && strstr( $value, '.log' ) ) {
                        $result = $value;
                    }
                }
            }
        }
        if ( true == $check && empty( $result ) ) {
            return false;
        }
        if ( empty( $result ) ) {
            $result = 'ytam-' . wp_generate_password( 14, false, false ) . '.log';
        }
        return $result;
    }

    /**
     * Create file for logs
     *
     * @since    1.0.0
     */
    public function monolog_call() {
        $main_logs = get_option( 'YTAM_logs' );
        // Check if logs enabled
        if ( !empty( $main_logs['logs_enable'] ) && true == esc_html( $main_logs['logs_enable'] ) ) {
            require_once dirname( __FILE__ ) . '/partials/monolog/vendor/autoload.php';
            $log = new Monolog\Logger('ytam_logger');
            $logfile = $this->log_file();
            // Get upload folder
            $upload_dir = wp_upload_dir();
            $upload_base_dir = $upload_dir['basedir'];
            $filename = $upload_base_dir . '/youtube-automate/logs/' . $logfile;
            // Now add some handlers
            $log->pushHandler( new Monolog\Handler\StreamHandler($filename, Monolog\Logger::DEBUG) );
            $log->pushHandler( new Monolog\Handler\FirePHPHandler() );
        } else {
            require_once dirname( __FILE__ ) . '/partials/monolog/nologs.php';
            $log = new YTAM_Nolog();
        }
        return $log;
    }

    /**
     * Adds a settings link to the plugins page
     *
     * @since    1.0.0
     */
    public function add_link_parameters( $links ) {
        $settings_link = '<a href="admin.php?page=youtube-automate">' . esc_html__( 'Settings', 'easy-youtube-automate' ) . '</a>';
        array_push( $links, $settings_link );
        return $links;
    }

    /**
     * Register YTAM Gutenberg Block
     *
     * @since    1.0.0
     */
    public function register_ytam_block() {
        $asset_file = (include plugin_dir_path( __FILE__ ) . 'blocks/youtube-automate/build/index.asset.php');
        wp_register_script(
            'ytam-images-script',
            plugins_url( 'blocks/youtube-automate/build/index.js', __FILE__ ),
            $asset_file['dependencies'],
            $asset_file['version'],
            array(
                'in_footer' => true,
            )
        );
        register_block_type( 'ytam/youtube-automate', array(
            'editor_script' => 'ytam-images-script',
        ) );
        $options = wp_parse_args( get_option( 'YTAM_settings' ), $this->default_options_main_settings( TRUE ) );
        if ( empty( $options['youtube_apikey'] ) ) {
            $apikey_filled = false;
        } else {
            $apikey_filled = true;
        }
        wp_localize_script( 'ytam-images-script', 'ytamAjax', array(
            'ajax_url'      => admin_url( 'admin-ajax.php' ),
            'admin_url'     => admin_url(),
            'apikey_filled' => $apikey_filled,
            'nonce'         => wp_create_nonce( 'ytam_gutenberg_block' ),
        ) );
        // Locate character strings
        wp_set_script_translations( 'ytam-images-script', 'easy-youtube-automate', plugin_dir_path( __DIR__ ) . 'languages' );
        /* Translations for Gutenberg block */
        load_plugin_textdomain( 'easy-youtube-automate', false, plugin_dir_path( __DIR__ ) . 'languages' );
    }

    /**
     * Search YTAM Gutenberg Block
     *
     * @since    1.0.0
     */
    public function block_searching_videos() {
        $ytam_options = get_option( 'YTAM_settings' );
        // Check the nonce
        check_ajax_referer( 'ytam_gutenberg_block', 'nonce' );
        $search_term = sanitize_text_field( $_GET['search'] );
        $index = intval( $_GET['index'] );
        $id = intval( $_GET['id'] );
        if ( FALSE === get_post_status( $id ) ) {
            wp_send_json_error( 'Error with post ID.' );
        }
        $apiKey = esc_html( $ytam_options['youtube_apikey'] );
        $maxResults = 50;
        // Appeler la fonction et récupérer les résultats
        $result = $this->searchYouTube( $apiKey, $search_term, $maxResults );
        $log = $this->monolog_call();
        $log->info( 'Search videos with term "' . $search_term . '"', array(
            'post' => $id,
        ) );
        // Get results
        if ( $result && isset( $result['items'] ) ) {
            foreach ( $result['items'] as $video ) {
                $url = 'https://img.youtube.com/vi/' . $video['id']['videoId'] . '/mqdefault.jpg';
                $video['urlThumb'] = $url;
                $videos[] = $video;
            }
        } else {
            $results_thumbs = false;
        }
        if ( $results_thumbs === false ) {
            wp_send_json_error( 'Error connecting to the API.' );
        } else {
            wp_send_json_success( array(
                'results' => $videos,
            ) );
        }
    }

    /**
     * YouTube search function
     *
     * @since    1.0.0
     */
    public function searchYouTube( $apiKey, $keyword, $maxResults ) {
        $options = wp_parse_args( get_option( 'YTAM_settings' ), $this->default_options_main_settings( TRUE ) );
        if ( !isset( $options['relevanceLanguage'] ) ) {
            $wp_lang = get_bloginfo( 'language' );
            $relevanceLanguage = substr( $wp_lang, 0, 2 );
        } else {
            $relevanceLanguage = esc_html( $options['relevanceLanguage'] );
        }
        if ( !isset( $options['order'] ) ) {
            $order = 'relevance';
        } else {
            $order = esc_html( $options['order'] );
        }
        // Sending a request to the Google Translate API
        $response = @wp_remote_request( "https://www.googleapis.com/youtube/v3/search?part=snippet&type=video&q=" . urlencode( $keyword ) . "&maxResults=" . $maxResults . "&key=" . $apiKey . "&relevanceLanguage=" . $relevanceLanguage . "&order=" . $order );
        // Check if the request was successful
        if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) != 200 ) {
            $list_results = false;
        } else {
            // Extract translation from a successful response
            $list_results = json_decode( wp_remote_retrieve_body( $response ), true );
        }
        return $list_results;
    }

}
