<?php


    ## Create or edit a post



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


    
    ## user rights - user info
    # no admin rights or user info is needed but you can't edit somebody else's post if you're an author



    # Load post information or load a new empty form
    function loadpost() {
        
        if (isset($_GET['savedname'])) {
            
            $savedname = $_GET['savedname'];
            $xmlfile = simplexml_object($savedname,'l','post');
            
            # get categories
            $gc = get_categories();
            if ($gc !== false)
                foreach($gc as $k=>$v)
                    $gts[$k]=$v[1];            
            

            if ($xmlfile == ['falsexml'])
                return 'File has errors';
            
            elseif ($xmlfile == ['missingfile'])
                return 'File is missing';
            
            else {

                # Check if access to the post file is allowed
                if ($_SESSION['userID'] == $xmlfile->postinfo->post->createdby || get_account($_SESSION['userID'])['rights'] == 'administrator') {
                    
                    # Either normal or 'nu' file
                    $filebase = basename($savedname,".xml");
                    include_once 'en_code.php';
                    $catid = !empty($xmlfile->postinfo->post->catid) ? (string)$xmlfile->postinfo->post->catid : '';
                    $category = isset($gts[(string)$xmlfile->postinfo->post->catid]) ? $gts[(string)$xmlfile->postinfo->post->catid] : '';
                    $tags  = !empty($xmlfile->postinfo->post->tags) ? (string)$xmlfile->postinfo->post->tags : '';
                    $html_content = is_file('autosaves/content/'.$filebase.'.htm') ? file_get_contents('autosaves/content/'.$filebase.'.htm') : '';
                    $btnvalue = ($xmlfile->postinfo->post->type == 'Draft') ? 'Publish' : 'Update';
                    $values = ['title' => load_xml($xmlfile->postinfo->post->title),
                               'filename' => $xmlfile->postinfo->post->filename,
                               'metadescription' => $xmlfile->postinfo->post->description,
                               'filebase' => $filebase,
                               'catid' => $catid,
                               'category'=>$category,
                               'tags' => $tags,
                               'html_content' => $html_content,
                               'btnvalue' => $btnvalue,
                               'dates' => 'dates',
                               'ptime' => (int)$xmlfile->postinfo->post->ptime
                              ];
                    
                    return $values;
                }
                
                else 
                    return 'You cannot edit this post';
            }
        }
    
        else {
        
            $fbase = substr($_SESSION['userID'],0,5).bin2hex(random_bytes(6));
            $values = ['title' => '',
                       'filename' => '',
                       'metadescription' => '',
                       'catid' => '',
                       'category'=>'',
                       'tags' => '',
                       'html_content' => '',
                       'btnvalue' => 'Publish',
                       'date' => date('d F Y'),
                       'filebase' => $fbase,
                       'ptime' => time()# not really ptime
                      ];
            
            return $values;
        }
    
    }


    $pval = loadpost();
    

    if (!is_array($pval)) {
        $_SESSION['ERROR::post_not_exist'] = $pval;
        header('Location:opensaved.php');
        exit();
    }


    $texteditor = get_account($_SESSION['userID'])['texteditor']

?>
<!doctype html>
<html>
<head>
<title>Post</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="cmstyle.css">
<?php
    $cssid = '#posts';
    include 'csstheme.php';
    print '<style>'.$curval.'</style>' ?>
</head>
<body>
    <style>
    #posts + .dpsub:after{content:"Post"}
    .main{left:0;position:relative;width:100%;margin-top:140px;margin-right:0;max-width:88%}
    </style>
<?php



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



?>
    <div class="main">
        <form action="post.php" method="post" id="mainform"></form>
        <div id="page" class="nocontent">
            <div id="action-block">
                <div id="result-block">
                    <div id="resultt"></div>
                </div>
                <div class="postmore" tabindex="0">
                    <span class="dot"></span>
                    <span class="dot"></span>
                    <span class="dot"></span>
                    <div class="pmoptions">
                        <button class="close-but" onclick="closeEditor();location.href='opensaved.php'" type="button">Close</button>
                    </div>
                </div>            
        
                <!-- Save , Post, Update-->
                <input name="savebutton" type="button" id="sd" class="stylish-button" value="Save" onclick="saveTime();sendTopost()">
                <input type="text" id="uuid" name="uniqueid" value="<?php print $pval['filebase'] ?>" form="mainform" hidden>
                <input name="postbutton" type="submit" class="stylish-button" id="pd" onclick="closeEditor()" onsubmit="document.getElementById('page').className = 'nocontent';return event.key != 'Enter';"  value="<?php print $pval['btnvalue'] ?>" form="mainform">
            </div>
            
            <div class="newpageleft">
                <input name="title" type="text" class="grow" id="headline" form="mainform" value="<?php print $pval['title'] ?>" placeholder="Title" onkeydown="return event.key != 'Enter';">
                <div id="editor-container">
                    
                    
                    <?php  
                        
                        if ($texteditor == 'on') {
                        
                            include 'text-editor-controls.php';        
                            print '<div id="editor" contenteditable></div>'.PHP_EOL.'<div id="output-container" class="hide">';                    
                    }
                        else
                            print '<div id="output-container">'
                        
                        
                         ?>
                        
                        
                        <textarea name="content" id="output" autocomplete="off" form="mainform"><?php

                           if (isset($pval['html_content']))
                               print htmlspecialchars($pval['html_content'])

                          ?>
</textarea>
                    </div>
                </div>
            </div>
        
        
            <!-- Meta & info -->
            <div class="newpageright">
                <div class="clear"></div>
                <div class="clear"></div>
                <label for="filename" class="postinfo">Filename</label>
                <input type="text" name="filename" id="filename" value="<?php print $pval['filename'] ?>" form="mainform" onkeydown="return event.key != 'Enter';">
                <label for="metades" class="postinfo">Meta description</label>
                <textarea type="text" name="description" id="metades" form="mainform"><?php print $pval['metadescription'] ?></textarea>
                <div class="clear"></div>
                <div class="newoptions"></div>
                <div class="clear"></div>
                <label for="catalogue" class="postinfo">Tags</label>
                <div id="finaltags">
                <?php 
                
                    $all_tags = get_tags();
                    
                    
                    
                    
                    asort($all_tags);
                    $pvaltg = explode(',',$pval['tags']);

                    $c=1;
                    foreach($all_tags as $tag) {
                        
                        if ($tag != '' && in_array($tag,$pvaltg)) {
                            $tagn = str_replace(' ','-',$tag);
                            print '<input onkeydown="return event.key != \'Enter\'" type="checkbox" name="montag-'.$tagn.'" value="'.$tag.'" class="montagcheck" id="montag-'.$tagn.'" onchange="if(document.getElementById(\'lbmontag-'.$tagn.'\') !== null)document.getElementById(\'lbmontag-'.$tagn.'\').remove();warning()" onfocusout="if(document.getElementById(\'lbmontag-'.$tagn.'\') === null)this.remove()" form="mainform" checked><label id="lbmontag-'.$tagn.'" for="montag-'.$tagn.'">'.$tag.'</label>';
                            $c++;
                        }
                    }
                ?>
                </div>
                <input type="text" id="catalogue" value="" list="taggs" maxlength="50">
                <button id="instag" onclick="ridf()">&rsaquo;</button>
                
                
                <script>
                
                function rem(tag) {        
                    document.getElementById('lb'+tag).remove();
                    warning();
                }
                function ridf() {
                    
                    const ftags = document.getElementById('finaltags');
                    const rid = document.getElementById('catalogue');
                    
                    const ridv = rid.value;
                    
                    if (ridv != '' && ridv != ' ') {
                        
                        const sp = rid.value.replace(/\s{2,}/g,' ');
                        const com = sp.replace(/[\\,".'#%^/]/g,'');
                        const newridv = com.trim();
                        
                        const idname = newridv.replace(/\s/g,'-');
                        //idname = idname.replace(/\\/g,'');
                        
                        
                        if (document.getElementById('montag-' + idname) == null && newridv != '') {
                            const node = document.createElement('input');
                            node.setAttribute('type','checkbox');
                            node.setAttribute('class','montagcheck');
                            node.setAttribute('checked','true');
                            node.setAttribute('onkeydown','return event.key != \'Enter\'');
                            node.setAttribute('onchange','if(document.getElementById(\'lbmontag-'+idname+'\') !== null){document.getElementById(\'lbmontag-'+idname+'\').remove();warning();}');
                            node.setAttribute('onfocusout','if(document.getElementById(\'lbmontag-'+idname+'\') === null)this.remove()');
                            node.setAttribute('name','montag-'+idname);
                            node.setAttribute('value',newridv);
                            node.setAttribute('form','mainform');
                            node.setAttribute('id','montag-'+idname);
                            const nodel = document.createElement('label');
                            nodel.setAttribute('for','montag-'+idname);
                            nodel.setAttribute('id','lbmontag-'+idname);
                            const nodtxt = document.createTextNode(newridv);
                            nodel.appendChild(nodtxt);
                            ftags.appendChild(node);
                            ftags.appendChild(nodel);
                            rid.value = '';
                            warning();
                        }    
                    }
                }


                const rid = document.getElementById('catalogue');
                
                rid.addEventListener('keypress', function(event) { 
                    
                    const ss = rid.selectionStart;
                    if (event.keyCode === 32)
                        if (rid.value.substr(ss-1,1) == ' ' || rid.value.substr(ss,1) == ' ' || rid.value == '')
                            event.preventDefault();
                        
                    if (event.key === 'Enter') {
                        document.getElementById('instag').click();
                
                    }
                });
                
                
                </script>
                <datalist id="taggs">
                <?php
                    
                    $c=1;
                    foreach($all_tags as $tag) {
                        
                        print '<option>'.$tag.'</option>';
                        $c++;
                    }
                
                
                ?>
                </datalist>
                <div class="postinfo">Category</div>
                <div class="categories">
                    <select name="category" class="selcat" onchange="warning();" form="mainform">
                        <?php 
                        
                        
                        $gc = get_categories();
                        
                        if ($gc !== false) {
                        
                            unset($gc['uncategorized']);
                            $mrg = merged_categories();
                        
                            # find out if it has a category and if it is a merged category
                            if (isset($mrg[$pval['catid']])) {
                        
                                #real category id
                                $rlid = $mrg[$pval['catid']];
                            
                                $attr = $rlid;
                            
                                # real category name
                                $pval['category'] = $gc[$rlid][1];
                            
                            }
                        
                            else
                                $attr = $pval['catid'];    
                        }
                        
                        
                        if (!isset($gc[$pval['catid']]) && !isset($mrg[$pval['catid']]))
                            $pval['category'] = 'Uncategorized';
                        
                        
                        if ($pval['category'] != '')
                            echo '<option value="'.$attr.'">'.$pval['category'].'</option>';
                                 
                        
                        if ($pval['category'] != 'Uncategorized')
                            echo '<option value="">Uncategorized</option>';
                        
                        if ($gc !== false) {
                            
                            $gcs=[];
                            foreach($gc as $id=>$v)
                                $gcs[$id] = $v[1];
                                
                            asort($gcs,SORT_NATURAL);
                            
                            foreach($gcs as $id=>$val)
                                if ($val != $pval['category'] )
                                    echo '<option value="'.$id.'">'.$val.'</option>';
                        }
                        ?>
                    </select>
                </div>
                <div class="clear-m"></div>
            </div>
        </div>
        <script>
            function warning() {
                var d = document.getElementById('page'); 
                if (d.className == 'nocontent') {
                    //document.getElementById('sd').setAttribute('value','Save*');
                    d.className = 'nocontent warn';
                    }
                }
            
            function closeEditor() {
                document.getElementById('sd').setAttribute('disabled','true'); }    

            function inputEnabled() {
                var inps = document.getElementsByTagName('input');
                    for (i=0; i<inps.length; i++)
                        inps[i].removeAttribute('disabled'); }

            function saveTime() {
            document.getElementById('sd').setAttribute('disabled','true');
            document.getElementById('pd').setAttribute('disabled','true'); }

            
            function sendTopost() {
                var mes = document.getElementById('resultt');
                var pag = document.getElementById('page');
                var myForm = document.getElementById('mainform');
                var sendpost = new XMLHttpRequest();
                
                var myData = new FormData(myForm);
                myData.append('savebutton','true');
                

                mes.innerHTML = '';
                pag.setAttribute("style","opacity:.5");
                
                sendpost.open('POST','post.php',true);
                sendpost.onreadystatechange = function() {

                    if (this.readyState == 4) {
                        pag.setAttribute("style","opacity:1");
                        pag.setAttribute("class","nocontent");
                        //document.getElementById('sd').setAttribute('value','Save');
                        inputEnabled();

                        if (this.status == 200) {
                            var savetxt = sendpost.responseText;
                            mes.innerHTML = '<span class="posted">' + savetxt + '</span>';
                        }

                        else
                            mes.innerHTML = '<span class="posted" style="color:red">**Error:could not save</span>';
                    }
                }
                sendpost.send(myData);
            }

            
        </script>
        <script>
            var ar = ['filename','headline','output','metades','catalogue'];
            function wwarn(idval) {
                document.getElementById(idval).onkeyup = function() { warning(); }
                document.getElementById(idval).onpaste = function() { warning(); }
                document.getElementById(idval).onchange = function() { warning(); }
            }
            ar.forEach(wwarn);
        </script>
        <script>
            window.onbeforeunload = function() {
                if (document.querySelector('.warn') !== null) {
                    inputEnabled();
                    return false;
                }
            }
            
        </script>
        <?php    
        
            if ($texteditor == 'on') :
            
        ?>
            
        <script src="javascript/text-editor.js"></script>
            
    <?php endif    ?>
    </div>
</body>
</html>