<?php

namespace Mnv\Core;

use Mnv\Core\Singleton\SingletonTrait;
use Mnv\Core\Utilities\Cookie\Session;

class SortTable
{

    use SingletonTrait;

    protected $sortable = [];

    /**
     * @param $tableId
     * @param $sortBy
     * @param $sortOrder
     *
     * @return void
     */
    public function setSort($tableId, $sortBy, $sortOrder): void
    {
        Session::regenerate(true);

        $_SESSION[$tableId]['column']            = $sortBy;
        $_SESSION[$tableId]['sort']              = $sortOrder;
        $_SESSION[$tableId]['last_sort_by']      = $sortBy;
        $_SESSION[$tableId]['last_sort_order']   = $sortOrder;
    }

    public function getSort($tableId): ?array
    {
        if (Session::has($tableId)) {
            $result[$tableId] = array(
                'last_sort_by' => Session::get($tableId)['last_sort_by'] ?? null,
                'last_sort_order'=> Session::get($tableId)['last_sort_order'] ?? null);

            return $result;
        }

        return null;
    }

    public function clearSort($tableId): void
    {
        if (Session::has($tableId)) {
            Session::delete($tableId);
        }
    }

    public function viewSortable($tableId): ?array
    {
        if (Session::has($tableId)) {
            return array(
                'column'            => Session::get($tableId)['column'] ?? null,
                'sort'              => Session::get($tableId)['sort'] ?? 'neutral',
                'last_sort_by'      => Session::get($tableId)['last_sort_by'] ?? null,
                'last_sort_order'   => Session::get($tableId)['last_sort_order'] ?? null);

        }

        return null;
    }


}