<?php


namespace Mnv\Core\Interfaces;

/**
 * Class AdminContextMenu
 * @package Mnv\Core\Interfaces
 */
/* Context links menu for edit forms */
class AdminContextMenu
{
    var $items;
    var $additional_items;
    var $bMenuAdded = false;
    var $bRightBarAdded = false;
    var $isSidePanel = false;
    var $isPublicMode = false;
    var $isPublicSidePanel = false;
    var $isPublicFrame = false;

    public function __construct($items, $additional_items = array())
    {
        $this->isPublicMode = 1;

        $this->prepareItemLink($items);
        $this->prepareItemLink($additional_items);

        $this->items = $items;
        $this->additional_items = $additional_items;
    }

    function prepareItemLink(array &$listItems)
    {

        foreach ($listItems as &$item) {
            if (!empty($item["LINK"])) {

                $selfFolderUrl = (defined("SELF_FOLDER_URL") ? SELF_FOLDER_URL : "/admin/");
                $reqValue = "/".str_replace("/", "\/", $selfFolderUrl)."/i";
                if (!preg_match($reqValue, $item["LINK"]) && !preg_match("/javascript:/", $item["LINK"])) {
                    $item["LINK"] = $selfFolderUrl.$item["LINK"];
                }
            }

            switch ($item["ICON"]) {
                case "btn_list":
                    if ($this->isSidePanel) {
                        if (isset($item["TYPE"])) {
                            switch ($item["TYPE"]){
                                case "default":
                                    global $adminSidePanelHelper;
                                    $item["LINK"] = $adminSidePanelHelper->setDefaultQueryParams($item["LINK"]);
                                    break;
                            }
                        }else {
                            if (empty($item["ONCLICK"])) {
                                $item["ONCLICK"] = "top.BX.onCustomEvent('SidePanel:close');";
                            }
                        }
                    }else {
                        if (!empty($item["LINK"]) && preg_match("/set_default/", $item["LINK"]))
                            $item["LINK"] .= "&apply_filter=Y";
                    }
                    break;
                case "delete":
                case "btn_delete":
                    if ($this->isSidePanel) {
                        if (empty($item["ONCLICK"])) {
                            $link = $item["ACTION"] ? $item["ACTION"] : $item["LINK"];
                            if (preg_match("/javascript:/", $item["LINK"]) || !empty($item["ACTION"])){
                                if (preg_match("/window.location=(?P<postUrl>[^<]+(\"|\'))/", $link, $found) ||
                                    preg_match("/window.location.href=(?P<postUrl>[^<]+(\"|\'))/", $link, $found))
                                {
                                    $confirmText = "";
                                    $postUrl = $found["postUrl"];
                                    if (preg_match("/confirm\((?P<text>[^<]+(\"|\'))\)/", $link, $found)){
                                        $confirmText = $found["text"];
                                    }

                                    if ($confirmText && $postUrl){
                                        $item["ONCLICK"] = "if(confirm(".$confirmText.
                                            ")) top.BX.onCustomEvent('AdminSidePanel:onSendRequest', [".$postUrl."]);";
                                    }

                                }else{
                                    $item["ONCLICK"] = $item["LINK"];
                                }
                                unset($item["LINK"]);
                                unset($item["ACTION"]);
                            }
                        }
                    }
                    break;
            }

            if (!empty($item["MENU"])) {
                $this->prepareItemLink($item["MENU"]);
            }
        }
    }

    public function show()
    {
        if (empty($this->items) && empty($this->additional_items)) {
            return;
        }

        $bar = $this->beginBar();

        $bar .= $this->beginLeftBar();
        foreach($this->items as $item) {
            $bar .= $this->button($item);
        }

        $bar .= $this->endLeftBar();

        if (!empty($this->additional_items)) {

            $bar .= $this->beginRightBar();
            $bar .= '<div class="dropdown">';
                $bar .= '<a class="text-body dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" title="Настроить внешний вид списка"><i class="ph-gear"></i></a>';
                $bar .= '<div class="dropdown-menu" style="">';
                foreach ($this->additional_items as $additional_item) {
                    $bar .= $this->Additional($additional_item);
                }
                $bar .= '</div>';
            $bar .= '</div>';
            $bar .= $this->endRightBar();
        }

        $bar .= $this->EndBar();

        return $bar;
    }

	protected function beginBar()
    {
    	return '<div class="card-header d-flex flex-wrap">';
    }

    protected function endBar()
    {
	   return '</div>';
	}

	protected function beginLeftBar()
	{
		return '<div class="mb-0">';
	}

	protected function endLeftBar()
	{
        return'</div>';
	}

	protected function beginRightBar()
	{
		return '<div class="d-inline-flex ms-auto">';
	}

	protected function endRightBar()
	{
        return'</div>';
	}

    public function GetClassByID($icon_id)
    {

        switch ($icon_id) {
            case 'btn_new':
                return 'ph-plus';
            case 'btn_copy':
                return 'ph-copy-simple';
            case 'btn_delete':
                return 'ph-trash';
            case 'btn_desktop_gadgets':
                return 'btn btn-primary';
            case 'btn_desktop_settings':
                return 'ph-gear';
            case 'btn_active':
                return 'btn btn-active';
            case 'btn_green':
                return 'btn btn-success';
        }

        return '';
    }

    protected function GetActiveClassByID($icon_id)
    {
        return 'adm-btn-active';
    }

    /**
     * @param array $item
     */
    public function button(array $item)
    {
        // $item["ICON"]
        $html = '';
        if (isset($item["HTML"]) && $item["HTML"] <> "") {
            $html .= '<span class="adm-list-table-top-wrapper">'.$item['HTML'].'</span>';
        }
        elseif(!empty($item["MENU"])) {
            $icon = $this->GetClassByID($item["ICON"]);
            $html .= '<a href="javascript:void(0)" hidefocus="true" onclick="" class="btn btn-sm btn-link" title="' . $item["TITLE"] . '"><i class="' . $icon . '"></i> ' . $item["TEXT"] . '</a>';
        }
        else {
            $link = htmlspecialcharsbx($item["LINK"], ENT_COMPAT, false);

            if ($item['ICON'] == 'btn_list') {
                if ($this->isPublicFrame) {
                    $html .= '<a target="_top"  href="' . ($item["ONCLICK"] <> ''? 'javascript:void(0)' : $link) . '" ' . $item["LINK_PARAM"] . ' class="adm-detail-toolbar-btn" title="' . $item["TITLE"]. $item["ICON"] . '" ' . ($item["ONCLICK"] <> '' ? ' onclick="'.htmlspecialcharsbx($item["ONCLICK"]).'"':'') . ' ' . (!empty($item["ICON"])? ' id="'.$item["ICON"].'"':'') . '><span class="adm-detail-toolbar-btn-l"></span><span class="adm-detail-toolbar-btn-text">' . $item["TEXT"] . '</span><span class="adm-detail-toolbar-btn-r"></span></a>';
                } else {
                    $html .=  '<a  href="' . ($item["ONCLICK"] <> ''? 'javascript:void(0)' : $link) . '" ' . $item["LINK_PARAM"] . ' class="adm-detail-toolbar-btn" title="' . $item["TITLE"]. $item["ICON"] .'"' . ($item["ONCLICK"] <> ''? ' onclick="'.htmlspecialcharsbx($item["ONCLICK"]).'"':'') . ' ' . (!empty($item["ICON"])? ' id="'.$item["ICON"].'"':'') . '><span class="adm-detail-toolbar-btn-l"></span><span class="adm-detail-toolbar-btn-text">' .$item["TEXT"] . '</span><span class="adm-detail-toolbar-btn-r"></span></a>';
                }
            } else {
                $icon = $this->GetClassByID($item["ICON"]);
//                print_r($icon);
                if ($this->isPublicFrame) {
                    $html .=  '<a target="_top" href="' . ($item["ONCLICK"] <> ''? 'javascript:void(0)' : $link) . '" '. $item["LINK_PARAM"] . ' class="adm-btn" title="' . $item["TITLE"]. $item["ICON"] . '"' . ($item["ONCLICK"] <> ''? ' onclick="'.htmlspecialcharsbx($item["ONCLICK"]).'"' : '') . ' ' . (!empty($item["ICON"])? ' id="'.$item["ICON"].'"':'') . '>' . $item["TEXT"] . '</a>';
                } else {
                	if (isset($item["LINK_PARAM"])) {
                        $html .= '<a href="' . (isset($item["ONCLICK"]) && $item["ONCLICK"] <> '' ? 'javascript:void(0)' : $link) . '" ' .  $item["LINK_PARAM"] . ' class="adm-btn" title="' . $item["TITLE"] . $item["ICON"] . '"' . ($item["ONCLICK"] <> '' ? ' onclick="' . htmlspecialcharsbx($item["ONCLICK"]) . '"' : '') . ' ' . (!empty($item["ICON"]) ? ' id="' . $item["ICON"] . '"' : '') . '>' . $item["TEXT"] . '</a>';
                    }else {
//                        print_r($item);
                        if (isset($item["ONCLICK"]) && $item["ONCLICK"] <> '') {
                            $html .= '<a href="javascript:void(0)"  class="btn btn-sm btn-primary" title="' . $item["TITLE"] . '"' . ($item["ONCLICK"] <> '' ? ' onclick="' . htmlspecialcharsbx($item["ONCLICK"]) . '"' : '') . '><i class="' .  $icon . '"></i> ' . $item["TEXT"] . '</a>';

                        } else {

                            $html .= '<a href="' . $link . '" ' . ' class="btn btn-sm btn-primary" title="' . $item["TITLE"] . '"><i class="' .  $icon . ' me-2"></i>' . $item["TEXT"] . '</a>';
                        }
//
                    }
                }
            }
        }

        return $html;
    }
    protected function Additional($additional_item)
    {
        if (isset($additional_item['LINK'])) {
            $html = '<a href="' . $additional_item['LINK'] .'" class="dropdown-item export" data-value="'. $additional_item['TEXT'] . '" title="' . $additional_item['TITLE'] . '"><i class="ph-file-xls me-2"></i>' .  $additional_item['TITLE'] . '</a>';
        } else {

            $html = '<div class="dropdown-divider"></div>';
            $html .= '<a class="dropdown-item export" data-bs-toggle="offcanvas" data-bs-target="#' . $additional_item['CLICK'] . '" title="' .  $additional_item['TITLE'] . '"><i class="ph-gear me-2"></i>' .  $additional_item['TITLE'] . '</a>';
        }
        return $html;
    }


//    protected function Additional()
//    {
////        $html = ' <div class="d-inline-flex ms-auto">';
//            $html = '<div class="dropdown">';
//                $html .= '<a class="text-body dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false" title="Настроить внешний вид списка"><i class="ph-gear"></i></a>';
//                $html .= '<div class="dropdown-menu" style="">';
//                    $html .= '<a href="/admin/projects?action=export&type_file=xlsx" class="dropdown-item export" data-value="xlsx"><i class="ph-file-xls me-2"></i>Экспорт в XLSX</a>';
//                    $html .= '<a href="/admin/projects?action=export&type_file=xls" class="dropdown-item export" data-value="xls"><i class="ph-file-xls me-2"></i>Экспорт в XLS</a>';
//                    $html .= '<a href="/admin/projects?action=export&type_file=csv" class="dropdown-item export" data-value="csv"><i class="ph-file-xls me-2"></i>Экспорт в CSV</a>';
//                    $html .= '<div class="dropdown-divider"></div>';
//                    $html .= '<a class="dropdown-item export" data-bs-toggle="offcanvas" data-bs-target="#setting_table"><i class="ph-gear me-2"></i>Настроить</a>';
//                $html .= '</div>';
//            $html .= '</div>';
////        $html .= '</div>';
//
//       return $html;
//    }
}