<?php


namespace Mnv\Core\Interfaces;


use Mnv\Core\Utilities\CUtil;

class AdminSorting
{

    var $by_name;
    var $ord_name;
    var $table_id;
    var $by_initial;
    var $order_initial;

    protected $field;
    protected $order;

    /**
     * @param string $table_id
     * @param string|false $by_initial
     * @param string|false $order_initial
     * @param string $by_name
     * @param string $ord_name
     */
    public function __construct($table_id, $by_initial=false, $order_initial=false, $by_name="by", $ord_name="order")
    {
        $this->by_name = $by_name;
        $this->ord_name = $ord_name;
        $this->table_id = preg_replace('/[^a-z0-9_]/i', '', $table_id);
        $this->by_initial = $by_initial;
        $this->order_initial = $order_initial;

        $needUserByField = false;
        $needUserOrder = false;
        if(isset($GLOBALS[$this->by_name])) {
            \Bitrix\Main\Application::getInstance()->getSession()["SESS_SORT_BY"][$this->table_id] = $GLOBALS[$this->by_name];
        } elseif(isset(\Bitrix\Main\Application::getInstance()->getSession()["SESS_SORT_BY"][$this->table_id])) {
            $GLOBALS[$this->by_name] = \Bitrix\Main\Application::getInstance()->getSession()["SESS_SORT_BY"][$this->table_id];
        } else {
            $needUserByField = true;
        }

        if(isset($GLOBALS[$this->ord_name])){
            \Bitrix\Main\Application::getInstance()->getSession()["SESS_SORT_ORDER"][$this->table_id] = $GLOBALS[$this->ord_name];
        } elseif(isset(\Bitrix\Main\Application::getInstance()->getSession()["SESS_SORT_ORDER"][$this->table_id])) {
            $GLOBALS[$this->ord_name] = \Bitrix\Main\Application::getInstance()->getSession()["SESS_SORT_ORDER"][$this->table_id];
        } else {
            $needUserOrder = true;
        }

        if ($needUserByField || $needUserOrder) {
            $userSorting = $this->getUserSorting();
            if ($needUserByField) {
                if (!empty($userSorting["by"])) {
                    $GLOBALS[$this->by_name] = $userSorting["by"];
                } else if ($this->by_initial !== false) {
                    $GLOBALS[$this->by_name] = $this->by_initial;
                }
            }

            if ($needUserOrder){
                if(!empty($userSorting["order"])) {
                    $GLOBALS[$this->ord_name] = $userSorting["order"];
                } else if($this->order_initial !== false) {
                    $GLOBALS[$this->ord_name] = $this->order_initial;
                }
            }
        }

        $this->field = $GLOBALS[$this->by_name];
        $this->order = $GLOBALS[$this->ord_name];
    }


    /**
     * @param string $text
     * @param string $sort_by
     * @param string|false $alt_title
     * @param string $baseCssClass
     * @return string
     */
    public function Show($text, $sort_by, $alt_title = false, $baseCssClass = "")
    {
        $ord = "asc";
        $class = "";
        $title = "admin_lib_sort_title" . ($alt_title ?: $text);

        if(mb_strtolower($this->field) == mb_strtolower($sort_by)) {
            if(mb_strtolower($this->order) == "desc") {
                $class = "-down";
                $title .= "admin_lib_sort_down";
            } else {
                $class = "-up";
                $title .= "admin_lib_sort_up";
                $ord = "desc";
            }
        }

        $path = $_SERVER["REQUEST_URI"];
        $sep = "?";
        if ($_SERVER["QUERY_STRING"] <> "") {
            $path = preg_replace("/([?&])".$this->by_name."=[^&]*[&]*/i", "\\1", $path);
            $path = preg_replace("/([?&])".$this->ord_name."=[^&]*[&]*/i", "\\1", $path);
            $path = preg_replace("/([?&])mode=[^&]*[&]*/i", "\\1", $path);
            $path = preg_replace("/([?&])table_id=[^&]*[&]*/i", "\\1", $path);
            $path = preg_replace("/([?&])action=[^&]*[&]*/i", "\\1", $path);
            $sep = "&";
        }
        if (($last = mb_substr($path,-1,1)) == "?" || $last == "&") {
            $sep = "";
        }
        $url = $path.$sep.$this->by_name."=".$sort_by."&".$this->ord_name."=".($class <> ""? $ord:"");

        return 'class="'.$baseCssClass.' adm-list-table-cell-sort'.$class.'" onclick="'.$this->table_id.'.Sort(\''.htmlspecialcharsbx(CUtil::addslashes($url)).'\', '.($class <> "" ? "false" : "true").', arguments);" title="'.$title.'"';
    }

}