<?php
namespace IntentDeep\VirtualFiles\Controllers;

use IntentDeep\VirtualFiles\Core\Cache;

/**
 * Admin Bar Controller - Adds Virtual Files menu to WordPress admin bar
 */
class AdminBarController {

    /**
     * Initialize admin bar hooks
     */
    public function __construct() {
        add_action('admin_bar_menu', [$this, 'add_admin_bar_menu'], 100);
        add_action('wp_head', [$this, 'add_admin_bar_styles']);
        add_action('admin_head', [$this, 'add_admin_bar_styles']);
    }

    /**
     * Add custom styles for admin bar menu
     */
    public function add_admin_bar_styles(): void {
        if (!is_admin_bar_showing()) {
            return;
        }

        $custom_css = "
            #wpadminbar #wp-admin-bar-virtual-files > .ab-item .ab-icon {
                width: 20px;
                height: 20px;
                margin-right: 5px;
            }

            #wpadminbar #wp-admin-bar-virtual-files > .ab-item .ab-icon:before {
                content: \"\\f121\";
                font-family: dashicons;
                font-size: 20px;
                line-height: 1;
                display: inline-block;
                vertical-align: middle;
                position: relative;
                top: -3px;
            }

            #wpadminbar #wp-admin-bar-virtual-files > .ab-item {
                padding-left: 5px;
            }

            #wpadminbar .ab-submenu-separator {
                height: 1px;
                margin: 6px 0;
                background: rgba(255, 255, 255, 0.1);
            }

            #wpadminbar #wp-admin-bar-virtual-files-upgrade > .ab-item {
                background: rgba(0, 163, 42, 0.1);
            }

            #wpadminbar #wp-admin-bar-virtual-files-upgrade:hover > .ab-item {
                background: rgba(0, 163, 42, 0.2);
            }
        ";
        wp_add_inline_style('admin-bar', $custom_css);
    }

    /**
     * Add Virtual Files menu to admin bar
     *
     * @param \WP_Admin_Bar $wp_admin_bar
     */
    public function add_admin_bar_menu($wp_admin_bar): void {
        // Only show for users who can manage options
        if (!current_user_can('manage_options')) {
            return;
        }

        // Check if we're on admin or if user can see admin bar
        if (!is_admin_bar_showing()) {
            return;
        }

        $is_pro = function_exists('intentdeep_vf_fs') && intentdeep_vf_fs()->can_use_premium_code__premium_only();

        // Add main Virtual Files node
        $wp_admin_bar->add_node([
            'id'    => 'virtual-files',
            'title' => '<span class="ab-icon dashicons dashicons-text-page"></span><span class="ab-label">Virtual Files</span>',
            'href'  => admin_url('edit.php?post_type=idep_virtual_file'),
            'meta'  => [
                'title' => __('Virtual Files', 'intentdeep-virtual-files'),
            ],
        ]);

        // Add "Add New File" submenu
        $wp_admin_bar->add_node([
            'id'     => 'virtual-files-add-new',
            'parent' => 'virtual-files',
            'title'  => __('Add New File', 'intentdeep-virtual-files'),
            'href'   => admin_url('post-new.php?post_type=idep_virtual_file'),
            'meta'   => [
                'title' => __('Add New Virtual File', 'intentdeep-virtual-files'),
            ],
        ]);

        // Add "All Files" submenu
        $wp_admin_bar->add_node([
            'id'     => 'virtual-files-all',
            'parent' => 'virtual-files',
            'title'  => __('All Files', 'intentdeep-virtual-files'),
            'href'   => admin_url('edit.php?post_type=idep_virtual_file'),
            'meta'   => [
                'title' => __('View All Virtual Files', 'intentdeep-virtual-files'),
            ],
        ]);

        // Add separator
        $wp_admin_bar->add_node([
            'id'     => 'virtual-files-separator-1',
            'parent' => 'virtual-files',
            'meta'   => [
                'class' => 'ab-submenu-separator',
            ],
        ]);

        // Add Pro features
        if ($is_pro) {
            // Get cache stats
            $cache = new Cache();
            $stats = $cache->get_cache_stats();
            $cached_files = $stats['cached_files'] ?? 0;

            // Add "Clear Cache" submenu
            $wp_admin_bar->add_node([
                'id'     => 'virtual-files-clear-cache',
                'parent' => 'virtual-files',
                /* translators: %d: number of cached files */
                'title'  => sprintf(__('Clear Cache (%d)', 'intentdeep-virtual-files'), $cached_files),
                'href'   => wp_nonce_url(
                    admin_url('admin-post.php?action=intentdeep_vf_clear_cache_admin_bar'),
                    'intentdeep_vf_clear_cache'
                ),
                'meta'   => [
                    'title' => __('Clear all cached virtual files', 'intentdeep-virtual-files'),
                ],
            ]);

            // Add "Warm Cache" submenu
            $wp_admin_bar->add_node([
                'id'     => 'virtual-files-warm-cache',
                'parent' => 'virtual-files',
                'title'  => __('Warm Up Cache', 'intentdeep-virtual-files'),
                'href'   => wp_nonce_url(
                    admin_url('admin-post.php?action=intentdeep_vf_warm_cache_admin_bar'),
                    'intentdeep_vf_warm_cache'
                ),
                'meta'   => [
                    'title' => __('Pre-load all virtual files into cache', 'intentdeep-virtual-files'),
                ],
            ]);

            // Add separator
            $wp_admin_bar->add_node([
                'id'     => 'virtual-files-separator-2',
                'parent' => 'virtual-files',
                'meta'   => [
                    'class' => 'ab-submenu-separator',
                ],
            ]);
        }

        // Add "Settings" submenu
        $wp_admin_bar->add_node([
            'id'     => 'intentdeep_vf_settings',
            'parent' => 'virtual-files',
            'title'  => __('Settings', 'intentdeep-virtual-files'),
            'href'   => admin_url('edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings'),
            'meta'   => [
                'title' => __('Virtual Files Settings', 'intentdeep-virtual-files'),
            ],
        ]);

        // Add "Flush Rewrite Rules" for admins
        $wp_admin_bar->add_node([
            'id'     => 'virtual-files-flush-rewrite',
            'parent' => 'virtual-files',
            'title'  => __('Flush Rewrite Rules', 'intentdeep-virtual-files'),
            'href'   => wp_nonce_url(
                admin_url('admin-post.php?action=intentdeep_vf_flush_rewrite_admin_bar'),
                'intentdeep_vf_flush_rewrite'
            ),
            'meta'   => [
                'title' => __('Flush WordPress rewrite rules', 'intentdeep-virtual-files'),
            ],
        ]);

        // Add separator
        if (!$is_pro) {
            $wp_admin_bar->add_node([
                'id'     => 'virtual-files-separator-3',
                'parent' => 'virtual-files',
                'meta'   => [
                    'class' => 'ab-submenu-separator',
                ],
            ]);

            // Add "Upgrade to Pro" for free users
            $wp_admin_bar->add_node([
                'id'     => 'virtual-files-upgrade',
                'parent' => 'virtual-files',
                'title'  => '<span style="color: #00a32a; font-weight: 600;">⭐ ' . __('Upgrade to Pro', 'intentdeep-virtual-files') . '</span>',
                'href'   => admin_url('edit.php?post_type=idep_virtual_file&page=intentdeep_vf_settings-pricing'),
                'meta'   => [
                    'title' => __('Unlock unlimited files and premium features', 'intentdeep-virtual-files'),
                ],
            ]);
        }
    }

    /**
     * Handle admin bar cache clear action
     */
    public static function handle_clear_cache_action(): void {
        // Verify nonce
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'intentdeep_vf_clear_cache')) {
            wp_die(esc_html__('Security check failed', 'intentdeep-virtual-files'));
        }

        // Verify user capability
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action', 'intentdeep-virtual-files'));
        }

        // Clear cache
        $cache = new Cache();
        $cleared_count = $cache->clear_all_caches();

        // Redirect back with success message
        $redirect_url = add_query_arg(
            [
                'vf-action' => 'cache-cleared',
                'vf-count' => $cleared_count,
            ],
            wp_get_referer() ?: admin_url('edit.php?post_type=idep_virtual_file')
        );

        wp_safe_redirect($redirect_url);
        exit;
    }

    /**
     * Handle admin bar cache warm action
     */
    public static function handle_warm_cache_action(): void {
        // Verify nonce
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'intentdeep_vf_warm_cache')) {
            wp_die(esc_html__('Security check failed', 'intentdeep-virtual-files'));
        }

        // Verify user capability
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action', 'intentdeep-virtual-files'));
        }

        // Warm cache
        $cache = new Cache();
        $warmed_count = $cache->warm_up_cache();

        // Redirect back with success message
        $redirect_url = add_query_arg(
            [
                'vf-action' => 'cache-warmed',
                'vf-count' => $warmed_count,
            ],
            wp_get_referer() ?: admin_url('edit.php?post_type=idep_virtual_file')
        );

        wp_safe_redirect($redirect_url);
        exit;
    }

    /**
     * Handle admin bar flush rewrite action
     */
    public static function handle_flush_rewrite_action(): void {
        // Verify nonce
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'intentdeep_vf_flush_rewrite')) {
            wp_die(esc_html__('Security check failed', 'intentdeep-virtual-files'));
        }

        // Verify user capability
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have permission to perform this action', 'intentdeep-virtual-files'));
        }

        // Flush rewrite rules
        flush_rewrite_rules();

        // Redirect back with success message
        $redirect_url = add_query_arg(
            [
                'vf-action' => 'rewrite-flushed',
            ],
            wp_get_referer() ?: admin_url('edit.php?post_type=idep_virtual_file')
        );

        wp_safe_redirect($redirect_url);
        exit;
    }

    /**
     * Display admin notices for admin bar actions
     */
    public static function display_admin_notices(): void {
        if (!isset($_GET['vf-action'])) {
            return;
        }

        $action = sanitize_text_field($_GET['vf-action']);
        $message = '';
        $type = 'success';

        switch ($action) {
            case 'cache-cleared':
                $count = isset($_GET['vf-count']) ? intval($_GET['vf-count']) : 0;
                $message = sprintf(
                    /* translators: %d: number of files removed from cache */
                    __('Cache cleared successfully! %d files removed from cache.', 'intentdeep-virtual-files'),
                    $count
                );
                break;

            case 'cache-warmed':
                $count = isset($_GET['vf-count']) ? intval($_GET['vf-count']) : 0;
                $message = sprintf(
                    /* translators: %d: number of files loaded into cache */
                    __('Cache warmed up successfully! %d files loaded into cache.', 'intentdeep-virtual-files'),
                    $count
                );
                break;

            case 'rewrite-flushed':
                $message = __('Rewrite rules flushed successfully!', 'intentdeep-virtual-files');
                break;
        }

        if ($message) {
            printf(
                '<div class="notice notice-%s is-dismissible"><p>%s</p></div>',
                esc_attr($type),
                esc_html($message)
            );
        }
    }
}
