<?php
namespace Storzen;
defined('ABSPATH') || exit;

class Menu {
    /** @var string */     protected $slug;
    /** @var string */     protected $title;
    /** @var string */     protected $nav_label = '';
    /** @var string */     protected $icon       = '';
    /** @var bool   */     protected $pro        = false;
    /** @var Panel|null */ protected $panel      = null;
    /** @var Tab[] */      protected $tabs       = array();

    /** @return static */
    public static function make( $slug, $title, $nav_label = '' ) {
        return new static( $slug, $title, $nav_label );
    }

    public function __construct( $slug, $title, $nav_label = '' ) {
        $this->slug      = $slug;
        $this->title     = $title;
        $this->nav_label = $nav_label ? $nav_label : $title;
    }

    /** @return static */ public function set_icon( $i )      { $this->icon = $i;      return $this; }
    /** @return static */ public function icon( $i )          { return $this->set_icon($i); }
    /** @return static */ public function set_nav_label( $l ) { $this->nav_label = $l; return $this; }
    /** @return static */ public function nav_label( $l )     { return $this->set_nav_label($l); }
    /** @return static */ public function set_pro( $p = true ) { $this->pro = (bool)$p; return $this; }
    /** @return static */ public function pro( $p = true )     { return $this->set_pro($p); }
    public function is_pro() { return $this->pro; }

    /** @return static */
    public function add_tab( Tab $tab ) {
        $tab->set_menu( $this );
        $this->tabs[] = $tab;
        return $this;
    }

    public function set_panel( Panel $panel ) { $this->panel = $panel; }

    public function get_slug()      { return $this->slug; }
    public function get_title()     { return $this->title; }
    public function get_nav_label() { return $this->nav_label; }
    public function get_icon()      { return $this->icon; }
    public function get_tabs()      { return $this->tabs; }
    public function get_panel()     { return $this->panel; }

    public function find_tab( $slug ) {
        foreach ( $this->tabs as $t ) {
            if ( $t->get_slug() === $slug ) return $t;
        }
        return null;
    }

    public function get_page_slug() {
        if ( ! $this->panel ) {
            return $this->slug;
        }

        // First menu uses the parent panel slug so WordPress does not show a duplicate submenu.
        $menus = $this->panel->get_menus();
        if ( ! empty( $menus ) && $menus[0]->get_slug() === $this->slug ) {
            return $this->panel->get_slug();
        }

        return $this->panel->get_slug() . '--' . $this->slug;
    }
}
