<?php

namespace PloverCRM\Core;

/**
 * Admin Menu Manager
 * 
 * Centralizes all PloverCRM admin menu registration.
 * Creates a top-level PloverCRM menu that always exists,
 * regardless of which CRM backend is active.
 */
class AdminMenu
{
  /**
   * Menu slug for the top-level PloverCRM menu
   */
  const MENU_SLUG = 'plover-crm';

  /**
   * @var Container
   */
  private $container;

  /**
   * @var array Registered submenu items
   */
  private static $submenus = [];

  /**
   * Constructor
   */
  public function __construct(Container $container)
  {
    $this->container = $container;
  }

  /**
   * Initialize admin menu
   */
  public function init(): void
  {
    add_action('admin_menu', [$this, 'registerMainMenu'], 5);
    add_action('admin_menu', [$this, 'registerSubmenus'], 50); // After PloverCRM submenus (priority 20)

    // Fix menu highlighting
    add_filter('parent_file', [$this, 'fixParentMenuHighlight']);
    add_filter('submenu_file', [$this, 'fixSubmenuHighlight'], 10, 2);
  }

  /**
   * Register the main PloverCRM menu
   */
  public function registerMainMenu(): void
  {
    $iconSvg = $this->getMenuIcon();
    $isLicensed = \PloverCRM\Common\LicenseChecker::isValid();

    // If not licensed, only show a menu that points to the License page
    if (!$isLicensed) {
      add_menu_page(
        'PloverCRM',
        'PloverCRM',
        'manage_options',
        'plover-crm-license',
        [\PloverCRM\Common\LicensePage::class, 'render'],
        $iconSvg,
        30
      );
      return;
    }

    // Check if the built-in CRM module is active
    $disabledModules = get_option('plover_crm_disabled_modules', []);
    $isNativeCRMActive = !in_array('native_crm', $disabledModules);

    if ($isNativeCRMActive) {
      add_menu_page(
        'PloverCRM',
        'PloverCRM',
        'manage_options',
        self::MENU_SLUG,
        [$this, 'renderDashboard'],
        $iconSvg,
        30
      );
    } else {
      add_menu_page(
        'PloverCRM Settings',
        'PloverCRM',
        'manage_options',
        'plover-crm-settings',
        [$this, 'renderSettingsPage'],
        $iconSvg,
        30
      );
    }
  }

  /**
   * Render settings page (proxy to AdminSettingsModule)
   */
  public function renderSettingsPage(): void
  {
    \PloverCRM\Modules\AdminSettings\AdminSettingsModule::renderAppSettingsPageStatic();
  }

  /**
   * Register all submenus
   */
  public function registerSubmenus(): void
  {
    // If not licensed, no submenus — only the license page is shown
    if (!\PloverCRM\Common\LicenseChecker::isValid()) {
      return;
    }

    // Check if the built-in CRM module is active
    $disabledModules = get_option('plover_crm_disabled_modules', []);
    $isNativeCRMActive = !in_array('native_crm', $disabledModules);

    // Determine parent slug based on whether the built-in CRM is enabled
    $parentSlug = $isNativeCRMActive ? self::MENU_SLUG : 'plover-crm-settings';

    // Sort submenus by priority
    usort(self::$submenus, function ($a, $b) {
      return ($a['priority'] ?? 50) <=> ($b['priority'] ?? 50);
    });

    foreach (self::$submenus as $submenu) {
      // Skip Settings submenu when Native CRM is disabled (it's already the main menu)
      if (!$isNativeCRMActive && $submenu['menu_slug'] === 'plover-crm-settings') {
        continue;
      }

      $submenuParent = ($submenu['visible'] ?? true) ? $parentSlug : null;

      add_submenu_page(
        $submenuParent,
        $submenu['page_title'],
        $submenu['menu_title'],
        $submenu['capability'] ?? 'manage_options',
        $submenu['menu_slug'],
        $submenu['callback']
      );
    }

    // Remove the duplicate submenu that WordPress creates for the parent
    // When Native CRM is disabled, keep "Settings" as the first item
    if (!$isNativeCRMActive) {
      $this->renameFirstSubmenu($parentSlug, 'Settings');
    } else {
      $this->removeDuplicateSubmenu($parentSlug);
    }
  }

  /**
   * Rename the first submenu item (WordPress auto-creates it with parent name)
   */
  private function renameFirstSubmenu(string $parentSlug, string $newName): void
  {
    global $submenu;

    if (isset($submenu[$parentSlug]) && !empty($submenu[$parentSlug])) {
      // Find the first item that matches the parent slug
      foreach ($submenu[$parentSlug] as $key => $item) {
        if ($item[2] === $parentSlug) {
          $submenu[$parentSlug][$key][0] = $newName;
          break;
        }
      }
    }
  }

  /**
   * Remove the duplicate submenu item WordPress creates for the parent
   */
  private function removeDuplicateSubmenu(string $parentSlug): void
  {
    global $submenu;

    if (isset($submenu[$parentSlug])) {
      foreach ($submenu[$parentSlug] as $key => $item) {
        if ($item[2] === $parentSlug) {
          unset($submenu[$parentSlug][$key]);
          break;
        }
      }
      // Re-index array
      $submenu[$parentSlug] = array_values($submenu[$parentSlug]);
    }
  }

  /**
   * Fix parent menu highlighting for all PloverCRM pages
   */
  public function fixParentMenuHighlight($parent_file)
  {
    global $current_screen;

    if (!$current_screen) {
      return $parent_file;
    }

    // Highlight PloverCRM menu for contact post type
    if ($current_screen->post_type === 'plover_crm_contact') {
      return self::MENU_SLUG;
    }

    // Highlight PloverCRM menu for Lists and Tags taxonomy pages
    if ($current_screen->taxonomy === 'plover_crm_list' || $current_screen->taxonomy === 'plover_crm_tag') {
      return self::MENU_SLUG;
    }

    return $parent_file;
  }

  /**
   * Fix submenu highlighting
   */
  public function fixSubmenuHighlight($submenu_file, $parent_file)
  {
    global $current_screen;

    if (!$current_screen) {
      return $submenu_file;
    }

    // Highlight Contacts submenu for contact post type
    if ($current_screen->post_type === 'plover_crm_contact' && $current_screen->base === 'edit') {
      return 'edit.php?post_type=plover_crm_contact';
    }

    // Highlight correct submenu for Lists and Tags
    if ($current_screen->taxonomy === 'plover_crm_list') {
      return 'edit-tags.php?taxonomy=plover_crm_list&post_type=plover_crm_contact';
    }

    if ($current_screen->taxonomy === 'plover_crm_tag') {
      return 'edit-tags.php?taxonomy=plover_crm_tag&post_type=plover_crm_contact';
    }

    return $submenu_file;
  }

  /**
   * Register a submenu item
   * 
   * @param string $menuSlug Unique slug for this submenu
   * @param string $pageTitle Title shown in browser tab
   * @param string $menuTitle Title shown in menu
   * @param callable $callback Render callback
   * @param int $priority Lower = higher in menu (default: 50)
   * @param string $capability Required capability (default: manage_options)
   */
  public static function addSubmenu(
    string $menuSlug,
    string $pageTitle,
    string $menuTitle,
    callable $callback,
    int $priority = 50,
    string $capability = 'manage_options',
    bool $visible = true
  ): void {
    self::$submenus[] = [
      'menu_slug' => $menuSlug,
      'page_title' => $pageTitle,
      'menu_title' => $menuTitle,
      'callback' => $callback,
      'priority' => $priority,
      'capability' => $capability,
      'visible' => $visible,
    ];
  }

  /**
   * Get the menu parent slug
   * 
   * @return string
   */
  public static function getParentSlug(): string
  {
    $disabledModules = get_option('plover_crm_disabled_modules', []);
    $isNativeCRMActive = !in_array('native_crm', $disabledModules);

    return $isNativeCRMActive ? self::MENU_SLUG : 'plover-crm-settings';
  }

  /**
   * Render the dashboard page
   */
  public function renderDashboard(): void
  {
    wp_safe_redirect(home_url('/plover-crm/'));
    exit;
  }

  /**
   * Get the menu icon as base64 SVG
   */
  private function getMenuIcon(): string
  {
    static $iconDataUri = null;

    if ($iconDataUri !== null) {
      return $iconDataUri;
    }

    $iconPath = (defined('PLOVER_CRM_PLUGIN_PATH') ? PLOVER_CRM_PLUGIN_PATH : dirname(__DIR__, 2) . '/')
      . 'assets/icons/admin-menu-icon.svg';

    if (is_readable($iconPath)) {
      $svg = file_get_contents($iconPath);
      if (is_string($svg) && $svg !== '') {
        $iconDataUri = 'data:image/svg+xml;base64,' . base64_encode($svg);
        return $iconDataUri;
      }
    }

    $fallbackSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="black"><path d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"/></svg>';
    $iconDataUri = 'data:image/svg+xml;base64,' . base64_encode($fallbackSvg);

    return $iconDataUri;
  }
}
