<?php

namespace Webien\Setup;
use StoutLogic\AcfBuilder\FieldsBuilder;

/*
 * Clean up some WP stuff and add ACF options for them
 */

class CleanUp
{

    static $acfGroup;

    public static function init()
    {
        // Start ACF section, (Optional stuff)
        self::$acfGroup = new FieldsBuilder(
            'webien_cleanup_options', ['title' => __('Diverse inställningar', 'webien')]
        );

        //self::limitRevisions();
        self::disableComments();
        self::removeEmojis();
        self::moveMenuNav();
        self::fixBrokenJetAssets();
        self::miscOptions();

        // End ACF section
        self::$acfGroup
            ->setLocation('options_page', '==', 'acf-options-webien');
            acf_add_local_field_group(self::$acfGroup->build());


        // Sanitize filenames before upload to remove non latin characters
        add_filter('sanitize_file_name', [__CLASS__, 'sanitizeFileNames'], 10);

        // Mime types
        add_filter('upload_mimes', [__CLASS__, 'fixMimeTypes']);

        // Fix SVG srcset urls (double slash) on wordpress standard image
        add_filter('wp_calculate_image_srcset', [__CLASS__, 'svgSrcset'], 10, 5);

        // Clear cache on ACF save
        add_action('acf/save_post', [__CLASS__, 'clear_elementor_cache'], 20);

        // Remove Gutenberg Block Library CSS from loading on the frontend
        if(filter_var(get_option('options_webien_disable_gutenberg_css'), FILTER_VALIDATE_BOOLEAN)){
            add_action( 'wp_enqueue_scripts', [__CLASS__, 'remove_gutenberg_block_styles'], 100 );
        }

        // Remove some API endpoints for general security
        add_filter( 'rest_endpoints', [__CLASS__, 'remove_rest_api_endpoint'] );

        /*
        // Remove update notifications
        if(defined('WP_ENV') && WP_ENV !== 'development'){
            add_filter('pre_site_transient_update_core', [__CLASS__, 'hideUpdates']);
            add_filter('pre_site_transient_update_plugins', [__CLASS__, 'hideUpdates']);
            add_filter('pre_site_transient_update_themes', [__CLASS__, 'hideUpdates']);
        }
        */


        add_action( 'wp_ajax_webien_remove_option', [__CLASS__, 'removeDbOption'] );
        //add_action( 'wp_ajax_nopriv_webien_remove_option', [__CLASS__, 'removeDbOption'] );
    }


    private static function hideUpdates(){
        global $wp_version;
        return(object) array('last_checked'=> time(),'version_checked'=> $wp_version);
    }

    public static function removeDbOption(){
        if(!current_user_can('manage_options')){
            wp_die();
        }

        $option = sanitize_text_field($_POST['option_name']);
        if($option){
            $success = delete_option($option);
        }

        wp_send_json(['success' => $success]);

        wp_die();
    }


    private static function limitRevisions()
    {
        self::$acfGroup
            ->addNumber('webien_post_revisions', [
                'label' => __('Antal sparade revisioner på poster', 'webien'),
                'instructions' => __('Antal revisioner som ska sparas i databasen. (Standard: 10)', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'default_value' => 10,
                'min' => 0,
                'max' => 50,
                'step' => 5,
            ]);

        $revisions = get_option('options_webien_post_revisions') ?: 10;
        if(!defined('WP_POST_REVISIONS')){
            define( 'WP_POST_REVISIONS', intval($revisions) );
        }

    }



    private static function miscOptions()
    {
        // Post scheduling
        self::$acfGroup
            ->addTrueFalse('webien_use_scheduling', [
                'label' => __('Schemaläggning', 'webien'),
                'instructions' => __('Möjlighet att schemalägga poster. Kräver ett cronjobb på servern. (Standard: Inaktivt)', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'message' => __('Använd schemaläggning', 'webien'),
                'default_value' => 0,
            ]);

        self::$acfGroup
            ->addNumber('webien_scheduling_offset', [
                'label' => __('Schemaläggning - justering', 'webien'),
                'instructions' => __('Justera tid från serverns klocka i timmar. Serverns klocka vid sidladdning: <b>', 'webien') . date('H:i') . '</b>',
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'default_value' => 1,
                'min' => 0,
                'max' => 10,
            ]);

        // Show animation settings
        self::$acfGroup
            ->addTrueFalse('webien_use_animation_settings', [
                'label' => __('Animeringshjälp', 'webien'),
                'instructions' => __('Adderar en inställning under Advanced tabben för att jobba med scroll animeringar.', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'message' => __('Visa animeringshjälp', 'webien'),
                'default_value' => 0,
            ]);

        // Gutenberg CSS
        self::$acfGroup
            ->addTrueFalse('webien_disable_gutenberg_css', [
                'label' => __('Gutenberg CSS', 'webien'),
                'instructions' => __('Om inte Gutenberg editorn ska användas någonstans är det bra att exkludera all CSS som den lägger på för bättre performance.', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'message' => __('Ta bort Gutenberg CSS', 'webien'),
                'default_value' => 1,
            ]);

        // WCAG Jump to content
        self::$acfGroup
            ->addTrueFalse('webien_jump_to_content_wcag', [
                'label' => __('Hoppa till innehåll knapp', 'webien'),
                'instructions' => __('Inkluderar en WCAG knapp som går att tabba till för att snabbare nå innehållet.', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'message' => __('Använd', 'webien'),
                'default_value' => 1,
            ]);

        // API routes cleanup
        self::$acfGroup
            ->addTrueFalse('webien_disable_general_api_endpoints', [
                'label' => __('Blockera API endpoints', 'webien'),
                'instructions' => __('Tar bort åtkomst till några publika endpoints av säkerhetsskäl. De endpoints som inaktiveras är:<br><small>/wp-json/wp/v2/users<br>/wp-json/wp/v2/users/[ID]<br>/wp-json/wp/v2/media</small>', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'message' => __('Blockera', 'webien'),
                'default_value' => 1,
            ]);


        // Widget remover
        self::$acfGroup
            ->addTrueFalse('webien_hide_all_widgets', [
                'label' => __('Dölj Webien widgets', 'webien'),
                'instructions' => __('Döljer de legacy widgets som finns i webien pluginet, till fördel för widgets i Webien Suite som ska ersätta dessa. Dessa widgets finns dock kvar i bakgrunden ifall de skulle finnas aktiva någonstans.', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '100',
                ],
                'message' => __('Dölj webien legacy widgets', 'webien'),
                'default_value' => 0,
            ]);


        // WP Options remover
        self::$acfGroup
            ->addMessage('webien_wp_options_remover', 'Message', [
                'label' => __('Rensa wp_options fält', 'webien'),
                'required' => 0,
                'wrapper' => [
                    'width' => '100',
                ],
                'message' => __('Används för att ta bort rader från wp_options tabellen. Detta kan behövas ibland då gamla autoloadade fält finns kvar och skräpar. <b>Använd denna bara om du vet vad du gör.</b>', 'webien') . '<div class="options-remover"><textarea id="webien_option_name" rows="1">' . __('option_name', 'webien') . '..</textarea><button id="webien_remove_option" class="button button-secondary" type="button">' . __('Ta bort', 'webien') . '</button></div>',
                //'new_lines' => 'wpautop',
                'esc_html' => 0,
            ]);

    }





    private static function disableComments()
    {
        self::$acfGroup
            ->addTrueFalse('webien_disable_comments', [
                'label' => __('Kommentarer', 'webien'),
                'instructions' => __('Möjlighet att kunna visa ut och kommentera på poster. (Standard: Inaktivt)', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'message' => __('Stäng av kommentarer', 'webien'),
                'default_value' => 1,
            ]);

        $inactivateComments = get_option('options_webien_disable_comments') ?: false;

        if($inactivateComments){
            // Taken from this thread -> https://gist.github.com/mattclements/eab5ef656b2f946c4bfb

            add_action('admin_init', function () {
                // Redirect any user trying to access comments page
                global $pagenow;

                if ($pagenow === 'edit-comments.php') {
                    wp_redirect(admin_url());
                    exit;
                }
                if ( $pagenow == 'options-discussion.php' ) {
                    wp_redirect(admin_url());
                    exit;
                }

                // Remove comments metabox from dashboard
                remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');

                // Disable support for comments and trackbacks in post types
                foreach (get_post_types() as $post_type) {
                    if (post_type_supports($post_type, 'comments')) {
                        remove_post_type_support($post_type, 'comments');
                        remove_post_type_support($post_type, 'trackbacks');
                    }
                }
            });

            // Close comments on the front-end
            add_filter('comments_open', '__return_false', 20, 2);
            add_filter('pings_open', '__return_false', 20, 2);

            // Hide existing comments
            add_filter('comments_array', '__return_empty_array', 10, 2);

            // Remove comments page in menu
            add_action('admin_menu', function () {
                remove_menu_page('edit-comments.php');
                remove_submenu_page( 'options-general.php', 'options-discussion.php' );

            });

            // Remove comments links from admin bar
            add_action('init', function () {
                if (is_admin_bar_showing()) {
                    remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
                }
            });

            // Remove admin var icon menu
            add_action('wp_before_admin_bar_render', function() {
                global $wp_admin_bar;
                $wp_admin_bar->remove_menu('comments');
            });

        }
    }


    public static function remove_gutenberg_block_styles(){
        wp_dequeue_style( 'wp-block-library' );
        wp_dequeue_style( 'wp-block-library-theme' );
        wp_dequeue_style( 'wc-block-style' ); // Remove WooCommerce block CSS
    }



    private static function removeEmojis(){
        self::$acfGroup
            ->addTrueFalse('webien_remove_emojis', [
                'label' => __('Emojis', 'webien'),
                'instructions' => __('Möjlighet att använda emojis i textredigerare etc. (Standard: Inaktivt)', 'webien'),
                'required' => 0,
                'conditional_logic' => [],
                'wrapper' => [
                    'width' => '50',
                ],
                'message' => __('Stäng av emojis', 'webien'),
                'default_value' => 1,
            ]);

        $removeEmojis = get_option('options_webien_remove_emojis') ?: false;

        if($removeEmojis){
            remove_action('wp_head', 'print_emoji_detection_script', 7);
            remove_action('wp_print_styles', 'print_emoji_styles');
            remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
            remove_action( 'admin_print_styles', 'print_emoji_styles' );
        }

    }



    private static function moveMenuNav(){
        // Removes nav-menu and adds a new menu page
        add_action('admin_menu', function(){
            global $submenu, $menu;

            if (isset($submenu['themes.php'])) {
                foreach ($submenu['themes.php'] as $key => $item) {
                    if ($item[2] === 'nav-menus.php') {
                        unset($submenu['themes.php'][$key]);
                    }
                }
            }
            $user = wp_get_current_user();
            if (in_array('editor', $user->roles)) {
                unset($menu[60]);
            }
            if ( empty ( $GLOBALS['admin_page_hooks']['nav-menus.php'] ) ){
                add_menu_page(__('Menus'), __('Menus'), 'delete_others_pages', 'nav-menus.php', '', 'dashicons-list-view', 61);
            }
        });

        // Changes the parent page for nav-menus
        add_filter('parent_file', function($parent_file){
            global $current_screen;
            // Set correct active/current menu and submenu in the WordPress Admin menu for the "example_cpt" Add-New/Edit/List
            if ($current_screen->base == 'nav-menus') {
                $parent_file = 'nav-menus.php';
            }
            return $parent_file;
        });

        // Fixes the problem where the capability is wrong
        add_filter('user_has_cap', function($caps, $cap, $args, $user){
            $url = $_SERVER['REQUEST_URI'];
            if (strpos($url, 'nav-menus.php') !== false && in_array('edit_theme_options', $cap) && in_array('editor', $user->roles)) {
                $caps['edit_theme_options'] = true;
            }
            return $caps;
        }, 20, 4);

    }

    public static function fixBrokenJetAssets(){
        add_filter( 'cherry_core_base_url', function($url){
            $arr = explode( '/web/', $url );
            if(isset($arr[1])){
                return home_url( '/' ) . $arr[1];
            }
            return $url;
        } );
        add_filter( 'cx_include_module_url', function($url){
            $arr = explode( '/web/', $url );
            if(isset($arr[1])){
                return home_url( '/' ) . $arr[1];
            }
            return $url;
        } );
    }

    public static function fixMimeTypes($mimes = []){

        $mimes['json'] = 'application/json';
        $mimes['svg'] = 'image/svg+xml';

        return $mimes;
    }

    public static function svgSrcset($sources, $size_array, $image_src, $image_meta, $attachment_id){

        foreach ($sources as $src) {
            $sources[$src['value']]['url'] = str_replace('uploads//', 'uploads/', $src['url']);
        }
        return $sources;
    }


    public static function sanitizeFileNames($filename) {

        $fileinfo = pathinfo($filename);

        if(isset($fileinfo['extension']) && isset($fileinfo['filename'])){
            // Handle S3 upload temp file
            if($fileinfo['extension']  === 'tmp'){
                return $filename;
            }

            // Exchange some characters, remove the rest
            $sanitized = preg_replace('/[åäÅÄ]/', 'a', $fileinfo['filename']);
            $sanitized = preg_replace('/[öÖ]/', 'o', $sanitized);

            // Now filter out anything but a-z and dashes
            $friendly_filename = preg_replace('/[^a-zA-Z0-9-_]/', '', $sanitized);

            return strtolower( $friendly_filename . '.' . $fileinfo['extension'] );
        }

        return $filename;

    }

    public static function remove_rest_api_endpoint($rest_endpoints) {

        $disable = get_option('options_webien_disable_general_api_endpoints', true); // Set to true if not set in DB
        $disable = filter_var($disable, FILTER_VALIDATE_BOOLEAN);
        if(!$disable){
            return $rest_endpoints;
        }

        if( isset( $rest_endpoints[ '/wp/v2/users' ] ) ) {
            unset( $rest_endpoints[ '/wp/v2/users' ] );
        }
        if( isset( $rest_endpoints[ '/wp/v2/users/(?P<id>[\d]+)' ] ) ) {
            unset( $rest_endpoints[ '/wp/v2/users/(?P<id>[\d]+)' ] );
        }
        if( isset( $rest_endpoints[ '/wp/v2/media' ] ) ) {
            unset( $rest_endpoints[ '/wp/v2/media' ] );
        }
        return $rest_endpoints;
    }


    public static function clear_elementor_cache(){
        (new \Elementor\Core\Files\Manager())->clear_cache();
    }

}