<?php
/**
 * Kavehboard Routing System
 * Handles dynamic content routing, WooCommerce integration, and custom menu management
 */
class kavehboardrouting {
    
    private $dashboard_page_id;
    private $options;
    
    public function __construct() {
        $this->options = get_option('kavehboard_options');
        $this->dashboard_page_id = isset($this->options['kavehboard_page']) ? $this->options['kavehboard_page'] : '';
        
        // Initialize hooks
        add_action('init', array($this, 'add_query_vars'));
        add_filter('query_vars', array($this, 'custom_query_vars'));
        add_action('wp', array($this, 'handle_dashboard_routing'));
        
        // Add notifications page route
        $this->pages['notifications'] = array(
            'title' => __('Notifications', 'kavehboard'),
            'description' => __('View your notifications', 'kavehboard'),
            'template' => 'notifications.php'
        );
        
        // WooCommerce integration
        if (class_exists('WooCommerce')) {
            add_filter('woocommerce_account_menu_items', array($this, 'customize_woo_menu'), 10, 1);
            add_action('woocommerce_account_content', array($this, 'handle_woo_content'));
        }
    }
    
    /**
     * Add custom query variables
     */
    public function custom_query_vars($vars) {
        $vars[] = 'kaveh_page';
        $vars[] = 'kaveh_action';
        return $vars;
    }
    
    /**
     * Add rewrite rules for clean URLs
     */
    public function add_query_vars() {
        if (!empty($this->dashboard_page_id)) {
            $dashboard_slug = get_post_field('post_name', $this->dashboard_page_id);
            
            // Add rewrite rules for dashboard pages
            add_rewrite_rule(
                '^' . $dashboard_slug . '/([^/]+)/?$',
                'index.php?page_id=' . $this->dashboard_page_id . '&kaveh_page=$matches[1]',
                'top'
            );
            
            add_rewrite_rule(
                '^' . $dashboard_slug . '/([^/]+)/([^/]+)/?$',
                'index.php?page_id=' . $this->dashboard_page_id . '&kaveh_page=$matches[1]&kaveh_action=$matches[2]',
                'top'
            );
        }
    }
    
    /**
     * Handle dashboard content routing
     */
    public function handle_dashboard_routing() {
        if (!is_page($this->dashboard_page_id)) {
            return;
        }
        
        $current_page = get_query_var('kaveh_page');
        $current_action = get_query_var('kaveh_action');
        
        // Set default page if none specified
        if (empty($current_page)) {
            $current_page = 'dashboard';
        }
        
        // Store current page for template use
        global $kaveh_current_page, $kaveh_current_action;
        $kaveh_current_page = $current_page;
        $kaveh_current_action = $current_action;
    }
    
    /**
     * Get dashboard menu items
     */
    public function get_dashboard_menu() {
        $menu_items = array();
        
        // Get menu type setting
        $menu_type = isset($this->options['kavehboard_menu_type']) ? $this->options['kavehboard_menu_type'] : 'custom';
        
        switch ($menu_type) {
            case 'woocommerce':
                $menu_items = $this->get_woocommerce_menu();
                break;
                
            case 'combined':
                $menu_items = array_merge(
                    $this->get_custom_menu_without_notifications(),
                    $this->get_woocommerce_menu()
                );
                break;
                
            case 'custom':
            default:
                $menu_items = $this->get_custom_menu_without_notifications();
                break;
        }
        
        // Always add notifications and logout at the end
        $menu_items = array_merge($menu_items, $this->get_fixed_menu_items());
        
        return apply_filters('kavehboard_dashboard_menu', $menu_items);
    }
    
    /**
     * Get custom menu items from admin settings (without notifications)
     */
    private function get_custom_menu_without_notifications() {
        $menu_items = array();
        
        // Get custom menu items from repeater field
        $custom_menus = isset($this->options['kavehboard_dashboard_menu']) ? $this->options['kavehboard_dashboard_menu'] : array();
        
        if (!empty($custom_menus)) {
            foreach ($custom_menus as $menu) {
                if (empty($menu['text']) || empty($menu['slug'])) {
                    continue;
                }
                
                // Skip wallet menu if wallet system is disabled
                if ($menu['slug'] === 'wallet' && empty($this->options['kavehboard_wallet_enable'])) {
                    continue;
                }
                
                $menu_items[$menu['slug']] = array(
                    'title' => $menu['text'],
                    'icon' => isset($menu['icon']) ? $menu['icon'] : 'icon-menu',
                    'url' => $this->get_dashboard_url($menu['slug']),
                    'elementor_template' => isset($menu['elementor_template']) ? $menu['elementor_template'] : '',
                    'shortcode' => isset($menu['shortcode']) ? $menu['shortcode'] : '',
                    'type' => 'custom'
                );
            }
        }
        
        return $menu_items;
    }
    
    /**
     * Get fixed menu items that always appear at the end (notifications and logout)
     */
    private function get_fixed_menu_items() {
        $menu_items = array();
        
        // Add notifications menu item
        $current_user_id = get_current_user_id();
        $unread_count = function_exists('kavehboard_get_unread_notifications_count') ? kavehboard_get_unread_notifications_count($current_user_id) : 0;
        
        $menu_items['notifications'] = array(
            'title' => __('اعلانات', 'kavehboard'),
            'icon' => 'icon-notification-2',
            'url' => $this->get_dashboard_url('notifications'),
            'type' => 'fixed',
            'badge_count' => $unread_count
        );
        
        // Add logout menu item
        $menu_items['logout'] = array(
            'title' => __('خروج از پنل', 'kavehboard'),
            'icon' => 'icon-logout',
            'url' => wp_logout_url(home_url()),
            'type' => 'fixed'
        );
        
        return $menu_items;
    }
    
    /**
     * Get custom menu items from admin settings (legacy method for backward compatibility)
     */
    private function get_custom_menu() {
        return $this->get_custom_menu_without_notifications();
    }
    
    /**
     * Get WooCommerce menu items
     */
    private function get_woocommerce_menu() {
        $menu_items = array();
        
        if (!class_exists('WooCommerce')) {
            return $menu_items;
        }
        
        // Get WooCommerce account menu items
        $woo_menu_items = wc_get_account_menu_items();
        
        foreach ($woo_menu_items as $endpoint => $label) {
            // Skip logout as it's handled separately
            if ($endpoint === 'customer-logout') {
                continue;
            }
            
            $menu_items['woo-' . $endpoint] = array(
                'title' => $this->translate_woo_menu_label($endpoint, $label),
                'icon' => $this->get_woo_icon($endpoint),
                'url' => $this->get_dashboard_url('woo-' . $endpoint),
                'endpoint' => $endpoint,
                'type' => 'woocommerce'
            );
        }
        
        return $menu_items;
    }
    
    /**
     * Translate WooCommerce menu labels to theme text domain
     */
    private function translate_woo_menu_label($endpoint, $default_label) {
        $translations = array(
            'dashboard' => __('Dashboard', 'kavehTheme'),
            'orders' => __('Orders', 'kavehTheme'),
            'downloads' => __('Downloads', 'kavehTheme'),
            'edit-address' => __('Addresses', 'kavehTheme'),
            'edit-account' => __('Account details', 'kavehTheme'),
            'payment-methods' => __('Payment methods', 'kavehTheme'),
            'wishlist' => __('Wishlist', 'kavehTheme')
        );
        
        // Return translated label if available, otherwise return default
        return isset($translations[$endpoint]) ? $translations[$endpoint] : $default_label;
    }
    
    /**
     * Get icon for WooCommerce endpoints
     */
    private function get_woo_icon($endpoint) {
        $icons = array(
            'dashboard' => 'icon-element',
            'orders' => 'icon-bag-4',
            'downloads' => 'icon-directbox-receive',
            'edit-address' => 'icon-location',
            'edit-account' => 'icon-user',
            'payment-methods' => 'icon-credit-card',
            'wishlist' => 'icon-heart-6'
        );
        
        return isset($icons[$endpoint]) ? $icons[$endpoint] : 'icon-menu';
    }
    
    /**
     * Generate dashboard URL
     */
    public function get_dashboard_url($page = '') {
        $base_url = get_permalink($this->dashboard_page_id);
        
        if (!empty($page) && $page !== 'dashboard') {
            $base_url = trailingslashit($base_url) . $page . '/';
        }
        
        return $base_url;
    }
    
    /**
     * Render dashboard content based on current page
     */
    public function render_dashboard_content() {
        global $kaveh_current_page, $kaveh_current_action;
        
        $current_page = $kaveh_current_page ?: 'dashboard';
        $menu_items = $this->get_dashboard_menu();
        
        // Handle specific template pages
        switch ($current_page) {
            case 'orders':
                $template_path = KAVEHBOARD_PATH . 'template-part/orders.php';
                if (file_exists($template_path)) {
                    include $template_path;
                    return;
                }
                break;
                
            case 'order-details':
                $template_path = KAVEHBOARD_PATH . 'template-part/order-details.php';
                if (file_exists($template_path)) {
                    include $template_path;
                    return;
                }
                break;
                
            case 'edit-profile':
                $template_path = KAVEHBOARD_PATH . 'template-part/edit-profile.php';
                if (file_exists($template_path)) {
                    include $template_path;
                    return;
                }
                break;
                
            case 'notifications':
                $template_path = KAVEHBOARD_PATH . 'template-part/notifications.php';
                if (file_exists($template_path)) {
                    include $template_path;
                    return;
                }
                break;
                
        

        }
        
        // Handle WooCommerce pages
        if (strpos($current_page, 'woo-') === 0) {
            $this->render_woocommerce_content($current_page);
            return;
        }
        
        // Handle custom pages
        if (isset($menu_items[$current_page])) {
            $menu_item = $menu_items[$current_page];
            
            // Render Elementor template if available
            if (!empty($menu_item['elementor_template']) && did_action('elementor/loaded')) {
                echo \Elementor\Plugin::instance()->frontend->get_builder_content_for_display($menu_item['elementor_template']);
                return;
            }
            
            // Render shortcode if available
            if (!empty($menu_item['shortcode'])) {
                echo do_shortcode($menu_item['shortcode']);
                return;
            }
        }
        
       
    }
    
    /**
     * Render WooCommerce content
     */
    private function render_woocommerce_content($page) {
        if (!class_exists('WooCommerce')) {
            $this->render_404_content();
            return;
        }
        
        $endpoint = str_replace('woo-', '', $page);
        
        // Check if we have custom templates for specific endpoints
        $custom_template_path = KAVEHBOARD_PATH . 'template-part/';
        
        // Handle orders with custom template
        if ($endpoint === 'orders' && file_exists($custom_template_path . 'orders.php')) {
            include $custom_template_path . 'orders.php';
            return;
        }
        
        // Handle edit-account with custom template
        if ($endpoint === 'edit-account' && file_exists($custom_template_path . 'edit-profile.php')) {
            include $custom_template_path . 'edit-profile.php';
            return;
        }
        
        // Handle edit-address with custom template
        if ($endpoint === 'edit-address' && file_exists($custom_template_path . 'edit-address.php')) {
            include $custom_template_path . 'edit-address.php';
            return;
        }
        
        // Set up WooCommerce query vars and environment for other endpoints
        global $wp, $woocommerce;
        
        // Set the current endpoint
        $wp->query_vars[$endpoint] = '';
        
        // Set up WooCommerce account page context
        if (!is_account_page()) {
            // Temporarily set account page context
            add_filter('woocommerce_is_account_page', '__return_true');
        }
        
        // Render WooCommerce content
        echo '<div class="woocommerce-account">';
        
        // Handle different endpoints
        switch ($endpoint) {
            case 'dashboard':
                include $custom_template_path . 'inner-dashboard.php';
            break;
                
            case 'downloads':
                wc_get_template('myaccount/downloads.php', array(
                    'downloads' => wc_get_customer_available_downloads(get_current_user_id()),
                    'has_downloads' => false
                ));
                break;
                
            case 'edit-address':
                // Handle address type (billing/shipping)
                $address_type = isset($_GET['type']) ? sanitize_title($_GET['type']) : 'billing';
                if (!in_array($address_type, array('billing', 'shipping'))) {
                    $address_type = 'billing';
                }
                
                // Set up the address editing context
                $wp->query_vars['edit-address'] = $address_type;
                
                // Get customer data
                $customer = WC()->customer;
                $address = array();
                
                if ($address_type === 'billing') {
                    $address = $customer->get_billing();
                } else {
                    $address = $customer->get_shipping();
                }
                
                wc_get_template('myaccount/form-edit-address.php', array(
                    'type' => $address_type,
                    'address' => $address,
                    'load_address' => $address
                ));
                break;
                
            case 'payment-methods':
                $saved_methods = wc_get_customer_saved_methods_list(get_current_user_id());
                wc_get_template('myaccount/payment-methods.php', array(
                    'saved_methods' => $saved_methods,
                    'has_methods' => (bool) $saved_methods
                ));
                break;
                
            default:
                // Try to handle custom endpoints or other WooCommerce endpoints
                if (has_action('woocommerce_account_' . $endpoint . '_endpoint')) {
                    do_action('woocommerce_account_' . $endpoint . '_endpoint', '');
                } else {
                    $this->render_404_content();
                }
                break;
        }
        
        echo '</div>';
        
        // Remove the temporary filter
        remove_filter('woocommerce_is_account_page', '__return_true');
    }
    
    /**
     * Render 404 content for invalid pages
     */
    private function render_404_content() {
        echo '<div class="kavehboard-404">';
        echo '<h2>' . __('Page Not Found', 'kavehTheme') . '</h2>';
        echo '<p>' . __('The requested page could not be found.', 'kavehTheme') . '</p>';
        echo '</div>';
    }
    
    /**
     * Customize WooCommerce account menu
     */
    public function customize_woo_menu($items) {
        // Only modify if we're using WooCommerce or combined menu
        $menu_type = isset($this->options['kavehboard_menu_type']) ? $this->options['kavehboard_menu_type'] : 'custom';
        
        if ($menu_type === 'woocommerce' || $menu_type === 'combined') {
            // Note: We don't modify the items here as it would overwrite the labels with URLs
            // The URL redirection is handled in the get_woocommerce_menu() method instead
        }
        
        return $items;
    }
    
    /**
     * Handle WooCommerce content in our dashboard
     */
    public function handle_woo_content($endpoint) {
        // This is handled by our routing system
    }
    



    
    /**
     * Check if menu item is active
     */
    public function is_menu_active($slug) {
        global $kaveh_current_page;
        $current_page = $kaveh_current_page ?: 'dashboard';
        
        // Handle dashboard as default
        if ($slug === 'dashboard' && ($current_page === 'dashboard' || empty($current_page))) {
            return true;
        }
        
        return $current_page === $slug;
    }
    
    /**
     * Get current active page
     */
    public function get_current_page() {
        global $kaveh_current_page;
        return $kaveh_current_page ?: '';
    }
}