<?php


namespace Mnv\Core\Interfaces;

use Mnv\Core\Utilities\CUtil;

/**
 * Class AdminListRow
 * @package Mnv\Core\Interfaces
 */
class AdminListRow
{

    public $aHeaders = array();
    public $aHeadersID = array();
    public $aFields = array();
    public $aActions = array();
    public $table_id;
    public $indexFields = 0;
    public $edit = false;
    public $id;
    public $aFeatures = array();
    public $bEditMode = false;
    public $arRes;
    public $link;
    public $title;
    public $pList;

    public $isPublicMode;

    protected $config;


    /**
     * AdminListRow constructor.
     * @param array &$aHeaders
     * @param string $table_id
     */
    public function __construct(&$aHeaders, $table_id)
    {
        $this->aHeaders = $aHeaders;
        $this->aHeadersID = array_keys($aHeaders);
        $this->table_id = $table_id;

        $this->config = [];
    }

    public function setPublicModeState(bool $mode): void
    {
        $this->isPublicMode = $mode;
    }

    public function addField($id, $text, $edit = false, $isHtml = true)
    {
        $this->aFields[$id] = array();
        if ($edit !== false) {
            $this->aFields[$id]["edit"] = array("type" => "input", "value" => $edit);
            $this->pList->bCanBeEdited = true;
        }
        $type = $isHtml ? "html" : "text";
        $this->aFields[$id]["view"] = array("type" => $type, "value" => $text);
    }

    /**
     * @param string $id
     * @param array|boolean $arAttributes
     * @return void
     */
    public function AddCheckField($id, $arAttributes = array())
    {
        if ($arAttributes !== false)  {
            $this->aFields[$id]["edit"] = Array("type"=>"checkbox", "attributes"=>$arAttributes);
            $this->pList->bCanBeEdited = true;
        }
        $this->aFields[$id]["view"] = Array("type"=>"checkbox");
    }

    /**
     * @param string $id
     * @param array $arValues
     * @param array|boolean $arAttributes
     * @return void
     */
    function AddSelectField($id, $arValues = Array(), $arAttributes = Array())
    {
        if($arAttributes !== false) {
            $this->aFields[$id]["edit"] = Array("type"=>"select", "values"=>$arValues, "attributes"=>$arAttributes);
            $this->pList->bCanBeEdited = true;
        }
        $this->aFields[$id]["view"] = Array("type"=>"select", "values"=>$arValues);
    }

    /**
     * @param string $id
     * @param array|boolean $arAttributes
     * @return void
     */
    function AddInputField($id, $arAttributes = array())
    {
        if($arAttributes !== false) {
            $this->aFields[$id]["edit"] = Array("type"=>"input", "attributes"=>$arAttributes);
            $this->pList->bCanBeEdited = true;
        }
    }

    /**
     * @param string $id
     * @param bool|array $showInfo
     * @param array $inputs
     * @return void
     */
    function addFileField($id, $showInfo = false, $inputs = array())
    {
        $this->aFields[$id]["edit"] = array(
            "type"      => "file",
            "showInfo"  => $showInfo,
            "inputs"    => $inputs,
        );
        $this->pList->bCanBeEdited = true;
        $this->addViewFileField($id, $showInfo);
    }

    /**
     * @param string $id
     * @param bool|array $showInfo
     * @return void
     */
    function addViewFileField($id, $showInfo = false)
    {
        $this->aFields[$id]["view"] = array(
            "type"      => "file",
            "showInfo"  => $showInfo,
            "inputs"    => array(
                'upload'        => false,
                'medialib'      => false,
                'file_dialog'   => false,
                'cloud'         => false,
                'del'           => false,
                'description'   => false,
            ),
        );
    }


    public function display(): string
    {
        $sDefAction = $sDefTitle = "";

        if (!$this->bEditMode) {
            if (!empty($this->link)) {
                $sDefAction = $this->getActionLink($this->link);
                $sDefTitle = $this->title;
            } else {
                foreach($this->aActions as $action) {
                    if(isset($action["default"]) && $action["default"] == true) {
                        $sDefAction = $this->getActionsItemLink($action);
                        $sDefTitle = (!empty($action["TITLE"]) ? $action["TITLE"] : $action["TEXT"]);
                        break;
                    }
                }
            }


            $sDefAction = htmlspecialcharsbx($sDefAction);
            $sDefTitle = htmlspecialcharsbx($sDefTitle);
        }

        $class = '';

        if (isset($this->arRes['status']) && $this->arRes['status'] == 'H') {
            $class .= 'table-warning';
        }

//        print_r($this->arRes);
        $tr = '<tr id="' . mb_substr($this->table_id, 0, -1) . '-' . current($this->arRes) . '" class=" ' . $class . '">';

        if(count($this->pList->arActions)>0 || $this->pList->bCanBeEdited) {
            $tr .= '<td class="text-center"><div class="form-check"><input type="checkbox" class="form-check-input content_list_check" name="id[]" value="' .$this->id . '" data-id="' .$this->id . '"></div></td>';
        }

        end($this->pList->aVisibleHeaders);
        $last_id = key($this->pList->aVisibleHeaders);
        reset($this->pList->aVisibleHeaders);

        $bVarsFromForm = ($this->bEditMode && is_array($this->pList->arUpdateErrorIDs) && in_array($this->id, $this->pList->arUpdateErrorIDs));

        foreach ($this->pList->aVisibleHeaders as $id => $header_props) {
            $attrs = '';
            $field = $row->aFields[$id] ?? [];

            if (isset($header_props["class"])) {
                $attrs .= 'class="' . $header_props["class"] . '"';
            }

//            if (isset($header_props["font"])) {
//                $attrs .= 'class="' . $header_props["font"] . '"';
//            }

//            print_r($this->arRes);
           if (is_string($this->arRes[$id])) {
                $val = trim($this->arRes[$id]);
            } else {
                $val = $this->arRes[$id];
            }

            $tr .= '<td ' . $attrs . '>';
            $tr .= ((string) $val <> "" ? $val : '&nbsp;');
            $tr .=  '</td>';
        }


//        if(!empty($this->aActions)) {
//            $sMenuItems = htmlspecialcharsbx(CAdminPopup::PhpToJavaScript($this->aActions));
//            $tr .= '<tr class="adm-list-table-row' . (isset($this->aFeatures["footer"]) && $this->aFeatures["footer"] == true? ' footer':'') . ' ' . $this->bEditMode ? ' adm-table-row-active' : '' . '"' . ($sMenuItems <> ""? ' oncontextmenu="return '.$sMenuItems.';"':'') . ' ' . ($sDefAction <> ""? ' ondblclick="'.$sDefAction.'"'.(!empty($sDefTitle) ? ' title="'. "admin_lib_list_double_click" .' '. $sDefTitle.'"':''):'') . '>';
//        }
//        if(count($this->pList->arActions) > 0 || $this->pList->bCanBeEdited) {
//            $check_id = RandString(5);
//
//            $tr .= '<td class="adm-list-table-cell adm-list-table-checkbox adm-list-table-checkbox-hover' . $this->bReadOnly ? ' adm-list-table-checkbox-disabled':'' . '">';
//            // '<input type="checkbox" class="adm-checkbox adm-designed-checkbox" name="ID[]" id="' . $this->table_id . '_' . $this->id . '" value="' . $this->id . '" autocomplete="off" title="admin_lib_list_check" ' . $this->bReadOnly ? ' disabled="disabled"': '' . ' ' . $this->bEditMode ? ' checked="checked" disabled="disabled"' : '' . '/>';
//            '<label class="adm-designed-checkbox-label adm-checkbox" for="' . $this->table_id . '_' . $this->id .'_' . $check_id . '"></label>';
//            '</td>';
//        }

        if ($this->pList->bShowActions) {
            if (!empty($this->aActions)) {
                $td  = '<td class="text-end">';
                    $td  .= '<div class="d-inline-flex">';

                    if (!empty($this->link)) {
                            $td .= $this->getActionLink($this->link);
                        }

                        $td .=  $this->showAction();
                    $td .= '</div>';
                $td .= '</td>';
            } else {
                $td = '<td class="text-end"></td>';
            }

            $tr .= $td;
        }

        $tr .= '</tr>';

        return $tr;
    }

    protected function showAction(): string
    {
        $act = '<div class="list-icons-item dropdown"><a class="text-body" data-bs-toggle="dropdown"><i class="ph-list"></i></a>';
        $act .= '<div class="dropdown-menu dropdown-menu-end">';
        foreach ($this->aActions as $aAction) {
            if (isset($aAction['TYPE'])) {
                if ($aAction['TYPE'] == 'view') {
                    $act .= '<a class="dropdown-item" href="' . $aAction['ACTION'] . '" target="_blank">'. $aAction['ICON'] .' '. $aAction['TEXT'] .'</a>';
                }

                if ($aAction['TYPE'] == 'edit') {
                    $act .= '<a class="dropdown-item" href="' . $aAction['ACTION'] . '">'. $aAction['ICON'] .' '. $aAction['TEXT'] .' </a>';
                }

                if ($aAction['TYPE'] == 'status') {
                    if ($aAction['STATUS'] == 'V') {
                        $act .= '<button class="dropdown-item ajax_action" data-module="' . $aAction['MODULE'] . '" data-action="status" data-id="' . $aAction['ID'] . '"><i class="ph-eye me-2"></i> ' . $aAction['TEXT'] . '</button>';
                    } else {
                        $act .= '<button class="dropdown-item ajax_action" data-module="' . $aAction['MODULE'] . '" data-action="status" data-id="' . $aAction['ID'] . '"><i class="ph-eye-slash me-2"></i> ' . $aAction['TEXT'] . '</button>';
                    }
                }

                if ($aAction['TYPE'] == 'delete') {
                    $act .= '<button class="dropdown-item text-danger" onclick="' . $aAction['ACTION'] . '">'. $aAction['ICON'] .' '. $aAction['TEXT'] .'</button>';
                }
            }

            if (isset($aAction['SEPARATOR']) && $aAction['SEPARATOR'] == true) {
                $act .= '<div class="dropdown-divider"></div>';
            }

        }
        $act .= '</div>';
        $act .= '</div>';

        return $act;
    }


    protected function _attrGen($attr)
    {
        $res = '';
        foreach ($attr as $name => $val) {
            $res .= ' ' . htmlspecialcharsbx($name) . '="' . htmlspecialcharsbx($val) . '"';
        }

        return $res;
    }

    public function addActions($aActions): void
    {
        if (is_array($aActions)) {
            $this->aActions = $aActions;
        }
    }

    /**
     * @param string $url
     * @return string
     */
    protected function getActionLink(string $url): string
    {
        return '<a class="mx-2" href="' . $url . '"><i class="ph-pen"></i></a>';
    }

    /**
     * @param array $item
     * @return bool
     */
    protected function getActionsItemLink(array $item)
    {
        return (!empty($item["ACTION"]) ? $item["ACTION"] : $this->getActionLink($item["LINK"]));
    }

}