<?php

use KupShop\KupShopBundle\Exception\RedirectException;

if (!function_exists('getTextString')) {
    // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
    /**
     * @deprecated Use translate($key, $section) instead
     */
    function getTextString($section, $key)
    {
        return translate($key, $section);
    }
}
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
function findRight($right, $var = null)
{
    // kdyz nejsou dodany vlastni prava
    if (is_null($var)) {
        // kdyz se jedna o superadmina
        if (isSuperuser()) {
            return true;
        }

        $adminUser = getAdminUser();
        $var = $adminUser ? $adminUser['privilege'] : '';
    }
    if (preg_match("/\b{$right}/i", $var) || preg_match('/ALL_RIGHTS/i', $var)) {
        return true;
    } else {
        return false;
    }
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
function redirect($URL, $type = 'header')
{
    if ($URL == 'REFERER') {
        if (!empty($_SERVER['HTTP_REFERER'])) {
            $URL = $_SERVER['HTTP_REFERER'];
        } else {
            $URL = './';
        }
    }
    if (isLocalDevelopment()) {
        throw new RedirectException($URL);
    }
    if (!headers_sent() && $type == 'header') {
        if (ob_get_length() > 0) {
            flush();
        }
        header('Location: '.$URL);
        exit;
    } elseif (headers_sent() || $type == 'script' || $type == 'script_this_win') {
        $ret = "<script type=\"text/javascript\" language=\"javascript\">\n";
        switch ($type) {
            case 'script':
                $ret .= "top.window.location='".$URL."&amp;js=1';\n";
                break;
            default:
            case 'script_this_win':
                $ret .= "this.window.location='".$URL."&amp;js=1';\n";
                break;
        }
        $ret .= "</script>\n";
        echo $ret;
        exit;
    }

    return false;
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
// danemu retezci je pridano na konec napis Kopie
function stringCopy($str)
{
    if (preg_match('/.+\\(Kopie[[:blank:]]*([0-9]+)?\\)/i', $str, $cut)) {
        $no = intval(getVal('1', $cut));
        $no = ($no == 0) ? 2 : ($no + 1);
        $end = '(Kopie '.$no.')';
        $str = preg_replace('/\\(Kopie[^\\)]*\\)/i', $end, $str);
    } else {
        $str = rtrim($str).' (Kopie)';
    }

    return $str;
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
function categoryTreeOption($topCat, $Pos, $selected, $without = null)
{
    $where = " sr.id_topsection='{$topCat}' ";
    if (!empty($without)) {
        $where .= " AND id_section<>'{$without}' ";
    }

    $SQL = sqlQuery('SELECT s.id, s.name, s.figure
         FROM '.getTableName('sections_relation').' AS sr LEFT JOIN '.getTableName('sections')." AS s ON s.id=sr.id_section
         WHERE {$where} 
         ORDER BY sr.position ASC, s.name ASC");
    $Found = sqlNumRows($SQL);
    for ($i = 0; $i < $Found; $i++) {
        $topCat = sqlResult($SQL, $i, 'id');
        $Name = sqlResult($SQL, $i, 'name');

        echo '<option value="'.$topCat.'"'.checkSelect($selected, $topCat).'>';
        for ($x = 0; $x < $Pos; $x++) {
            echo '&nbsp;&nbsp;&nbsp;';
        }
        echo htmlspecialchars($Name);
        echo "</option>\r\n";

        categoryTreeOption($topCat, $Pos + 1, $selected, $without);
    }

    sqlFreeResult($SQL);
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
function access($modules = [], $rights = [])
{
    while (true) {
        foreach ($modules as $module) {
            if (findModule($module)) {
                break 2;
            }
        }

        return false;
    }

    foreach ($rights as $right) {
        if (findRight($right)) {
            return true;
        }
    }

    return false;
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
function prepareDate($datetime)
{
    if (empty($datetime)) {
        return '';
    }
    $format = '%d-%m-%Y';

    $tm = strptime($datetime, $format);
    $stmp = mktime(0, 0, 0, $tm['tm_mon'] + 1, $tm['tm_mday'], $tm['tm_year'] + 1900);
    $time = date('Y-m-d', $stmp);

    return $time;
}

function prepareDateTime($datetime)
{
    if (empty($datetime)) {
        return '';
    }
    $format = '%d-%m-%Y %H:%M:%S';

    $tm = strptime($datetime, $format);
    $stmp = mktime($tm['tm_hour'], $tm['tm_min'], $tm['tm_sec'], $tm['tm_mon'] + 1, $tm['tm_mday'], $tm['tm_year'] + 1900);
    $time = date('Y-m-d H:i:s', $stmp);

    return $time;
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
function prepareDateForDialog($datetime)
{
    if (empty($datetime)) {
        return '';
    }
    $format = '%Y-%m-%d';

    $tm = strptime($datetime, $format);
    $stmp = mktime(0, 0, 0, $tm['tm_mon'] + 1, $tm['tm_mday'], $tm['tm_year'] + 1900);
    $time = date('d-m-Y', $stmp);

    return $time;
}

function prepareDateTimeForDialog($datetime)
{
    if (empty($datetime)) {
        return '';
    }
    $format = '%Y-%m-%d %H:%M:%S';

    $tm = strptime($datetime, $format);
    $stmp = mktime($tm['tm_hour'], $tm['tm_min'], $tm['tm_sec'], $tm['tm_mon'] + 1, $tm['tm_mday'], $tm['tm_year'] + 1900);
    $time = date('d-m-Y H:i:s', $stmp);

    return $time;
}

function switchLanguage($lang, $restore = false)
{
    global $txt_str, $temp_lang, $temp_txt_str, $cfg;
    if (!$restore) {
        $temp_txt_str = $txt_str;
        $temp_lang = $cfg['Lang']['language'];
        $cfg['Lang']['language'] = $lang;
    } else {
        $txt_str = $temp_txt_str;
        $cfg['Lang']['language'] = $temp_lang;
    }
}
