<?php
/**
 * Sidebar navigation for the redesigned admin UI
 *
 * @package    TTSWP
 * @subpackage Mementor_TTS/admin/partials
 */

if (!defined('ABSPATH')) {
    exit;
}

// ---------------------------------------------------------------------------
// Current page detection
// ---------------------------------------------------------------------------

$sidebar_page_map = [
    'text-to-speech-tts-settings'        => 'overview',
    'text-to-speech-tts-voices'          => 'voices',
    'text-to-speech-tts-player'          => 'player',
    'text-to-speech-tts-content'         => 'content',
    'text-to-speech-tts-generator'       => 'generator',
    'text-to-speech-tts-word-replacement'=> 'word-replacement',
    'text-to-speech-tts-css-selectors'   => 'css-selectors',
    'text-to-speech-tts-speech-to-text'  => 'speech-to-text',
    'text-to-speech-tts-my-stats-voices' => 'my-stats',
    'text-to-speech-tts-statistics'      => 'statistics',
    'text-to-speech-tts-audio-library'   => 'audio-library',
    'text-to-speech-tts-upgrade'         => 'license',
    'text-to-speech-tts-white-label'     => 'white-label',
    'text-to-speech-tts-affiliate'       => 'affiliate',
    'text-to-speech-tts-advanced'        => 'advanced',
    'text-to-speech-tts-add-credits'     => 'add-credits',
    'text-to-speech-tts-account'         => 'account',
    'text-to-speech-tts-documentation'   => 'documentation',
    'text-to-speech-tts-pro-help'        => 'pro-support',
];

$sidebar_current_slug = '';
if (isset($_GET['page'])) {
    $sidebar_raw_page = sanitize_text_field(wp_unslash($_GET['page']));
    if (isset($sidebar_page_map[$sidebar_raw_page])) {
        $sidebar_current_slug = $sidebar_page_map[$sidebar_raw_page];
    }
}

// ---------------------------------------------------------------------------
// Plugin state
// ---------------------------------------------------------------------------

$sidebar_is_pro    = ttswp_has_paid_plan();
$sidebar_has_api   = !empty(get_option('mementor_tts_api_key'));
$sidebar_license   = ['status' => $sidebar_is_pro ? 'active' : 'inactive'];

// ---------------------------------------------------------------------------
// White-label branding
// ---------------------------------------------------------------------------

require_once MEMENTOR_TTS_PLUGIN_DIR . 'admin/class-mementor-tts-admin.php';
$sidebar_wl_logo = Mementor_TTS_Admin::get_custom_white_label_logo();
$sidebar_wl_name = Mementor_TTS_Admin::get_white_label_name();

// Version string
$sidebar_version = defined('MEMENTOR_TTS_VERSION') ? MEMENTOR_TTS_VERSION : '1.0.0';
if ($sidebar_is_pro) {
    $sidebar_version_label = 'PRO v' . $sidebar_version;
} else {
    $sidebar_version_label = 'v' . $sidebar_version;
}

// ---------------------------------------------------------------------------
// Menu visibility helpers (replicate private methods as closures)
// ---------------------------------------------------------------------------

$sidebar_should_show_menu_item = function ($menu_type) use ($sidebar_is_pro, $sidebar_license) {
    // Admins always see everything
    if (current_user_can('administrator')) {
        return true;
    }

    if ($sidebar_is_pro) {
        $status = isset($sidebar_license['status']) ? $sidebar_license['status'] : 'inactive';
        if ($status === 'active') {
            if ($menu_type === 'affiliate' && get_option('mementor_tts_white_label_hide_affiliate', '0') === '1') {
                return false;
            }
            if ($menu_type === 'license' && get_option('mementor_tts_white_label_hide_license', '0') === '1') {
                return false;
            }
            if ($menu_type === 'documentation' && get_option('mementor_tts_white_label_hide_documentation', '0') === '1') {
                return false;
            }
            if ($menu_type === 'add-credits' && get_option('mementor_tts_white_label_hide_add_credits', '0') === '1') {
                return false;
            }
            if ($menu_type === 'pro-help' && get_option('mementor_tts_white_label_hide_pro_help', '0') === '1') {
                return false;
            }
        }
    }

    return true;
};

$sidebar_can_see_white_label = function () {
    return true;
};

// ---------------------------------------------------------------------------
// Helper: active class
// ---------------------------------------------------------------------------

$sidebar_active = function ($slug) use ($sidebar_current_slug) {
    return $sidebar_current_slug === $slug ? ' active' : '';
};
?>

<aside class="tts-sidebar">

  <!-- Logo / branding -->
  <div class="tts-sidebar-logo">
    <div class="tts-logo-icon">
      <?php if (!empty($sidebar_wl_logo)) : ?>
        <img src="<?php echo esc_url($sidebar_wl_logo); ?>" alt="<?php echo esc_attr($sidebar_wl_name); ?>">
      <?php else : ?>
        <img src="<?php echo esc_url(MEMENTOR_TTS_PLUGIN_URL . 'admin/images/ttswp-icon.svg'); ?>" alt="<?php echo esc_attr($sidebar_wl_name); ?>">
      <?php endif; ?>
    </div>
    <div>
      <div class="tts-plugin-name"><?php echo esc_html($sidebar_wl_name); ?></div>
      <div class="tts-plugin-version">
        <?php echo esc_html($sidebar_version_label); ?>
        <?php if (!$sidebar_is_pro && Mementor_TTS_Connect::get_connection_status() === 'connected'): ?>
          <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-upgrade')); ?>" class="tts-upgrade-link"><?php esc_html_e('UPGRADE', 'text-to-speech-tts'); ?></a>
        <?php endif; ?>
      </div>
    </div>
  </div>

  <nav class="tts-nav">

    <!-- Dashboard — always visible, no toggle -->
    <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-settings')); ?>"
       class="tts-nav-item tts-nav-item-top<?php echo $sidebar_active('overview'); ?>">
      <span class="dashicons dashicons-dashboard"></span>
      <?php esc_html_e('Overview', 'text-to-speech-tts'); ?>
    </a>

    <!-- Audio -->
    <div class="tts-nav-group" data-group="audio">
      <button type="button" class="tts-nav-label tts-nav-toggle">
        <span class="dashicons dashicons-controls-volumeon"></span>
        <?php esc_html_e('Audio', 'text-to-speech-tts'); ?>
        <svg class="tts-nav-chevron" width="10" height="6" viewBox="0 0 10 6" fill="none"><path d="M1 1l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </button>
      <div class="tts-nav-items">
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-voices')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('voices'); ?>">
          <?php esc_html_e('Voices', 'text-to-speech-tts'); ?>
        </a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-player')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('player'); ?>">
          <?php esc_html_e('Player', 'text-to-speech-tts'); ?>
        </a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-content')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('content'); ?>">
          <?php esc_html_e('Content', 'text-to-speech-tts'); ?>
        </a>
      </div>
    </div>

    <!-- Tools -->
    <div class="tts-nav-group" data-group="tools">
      <button type="button" class="tts-nav-label tts-nav-toggle">
        <span class="dashicons dashicons-admin-tools"></span>
        <?php esc_html_e('Tools', 'text-to-speech-tts'); ?>
        <svg class="tts-nav-chevron" width="10" height="6" viewBox="0 0 10 6" fill="none"><path d="M1 1l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </button>
      <div class="tts-nav-items">
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-generator')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('generator'); ?>">
          <?php esc_html_e('Shortcode Generator', 'text-to-speech-tts'); ?>
        </a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-word-replacement')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('word-replacement'); ?>">
          <?php esc_html_e('Word Replacement', 'text-to-speech-tts'); ?>
        </a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-css-selectors')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('css-selectors'); ?>">
          <?php esc_html_e('CSS Selectors', 'text-to-speech-tts'); ?>
        </a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-speech-to-text')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('speech-to-text'); ?>">
          <?php esc_html_e('Speech to Text', 'text-to-speech-tts'); ?>
        </a>
      </div>
    </div>

    <!-- Stats -->
    <div class="tts-nav-group" data-group="stats">
      <button type="button" class="tts-nav-label tts-nav-toggle">
        <span class="dashicons dashicons-chart-bar"></span>
        <?php esc_html_e('Stats', 'text-to-speech-tts'); ?>
        <svg class="tts-nav-chevron" width="10" height="6" viewBox="0 0 10 6" fill="none"><path d="M1 1l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </button>
      <div class="tts-nav-items">
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-my-stats-voices')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('my-stats'); ?>">
          <?php esc_html_e('My Stats', 'text-to-speech-tts'); ?>
        </a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-statistics')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('statistics'); ?>">
          <?php esc_html_e('Audio Statistics', 'text-to-speech-tts'); ?>
        </a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-audio-library')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('audio-library'); ?>">
          <?php esc_html_e('Audio Library', 'text-to-speech-tts'); ?>
        </a>
      </div>
    </div>

    <!-- Account -->
    <div class="tts-nav-group" data-group="account">
      <button type="button" class="tts-nav-label tts-nav-toggle">
        <span class="dashicons dashicons-admin-users"></span>
        <?php esc_html_e('Account', 'text-to-speech-tts'); ?>
        <svg class="tts-nav-chevron" width="10" height="6" viewBox="0 0 10 6" fill="none"><path d="M1 1l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </button>
      <div class="tts-nav-items">
        <?php if (Mementor_TTS_Connect::get_connection_status() === 'connected') : ?>
          <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-account')); ?>"
             class="tts-nav-item<?php echo $sidebar_active('account'); ?>">
            <?php esc_html_e('My Plan & Credits', 'text-to-speech-tts'); ?>
          </a>
        <?php endif; ?>

        <?php if ( get_option( 'tts_site_plan_slug', 'free' ) === 'free' && $sidebar_should_show_menu_item('license') ) : ?>
          <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-upgrade')); ?>"
             class="tts-nav-item<?php echo $sidebar_active('license'); ?>">
            <?php esc_html_e('Upgrade Plan', 'text-to-speech-tts'); ?>
          </a>
        <?php endif; ?>

        <?php if ($sidebar_can_see_white_label()) : ?>
          <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-white-label')); ?>"
             class="tts-nav-item<?php echo $sidebar_active('white-label'); ?>">
            <?php esc_html_e('White Label', 'text-to-speech-tts'); ?>
          </a>
        <?php endif; ?>

        <?php if ($sidebar_should_show_menu_item('affiliate')) : ?>
          <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-affiliate')); ?>"
             class="tts-nav-item<?php echo $sidebar_active('affiliate'); ?>">
            <?php esc_html_e('Affiliate Program', 'text-to-speech-tts'); ?>
          </a>
        <?php endif; ?>
      </div>
    </div>

    <!-- System -->
    <div class="tts-nav-group" data-group="system">
      <button type="button" class="tts-nav-label tts-nav-toggle">
        <span class="dashicons dashicons-admin-generic"></span>
        <?php esc_html_e('System & Help', 'text-to-speech-tts'); ?>
        <svg class="tts-nav-chevron" width="10" height="6" viewBox="0 0 10 6" fill="none"><path d="M1 1l4 4 4-4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
      </button>
      <div class="tts-nav-items">
        <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-advanced')); ?>"
           class="tts-nav-item<?php echo $sidebar_active('advanced'); ?>">
          <?php esc_html_e('Advanced', 'text-to-speech-tts'); ?>
        </a>

        <?php if ($sidebar_is_pro && $sidebar_should_show_menu_item('pro-help')) : ?>
          <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-pro-help')); ?>"
             class="tts-nav-item<?php echo $sidebar_active('pro-support'); ?>">
            <?php esc_html_e('PRO Support', 'text-to-speech-tts'); ?>
          </a>
        <?php endif; ?>

        <?php if (!$sidebar_is_pro) : ?>
          <a href="https://wordpress.org/support/plugin/text-to-speech-tts/" target="_blank" rel="noopener"
             class="tts-nav-item">
            <?php esc_html_e('Support Forum', 'text-to-speech-tts'); ?>
          </a>
        <?php endif; ?>

        <?php if ($sidebar_should_show_menu_item('documentation')) : ?>
          <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-documentation')); ?>"
             class="tts-nav-item<?php echo $sidebar_active('documentation'); ?>">
            <?php esc_html_e('Documentation', 'text-to-speech-tts'); ?>
          </a>
        <?php endif; ?>
      </div>
    </div>

    <!-- Add More Credits CTA — after System group -->
    <?php if ($sidebar_should_show_menu_item('add-credits') && Mementor_TTS_Connect::get_connection_status() === 'connected' && ! in_array( $sidebar_current_slug, array( 'account', 'license' ), true ) ) : ?>
    <div class="tts-sidebar-cta">
      <a href="<?php echo esc_url(admin_url('admin.php?page=text-to-speech-tts-account#top-ups')); ?>"
         class="tts-btn tts-btn-primary tts-sidebar-cta-btn">
        <?php esc_html_e('Add More Credits', 'text-to-speech-tts'); ?>
      </a>
    </div>
    <?php endif; ?>

  </nav>

</aside>
<script>
(function(){
  var STORAGE_KEY = 'tts_nav_open_groups';

  function getSavedState() {
    try {
      var raw = localStorage.getItem(STORAGE_KEY);
      return raw ? JSON.parse(raw) : null;
    } catch(e) { return null; }
  }

  function saveState() {
    var open = [];
    document.querySelectorAll('.tts-nav-group.open').forEach(function(g) {
      if (g.dataset.group) open.push(g.dataset.group);
    });
    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(open)); } catch(e) {}
  }

  // Restore saved state, or fall back to defaults (audio + active group)
  var saved = getSavedState();
  document.querySelectorAll('.tts-nav-group').forEach(function(group) {
    if (saved) {
      if (saved.indexOf(group.dataset.group) !== -1) {
        group.classList.add('open');
      }
    } else {
      if (group.dataset.group === 'audio' || group.querySelector('.tts-nav-item.active')) {
        group.classList.add('open');
      }
    }
  });

  // Always ensure the group containing the active item is open
  document.querySelectorAll('.tts-nav-group').forEach(function(group) {
    if (group.querySelector('.tts-nav-item.active')) {
      group.classList.add('open');
    }
  });

  // Toggle on click + persist
  document.querySelectorAll('.tts-nav-toggle').forEach(function(btn) {
    btn.addEventListener('click', function() {
      btn.closest('.tts-nav-group').classList.toggle('open');
      saveState();
    });
  });

  // Save initial state
  saveState();
})();
</script>
