<?php
$t = "Переменные";
include_once '../core/core.php';
if (!$user->auth()){
	$core->GoToPage("/login.lm");
	die();
}

$key = isset($_GET["key"]) && !empty($_GET["key"])?$core->FilterString($_GET["key"]):NULL;
$mod = isset($_GET["mod"]) && !empty($_GET["mod"])?$core->FilterString($_GET["mod"]):NULL;
$navbar = [];
$navbar["site"] = [
	"active"    => false,
    "name"      =>  '<img src="/assets/img/sf/tag.svg" class="navbar_icon">',
    "url"       =>  "/vars.lm?act=site"
];
$navbar["personal"] = [
	"active"    => false,
    "name"      =>  '<img src="/assets/img/sf/tag-alt.svg" class="navbar_icon">',
    "url"       =>  "/vars.lm?act=personal"
];
$navbar["import"] = [
	"active"    => false,
    "name"      =>  '<img src="/assets/img/sf/cloud-down.svg" class="navbar_icon">',
    "url"       =>  "/vars.lm?act=import"
];
if ($act == "site"){
    $navbar["site"]["active"] = true;
    $t = "Настройка переменных сайта и ПУ";
    if ($mod == "del"){
        $VarIO->DelS($key);
        $VarIO->Save();
        include_once '../core/head.php';
        echo '<div class="alert alert-success">Ключ <code>'.$key.'</code> успешно удален.</div>';
    }
    if (isset($_POST["add"])){
        $ikey = isset($_POST["key"])?$core->FilterString($_POST["key"]):NULL;
        $ival = isset($_POST["val"])?$core->FilterString($_POST["val"]):NULL;
        if ($ikey == NULL || $ival == NULL){
            $core->regError("","Ключ и Значение не должны быть пусты",1,"Vars");
        } else {
            $VarIO->SetS($ikey, $ival);
            $VarIO->Save();
            include_once '../core/head.php';
            echo '<div class="alert alert-success">Ключ <code>'.$ikey.'</code> успешно обновлен.</div>';
        }
    }
    include_once '../core/head.php';
    if ($core->isBooleanError()){
        foreach ($core->showError() as $csE){
            echo '<div class="alert alert-danger">#Err'.$csE["code"].'</b> | '.$csE["utxt"].'</div>';
        }	
    }
    echo '<div class=""><div class="panel panel-default">
    <div class="panel-heading">Обновление переменной</div>
    <div class="panel-body">
    <form class="form-horizontal" method="POST" action="/vars.lm?act=site">
            <div class="form-group">
                <label for="inputData2" class="col-sm-2 control-label">Ключ</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" value="" name="key" id="inputData2" placeholder="Ключ">
                </div>
            </div>
            <div class="form-group">
                <label for="inputData1" class="col-sm-2 control-label">Значение</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" value="" name="val" id="inputData1" placeholder="Значение">
                </div>
            </div>
            
            <div class="form-group" style="margin-bottom:0">
            <div class="col-sm-offset-2 col-sm-10 text-right">
                <button type="submit" class="btn btn-primary" name="add">Обновить</button>
            </div>
        </div>
            
            </form>

    </div>
    <table class="table"><thead><tr>
        <th>Ключ</th>
        <th>Значение</th>
        <th> </th>
    </tr></thead><tbody>';
    $t_h = 1;
    foreach ($VarIO->site as $tkey => $tval){
        echo '<tr><th scope="row">'.$VarIO->GetLocalKey($tkey).'</th>
        <td>'.$tval.'</td><td>
        <a class="btn btn-danger btn-xs pim-tt" '.tooltip_html_gen("Удалить").' href="?act=site&mod=del&key='.$tkey.'"><i class="fa fa-fw fa-trash"></i></a>
        </td></tr>';
        $t_h++;
    }
    echo '</tbody></table></div></div>';
    include_once '../core/foot.php';
    die();
} elseif ($act == "personal"){
    $navbar["personal"]["active"] = true;
    $t = "Настройка персональных переменных";
    if ($mod == "del"){
        $VarIO->DelP($key);
        $VarIO->Save();
        include_once '../core/head.php';
        echo '<div class="alert alert-success">Ключ <code>'.$key.'</code> успешно удален.</div>';
    }
    if (isset($_POST["add"])){
        $ikey = isset($_POST["key"]) && !empty($_POST["key"])?$core->FilterString($_POST["key"]):NULL;
        $ival = isset($_POST["val"]) && !empty($_POST["val"])?$core->FilterString($_POST["val"]):NULL;
        if ($ikey == NULL || $ival == NULL){
            $core->regError("","Ключ и Значение не должны быть пусты",1,"Vars");
        } else {
            $VarIO->SetP($ikey, $ival);
            $VarIO->Save();
            include_once '../core/head.php';
            echo '<div class="alert alert-success">Ключ <code>'.$ikey.'</code> успешно обновлен.</div>';
        }
    }
    include_once '../core/head.php';
    if ($core->isBooleanError()){
        foreach ($core->showError() as $csE){
            echo '<div class="alert alert-danger">#Err'.$csE["code"].'</b> | '.$csE["utxt"].'</div>';
        }	
    }
    echo '<div class=""><div class="panel panel-default">
    <div class="panel-heading">Обновление переменной</div>
    <div class="panel-body">
    <form class="form-horizontal" method="POST" action="/vars.lm?act=personal">
            <div class="form-group">
                <label for="inputData2" class="col-sm-2 control-label">Ключ</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" value="" name="key" id="inputData2" placeholder="Ключ">
                </div>
            </div>
            <div class="form-group">
                <label for="inputData1" class="col-sm-2 control-label">Значение</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" value="" name="val" id="inputData1" placeholder="Значение">
                </div>
            </div>
            
            <div class="form-group" style="margin-bottom:0">
            <div class="col-sm-offset-2 col-sm-10 text-right">
                <button type="submit" class="btn btn-primary" name="add">Обновить</button>
            </div>
        </div>
            
            </form>

    </div>
    <table class="table"><thead><tr>
        <th>Ключ</th>
        <th>Значение</th>
        <th> </th>
    </tr></thead><tbody>';
    $t_h = 1;
    foreach ($VarIO->personal as $tkey => $tval){
        echo '<tr><th scope="row"><code>'.$tkey.'</code></td></th>
        <td>'.$tval.'</td><td>
        <a class="btn btn-danger btn-xs pim-tt" '.tooltip_html_gen("Удалить").' href="?act=personal&mod=del&key='.$tkey.'"><i class="fa fa-fw fa-trash"></i></a>
        </td></tr>';
        $t_h++;
    }
    echo '</tbody></table></div></div>';
    include_once '../core/foot.php';
    die();
} elseif ($act == "import"){
    $navbar["import"]["active"] = true;
    $t = "Импорт переменных";
    if (isset($_POST["load"]) && isset($_FILES["file"]) && isset($_FILES["file"]["name"]) && isset($_FILES["file"]["type"]) && isset($_FILES["file"]["tmp_name"]) && isset($_FILES["file"]["error"]) && isset($_FILES["file"]["size"])){
		
        $cat = isset($_POST["cat"]) && !empty($_POST["cat"])?1:0;
        $raw = isset($_POST["raw"]) && !empty($_POST["raw"])?1:0;

        $f_e = intval($_FILES["file"]["error"]);
		$f_s = intval($_FILES["file"]["size"]);
		$f_n = $core->FilterString($_FILES["file"]["name"]);
		$f_t = $core->FilterString($_FILES["file"]["type"]);
		$f_v = $core->FilterString($_FILES["file"]["tmp_name"]);
		$f_p = pathinfo($f_n);
		if (isset($f_p["extension"])){
			$f_f = $f_p["extension"];
		} else {
			$f_f = "nonefile";
		}
		$f_l = $f_p["filename"];
		
		if ($f_e != 0 || $f_s <= 0){
			$core->regError("","Вы не выбрали файл или он является пустым.",2,"cp_filemgr");
		} elseif ($f_f != "json"){
			$core->regError("","Формат файла не поддерживается.",3,"cp_filemgr");
		} else {
            $file = @file_get_contents($f_v);
			if ($file === false){
                $core->regError("", "Произошла ошибка при загрузке файла.",4,"cp_filemgr");
            } else {
                $json = json_decode($file, true);
                if ($json == NULL || !is_array($json) || count($json) <= 0){
                    $core->regError("", "Не удалось прочитать файл",5,"cp_filemgr");
                } else {
                    $__IMPORT_X = 0;
                    foreach ($json as $jkey => $jval){
                        if (!is_string($jval) && !is_numeric($jval)) continue;
                        if ($cat == 0) {
                            if ($raw == 0){
                                if (!isset($VarIO->site[$jkey])){
                                    $VarIO->SetS($jkey, $jval);
                                }
                            } else {
                                $VarIO->SetS($jkey, $jval);
                            }
                            
                        }
                        if ($cat == 1) {
                            if ($raw == 0){
                                if (!isset($VarIO->personal[$jkey])){
                                    $VarIO->SetP($jkey, $jval);
                                }
                            } else {
                                $VarIO->SetP($jkey, $jval);
                            }
                            
                        }
                        $__IMPORT_X++;
                    }
                    $VarIO->Save();
                    include_once '../core/head.php';
                    echo '<div class="alert alert-success">Файл был успешно импортирован.<br>Обновлено <code>'.$__IMPORT_X.' шт.</code></div>';

                }
            }
		}
	}
    include_once '../core/head.php';
    if ($core->isBooleanError()){
        foreach ($core->showError() as $csE){
            echo '<div class="alert alert-danger">#Err'.$csE["code"].'</b> | '.$csE["utxt"].'</div>';
        }	
    }
    echo '<div class=""><div class="panel panel-default">
    <div class="panel-heading">Извлечение данных из файла</div>
    <div class="panel-body">
    <form class="form-horizontal" method="POST" action="/vars.lm?act=import"  enctype="multipart/form-data">
            <div class="form-group">
                <label for="inputData2" class="col-sm-2 control-label">Файл <code>json</code></label>
                <div class="col-sm-10">
                    <input type="file" name="file" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <label for="inputData1" class="col-sm-2 control-label">Категория</label>
                <div class="col-sm-10">
                    <select name="cat" class="form-control"><option value="0">Сайт и ПУ</option><option value="1">Персональное</option></select>
                </div>
            </div>

            <div class="form-group">
                <label for="inputData3" class="col-sm-2 control-label">Перезаписать</label>
                <div class="col-sm-10">
                    <select name="raw" class="form-control"><option value="0">Нет, дописать только новые</option><option value="1">Да, перезаписать переменные</option></select>
                </div>
            </div>
            
            <div class="form-group" style="margin-bottom:0">
            <div class="col-sm-offset-2 col-sm-10 text-right">
                <button type="submit" class="btn btn-primary" name="load">Импорт</button>
            </div>
        </div>
            
            </form>

    </div></div></div>';
    include_once '../core/foot.php';
    die();
}

include_once '../core/head.php';
if ($core->isBooleanError()){
    foreach ($core->showError() as $csE){
		echo '<div class="alert alert-danger">#Err'.$csE["code"].'</b> | '.$csE["utxt"].'</div>';
	}	
}
echo '<div class="row cm-fix-height">';
echo l("/vars.lm?act=site","Сайт и ПУ","tag",false,false,"Настройки переменных сайта и панели управления");
echo l("/vars.lm?act=personal","Персональные","tag-alt",false,false,"Настройка собственных переменных");
echo l("/vars.lm?act=import","Импорт","cloud-down",false,false,"Импортировать переменные");
echo '</div>';
include_once '../core/foot.php';
?>