<?php


    # Posts categories



    # login
    include_once 'data_connect.php';
    include_once 'log.php';



    # user rights - user info
    # no admin rights or user info is needed

    

    # save a category
    if (isset($_POST['newcat'])) {
    
        $catchk = get_categories();
        if ($catchk !== false) {
        
            $fname = str_replace(' ','',$_POST['foldername']);
            $cname = str_replace(' ','',$_POST['newcat']);


            if ($fname != '' && $cname != '') {


                $rem_chars = ['&','/',' ','$','+',',',':',';','=','?','@','<','>','#','%','{','}','|','^','~','[',']','`','\\','\'','"'];
                $newcat = str_replace($rem_chars,'-',strtolower($_POST['newcat']));
                $folder = str_replace($rem_chars,'-',strtolower($_POST['foldername']));

                
                $root = '../category/'.$folder;


                #check for categories.xml existance
                if (!is_file('filesinfo/categories.xml'))
                    file_put_contents('filesinfo/categories.xml','<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL.'<categories><folders></folders></categories>');



                # create a folder 
                if (!is_dir($root))
                    mkdir($root,0777,true);



                # write category index file
                file_put_contents($root.'/index.php','<?php $catg=\''.$newcat.'\'; include \'../../monofiles/precat.php\' ?>');    



                # check for existing name or folder
                if (array_search($newcat,$catchk) === $folder) {

                    $_SESSION['MON_cat_exists'] = true;
                    header('Location:category.php');
                    exit();

                }


                # save category in xml file
                $addcat = simplexml_object('categories.xml','e',null);
                if (!is_array($addcat)) { 
                    
                    # note: cannot start a tag name with a number
                    if (is_numeric(substr($folder,0,1)) || substr($folder,0,1) === '_')
                        $folder = '_'.$folder;
                    
                        
                    $fcat = $addcat->folders->addChild($folder);
                    $fcat->addChild('name');
                    $addcat->folders->$folder->name = $newcat;

                    simplexml_object_save('categories.xml',$addcat,null);


                    $_SESSION['MON_newcat'] = true;
                    header('Location:category.php');
                    exit();
                }
            }

            else {

                $_SESSION['MON_cat_notset'] = true;
                header('Location:category.php');
                exit();
            }
        }
        
        else {
            $_SESSION['MON_cat_falsexml'] = true;
            header('Location:category.php');
            exit();
        
        }
    }




    # delete a category
    if (isset($_GET['deln'])) {

        
        $foldername = $_GET['deln'];
        $delfolder = substr($_GET['deln'],0,1) === '_' ? '../category/'.substr($_GET['deln'],1) : '../category/'.$_GET['deln'];

        
        # remove category from posts         
        $resfiles = glob('autosaves/*.xml');
        foreach($resfiles as $f) {

            $sxml = simplexml_object($f,'e','post');
            if ($sxml->postinfo->post->category == $foldername) {

                $sxml->postinfo->post->category = '-';
                simplexml_object_save($f,$sxml,'post');

            }

        }

        # collect all excluding the deleted category
        $remcat = simplexml_object('categories.xml','e',null);
        
        if (!is_array($remcat)) {
            
            foreach($remcat->folders->children() as $key=>$val)
                if ($key != $foldername)
                    $catarr[$key] = (string)$val->name;

            # re write the categories
            $remcat->folders = '';
            if (isset($catarr))
                foreach($catarr as $key=>$val) {
                    $fcat = $remcat->folders->addChild($key);
                    $fcat->addChild('name',$val);
                }

            # save the categories
            simplexml_object_save('categories.xml',$remcat,null);
        }
        
        
        
        else {
            $_SESSION['MON_cat_falsexml'] = true;
            header('Location:category.php');
            exit();
        }

        
        
        if (file_exists($delfolder)) {
            unlink($delfolder.'/index.php');
            rmdir($delfolder);
        }

        
        $_SESSION['MON_delcat'] = true;
        header('Location:category.php');
        exit();


    
    }



    # extensions
    include 'command.php'


        
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Categories</title>
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php include 'csstheme.php' ?>
<script type="text/javascript"> function conf(form){ return confirm('Delete category?'); }</script>
</head>
<body>
<?php


        # panel
        include 'mypanel.php';
        action_confirm()



    ?>
    <div class="main">
        <h1>Categories</h1>
        <div class="center-container">
            <form action="category.php" method="POST" class="form-category">
                
                <label for="category-name" class="lab-5">Create category</label>

                <!-- qmark description -->
                <a class="qmark" href="javascript:;">?<span class="details">- Categories apply to posts only.<br>
                    - Deleting a category does not delete any posts.<br>
                    - Folder name is the location of the category directory.</span></a>
            
                <input name="newcat" id="category-name" type="text" class="inp-category" value="" placeholder="Category name">
                <input name="foldername" id="category-folder" type="text" class="inp-category" value="" placeholder="Folder name" style="margin-top:2px">
                <br>
                <input type="submit" class="stylish-button category-btn" value="Submit category">
            </form>
            <div class="clear"></div>
            <div class="ctg">
            <?php
            
            # see get_categories function
            $folders = get_categories();


            if ($folders !== false) {
                
                $c=0;
                foreach($folders as $key=>$val) {

                    echo '<span class="cat">'.$val.'<a href="category.php?deln='.$key.'" title="Delete category" class="cat-del" onclick="return conf(this);">X</a></span>';
                    $c++;
                }

                if ($c == 0)
                    echo '<i id="no-results">:: No categories</i>';
            }
            
            else
                echo '<i id="no-results">:: Error was found in categories file</i>';
            ?>
            </div>
        </div>
    </div>
    <?php



    # plugins
    include 'execute.php'



    ?>
</body>
</html>