<?php
include('db.php');

if (!empty($_POST)){

    //set up data
    $index = $_POST['id'];
    $edit = $_POST['ifEdit'];
    $content = $_POST['content'];

    if (strlen($content) == 0){
        if (isset($_POST['confirm'])){
            $sql = "UPDATE document SET ifEdit='$edit', state = 1 WHERE id='$index'";
        }
        else if (isset($_POST['archive'])){
            $sql = "DELETE FROM favourite WHERE documentId='$index'";
            $insert = $mysqli->query($sql);
            $sql = "UPDATE document SET ifEdit='$edit', state = 3 WHERE id='$index'";
        }
        else{
            $sql = "UPDATE document SET ifEdit='$edit' WHERE id='$index'";
        }
        $insert = $mysqli->query($sql);
    }
    else{
        $lastEdit = $_POST['lastEdit'];
        $oldContet = strstr($_POST['oldContent'], '<');

        $sql = "UPDATE document SET ifEdit='$edit' , content='$content', edited=NOW() WHERE id='$index'";
        $insert = $mysqli->query($sql);

        $sql = "INSERT INTO history (documentId, editDate, content) VALUES ('$index', '$lastEdit', '$oldContet')";
        $insert = $mysqli->query($sql);
    }
}

?>