<?php
/**
 * Router Class
 *
 * Handles admin page routing and menu management
 *
 * @package AIProductContentImageGenerator\Core
 * @since 1.0.0
 */

namespace AIProductContentImageGenerator\Core;

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

/**
 * Router class for handling admin pages and navigation
 */
class Router {
    /**
     * Registered routes
     *
     * @var array
     */
    private $routes = [];

    /**
     * Current page
     *
     * @var string
     */
    private $current_page = '';

    /**
     * Initialize router
     */
    public function init() {
        add_action('admin_menu', [$this, 'addMenuPages']);
        add_action('admin_init', [$this, 'handleRouting']);
    }

    /**
     * Register a route
     *
     * @param string $slug Route slug
     * @param array $config Route configuration
     */
    public function register_route($slug, $config) {
        $defaults = [
            'title' => '',
            'menu_title' => '',
            'capability' => 'manage_woocommerce',
            'callback' => null,
            'parent' => null
        ];

        $this->routes[$slug] = wp_parse_args($config, $defaults);
    }

    /**
     * Add WordPress admin menu pages
     */
    public function addMenuPages() {
        // Main menu page
        add_menu_page(
            __('AI Product Generator', 'contengen-ai-product-content-image-generator'),
            __('AI Product Gen', 'contengen-ai-product-content-image-generator'),
            'manage_woocommerce',
            'apcig-dashboard',
            [$this, 'renderDashboard'],
            'dashicons-admin-tools',
            56
        );

        // Dashboard submenu (same as main)
        add_submenu_page(
            'apcig-dashboard',
            __('Dashboard', 'contengen-ai-product-content-image-generator'),
            __('Dashboard', 'contengen-ai-product-content-image-generator'),
            'manage_woocommerce',
            'apcig-dashboard',
            [$this, 'renderDashboard']
        );

        // Content Generator
        add_submenu_page(
            'apcig-dashboard',
            __('Content Generator', 'contengen-ai-product-content-image-generator'),
            __('Content', 'contengen-ai-product-content-image-generator'),
            'manage_woocommerce',
            'apcig-content-generator',
            [$this, 'renderContentGenerator']
        );

        // Image Generator
        add_submenu_page(
            'apcig-dashboard',
            __('Image Generator', 'contengen-ai-product-content-image-generator'),
            __('Images', 'contengen-ai-product-content-image-generator'),
            'manage_woocommerce',
            'apcig-image-generator',
            [$this, 'renderImageGenerator']
        );

        // Bulk Processing
        add_submenu_page(
            'apcig-dashboard',
            __('Bulk Processing', 'contengen-ai-product-content-image-generator'),
            __('Bulk Process', 'contengen-ai-product-content-image-generator'),
            'manage_woocommerce',
            'apcig-bulk-processor',
            [$this, 'renderBulkProcessor']
        );

        // Settings
        add_submenu_page(
            'apcig-dashboard',
            __('Settings', 'contengen-ai-product-content-image-generator'),
            __('Settings', 'contengen-ai-product-content-image-generator'),
            'manage_woocommerce',
            'apcig-settings',
            [$this, 'renderSettings']
        );
    }

    /**
     * Handle routing logic
     */
    public function handleRouting() {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is just reading the page parameter for routing
        if (isset($_GET['page']) && strpos(sanitize_text_field(wp_unslash($_GET['page'])), 'apcig-') === 0) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            $this->current_page = sanitize_text_field(wp_unslash($_GET['page']));
        }
    }

    /**
     * Check if current page is a plugin page
     *
     * @return bool
     */
    public function is_plugin_page() {
        return !empty($this->current_page) && strpos($this->current_page, 'apcig-') === 0;
    }

    /**
     * Get current page
     *
     * @return string
     */
    public function get_current_page() {
        return $this->current_page;
    }

    /**
     * Render dashboard page
     */
    public function renderDashboard() {
        $this->renderLayout('dashboard');
    }

    /**
     * Render content generator page
     */
    public function renderContentGenerator() {
        $this->renderLayout('content-generator');
    }

    /**
     * Render image generator page
     */
    public function renderImageGenerator() {
        $this->renderLayout('image-generator');
    }

    /**
     * Render bulk processor page
     */
    public function renderBulkProcessor() {
        $this->renderLayout('bulk-processing');
    }

    /**
     * Render settings page
     */
    public function renderSettings() {
        $this->renderLayout('settings');
    }

    /**
     * Render page layout
     *
     * @param string $view View name
     */
    private function renderLayout($view) {
        // Security check
        if (!current_user_can('manage_woocommerce')) {
            wp_die(esc_html(__('You do not have sufficient permissions to access this page.', 'contengen-ai-product-content-image-generator')));
        }

        // Include layout wrapper
        $layout_file = APCIG_PLUGIN_DIR . 'src/Admin/Views/layout.php';
        $view_file = APCIG_PLUGIN_DIR . 'src/Admin/Views/' . $view . '.php';

        if (!file_exists($layout_file)) {
            echo '<div class="notice notice-error"><p>Layout file not found.</p></div>';
            return;
        }
        
        if (!file_exists($view_file)) {
            echo '<div class="notice notice-error"><p>Content file not found: ' . esc_html($view) . '</p></div>';
            return;
        }

        // Set variables for the layout (matching AdminManager format)
        $current_page = $view;
        $content_file_path = $view_file;
        
        include $layout_file;
    }

    /**
     * Get admin URL for a page
     *
     * @param string $page Page slug
     * @param array $args Additional arguments
     * @return string
     */
    public function get_admin_url($page, $args = []) {
        $url = admin_url('admin.php?page=' . $page);
        
        if (!empty($args)) {
            $url = add_query_arg($args, $url);
        }
        
        return $url;
    }

    /**
     * Get navigation items
     *
     * @return array
     */
    public function get_navigation_items() {
        return [
            'apcig-dashboard' => [
                'title' => __('Dashboard', 'contengen-ai-product-content-image-generator'),
                'icon' => 'dashicons-dashboard',
                'url' => $this->get_admin_url('apcig-dashboard')
            ],
            'apcig-content-generator' => [
                'title' => __('Content', 'contengen-ai-product-content-image-generator'),
                'icon' => 'dashicons-edit-page',
                'url' => $this->get_admin_url('apcig-content-generator')
            ],
            'apcig-image-generator' => [
                'title' => __('Images', 'contengen-ai-product-content-image-generator'),
                'icon' => 'dashicons-format-image',
                'url' => $this->get_admin_url('apcig-image-generator')
            ],
            'apcig-bulk-processor' => [
                'title' => __('Bulk Process', 'contengen-ai-product-content-image-generator'),
                'icon' => 'dashicons-performance',
                'url' => $this->get_admin_url('apcig-bulk-processor')
            ],
            'apcig-settings' => [
                'title' => __('Settings', 'contengen-ai-product-content-image-generator'),
                'icon' => 'dashicons-admin-settings',
                'url' => $this->get_admin_url('apcig-settings')
            ]
        ];
    }
}