<?php
/**
 * /subs/parts/userarea_backend.php
 * @version 1.5
 * @desc Users area backend
 * @author Fándly Gergő Zoltán (gergo@systemtest.tk, systemtest.tk)
 * @copy 2018 Fándly Gergő Zoltán
 * License:
    Systemtest.tk website's.
    Copyright (C) 2018  Fándly Gergő Zoltán

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
 **/

if(!$lm->validateLogin()){
    if(isset($_POST['username']) && isset($_POST['password'])){
        $lm->login($_POST['username'], $_POST['password'], isset($_POST['remember']));
    }
    if(isset($_GET['auto_login'])){
        $lm->login("", "");
    }
    if(isset($_GET['forget_user'])){
        $lm->forgetUser();
    }
}
else{
    if(isset($_GET['logout'])){
        $lm->logout();
        die();
    }
    
    if($sub!=""){
        if($sub!="fileshare" && $sub!="blog" && $sub!="orders" && $sub!="messages" && $sub!="news" && $sub!="admin" && $sub!="profile"){
            functions::setError(500);
            header("Location: /userarea");
        }
        if($sub=="blog" && $_SESSION['accesslevel']<1){
            functions::setError(500);
            header("Location: /userarea");
        }
        if(($sub=="orders" || $sub=="messages") && $_SESSION['accesslevel']<2){
            functions::setError(500);
            header("Location: /userarea");
        }
        if(($sub=="news" || $sub=="admin") && $_SESSION['accesslevel']<3){
            functions::setError(500);
            header("Location: /userarea");
        }
    }
    
    /*
     * FILESHARE
     */
    //file upload
    if(isset($_POST['upload_name']) && isset($_FILES['upload_file'])){
        $token=hash("md5", $_POST['upload_name']."<<<>>>".functions::randomString(16, functions::RAND_SPEC));
        $ext=strtolower(pathinfo($_FILES['upload_file']['name'], PATHINFO_EXTENSION));
        $size=$_FILES['upload_file']['size'];
        
        //get user quota
        if($_SESSION['quota']!=-1){
            //calc previous uploads quota:
            $sql=$db->prepare("SELECT SUM(size) AS size FROM files WHERE owner=:uid");
            $sql->execute(array(":uid"=>$_SESSION['id']));
            $prev=$sql->fetch(PDO::FETCH_ASSOC)['size'];
            
            if($prev+$size > $_SESSION['quota']*1000000){
                functions::setError(4);
                echo "quota";
                die();
            }
        }
        
        //add file to database
        $sql=$db->prepare("INSERT INTO files (token, owner, name, extension, size) VALUES (:token, :owner, :name, :ext, :size)");
        $sql->execute(array(":token"=>$token, ":owner"=>$_SESSION['id'], ":name"=>$_POST['upload_name'], ":ext"=>$ext, ":size"=>$size));
        $fid=$db->lastInsertId();
        
        $target="../uploads/files/".$fid;
        
        if(!move_uploaded_file($_FILES['upload_file']['tmp_name'], $target)){
            //wrong.
            //roll back SQL changes
            $sql=$db->prepare("DELETE FROM files WHERE id=:fid");
            $sql->execute(array(":fid"=>$fid));
            
            functions::setError(6);
            echo "error";
            die();
        }
        else{
            echo "https://systemtest.tk/uploads/".$token;
            die();
        }
    }
    
    //file delete
    if(isset($_POST['delete_file'])){
        $sql=$db->prepare("SELECT COUNT(id) AS count FROM files WHERE id=:fid and owner=:uid");
        $sql->execute(array(":fid"=>$_POST['delete_file'], ":uid"=>$_SESSION['id']));
        $res=$sql->fetch(PDO::FETCH_ASSOC);
        
        if($res['count'] < 1){
            functions::setError(7);
            die();
        }
        else{
            if(unlink("../uploads/files/".$_POST['delete_file'])){
                $sql=$db->prepare("DELETE FROM files WHERE id=:fid");
                $sql->execute(array(":fid"=>$_POST['delete_file']));
                functions::setMessage(3);
                echo "ok";
                die();
            }
            else{
                functions::setError(6);
                echo "error";
                die();
            }
        }
    }
    
    
    /*
     * BLOG
     */
    if($_SESSION['accesslevel']>=1){
        //new entry
        if(isset($_POST['blog_new'])){
            $sql=$db->prepare("INSERT INTO blog (owner, published) VALUES (:uid, 0)");
            $sql->execute(array(":uid"=>$_SESSION['id']));
            $res=$sql->rowCount();
            
            if($res < 1){
                functions::setError(6);
                echo "error";
                die();
            }
            else{
                echo $db->lastInsertId();
                die();
            }
        }
        
        //update entry
        if(isset($_POST['blog_id']) && isset($_POST['blog_title']) && isset($_POST['blog_content']) && isset($_POST['blog_tags']) && isset($_POST['blog_published'])){
            if($_SESSION['accesslevel'] < 3){
                $sql=$db->prepare("SELECT COUNT(id) AS count FROM blog WHERE id=:bid and owner=:uid");
                $sql->execute(array(":bid"=>$_POST['blog_id'], ":uid"=>$_SESSION['id']));
            }
            else{
                $sql=$db->prepare("SELECT COUNT(id) AS count FROM blog WHERE id=:bid");
                $sql->execute(array(":bid"=>$_POST['blog_id']));
            }
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                //merge updates
                if($_SESSION['accesslevel'] < 3){
                    $sql=$db->prepare("UPDATE blog SET title=:title, date=:date, content=:content, published=:published WHERE id=:bid and owner=:uid");
                    $sql->execute(array(":title"=>$_POST['blog_title'], ":date"=>date("Y-m-d H:i:s"), ":content"=>$_POST['blog_content'], ":published"=>$_POST['blog_published'], ":bid"=>$_POST['blog_id'], ":uid"=>$_SESSION['id']));
                }
                else{
                    $sql=$db->prepare("UPDATE blog SET title=:title, date=:date, content=:content, published=:published WHERE id=:bid");
                    $sql->execute(array(":title"=>$_POST['blog_title'], ":date"=>date("Y-m-d H:i:s"), ":content"=>$_POST['blog_content'], ":published"=>$_POST['blog_published'], ":bid"=>$_POST['blog_id']));
                }
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                }
                else{
                    $sql=$db->prepare("DELETE FROM blog_tags WHERE blogentry=:bid");
                    $sql->execute(array(":bid"=>$_POST['blog_id']));
                    
                    foreach(explode(";", $_POST['blog_tags']) as $t){
                        $sql=$db->prepare("INSERT INTO blog_tags (blogentry, tag) VALUES (:bid, :tag)");
                        $sql->execute(array(":bid"=>$_POST['blog_id'], ":tag"=>$t));
                    }
                    
                    functions::setMessage(4);
                }
            }
        }
        
        //get data
        if(isset($_GET['blog_get'])){
            $sql=$db->prepare("SELECT COUNT(b.id) AS count, b.id, b.title, u.fullname AS owner, b.date, b.content, b.published, GROUP_CONCAT(bt.tag SEPARATOR ';') AS tags FROM blog AS b INNER JOIN users AS u ON (u.id=b.owner) LEFT JOIN blog_tags AS bt ON (bt.blogentry=b.id) WHERE b.id=:id GROUP BY b.id");
            $sql->execute(array(":id"=>$_GET['blog_get']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                echo json_encode($res);
                die();
            }
        }
        
        //delete entry
        if(isset($_POST['blog_delete'])){
            if($_SESSION['accesslevel'] < 3){
                $sql=$db->prepare("SELECT COUNT(id) AS count FROM blog WHERE id=:bid and owner=:uid");
                $sql->execute(array(":bid"=>$_POST['blog_delete'], ":uid"=>$_SESSION['id']));
            }
            else{
                $sql=$db->prepare("SELECT COUNT(id) AS count FROM blog WHERE id=:bid");
                $sql->execute(array(":bid"=>$_POST['blog_delete']));
            }
            
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                if($_SESSION['accesslevel'] < 3){
                    $sql=$db->prepare("DELETE FROM blog WHERE id=:bid and owner=:uid");
                    $sql->execute(array(":bid"=>$_POST['blog_delete'], ":uid"=>$_SESSION['id']));
                }
                else{
                    $sql=$db->prepare("DELETE FROM blog WHERE id=:bid");
                    $sql->execute(array(":bid"=>$_POST['blog_delete']));
                }
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(5);
                    echo "ok";
                    die();
                }
            }
        }
    }
    
    
    /*
     * NEWS
     */
    if($_SESSION['accesslevel']>=3){
        //new entry
        if(isset($_POST['news_new'])){
            $sql=$db->prepare("INSERT INTO news (owner, published) VALUES (:uid, 0)");
            $sql->execute(array(":uid"=>$_SESSION['id']));
            $res=$sql->rowCount();
            
            if($res < 1){
                functions::setError(6);
                echo "error";
                die();
            }
            else{
                echo $db->lastInsertId();
                die();
            }
        }
        
        //update entry
        if(isset($_POST['news_id']) && isset($_POST['news_subject_eng']) && isset($_POST['news_subject_hun']) && isset($_POST['news_subject_rou']) && isset($_POST['news_content_eng']) && isset($_POST['news_content_hun']) && isset($_POST['news_content_rou']) && isset($_POST['news_published'])){
            $sql=$db->prepare("SELECT COUNT(id) AS count FROM news WHERE id=:id");
            $sql->execute(array(":id"=>$_POST['news_id']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                $sql=$db->prepare("UPDATE news SET date=:date, subject_eng=:subj_eng, subject_hun=:subj_hun, subject_rou=:subj_rou, content_eng=:cont_eng, content_hun=:cont_hun, content_rou=:cont_rou, published=:pub WHERE id=:id");
                $sql->execute(array(":date"=>date("Y-m-d H:i:s"), ":subj_eng"=>$_POST['news_subject_eng'], ":subj_hun"=>$_POST['news_subject_hun'], ":subj_rou"=>$_POST['news_subject_rou'], ":cont_eng"=>$_POST['news_content_eng'], ":cont_hun"=>$_POST['news_content_hun'], ":cont_rou"=>$_POST['news_content_rou'], ":pub"=>$_POST['news_published'], ":id"=>$_POST['news_id']));
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(4);
                    echo "ok";
                    die();
                }
            }
        }
        
        //get data
        if(isset($_GET['news_get'])){
            $sql=$db->prepare("SELECT COUNT(id) AS count, id, owner, date, subject_eng, subject_hun, subject_rou, content_eng, content_hun, content_rou, published FROM news WHERE id=:id");
            $sql->execute(array(":id"=>$_GET['news_get']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                echo json_encode($res);
                die();
            }
        }
        
        //delete entry
        if(isset($_POST['news_delete'])){
            $sql=$db->prepare("SELECT COUNT(id) AS count FROM news WHERE id=:id");
            $sql->execute(array(":id"=>$_POST['news_delete']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                $sql=$db->prepare("DELETE FROM news WHERE id=:id");
                $sql->execute(array(":id"=>$_POST['news_delete']));
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(5);
                    echo "ok";
                    die();
                }
            }
        }
        
        
        /*
         * ADMIN AREA
         */
        //new password
        if(isset($_POST['new_password_user']) && isset($_POST['new_password'])){
            $sql=$db->prepare("SELECT COUNT(id) AS count FROM users WHERE id=:id");
            $sql->execute(array(":id"=>$_POST['new_password_user']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                $sql=$db->prepare("UPDATE users SET password=:passwd WHERE id=:id");
                $passwd=PasswordStorage::create_hash($_POST['new_password']);
                $sql->execute(array(":passwd"=>$passwd, ":id"=>$_POST['new_password_user']));
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(4);
                    echo "ok";
                    die();
                }
            }
        }
        
        //new accesslevel
        if(isset($_POST['new_accesslevel_user']) && isset($_POST['new_accesslevel'])){
            $sql=$db->prepare("SELECT COUNT(id) AS count FROM users WHERE id=:id");
            $sql->execute(array(":id"=>$_POST['new_accesslevel_user']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                $sql=$db->prepare("UPDATE users SET accesslevel=:al WHERE id=:id");
                $sql->execute(array(":al"=>$_POST['new_accesslevel'], ":id"=>$_POST['new_accesslevel_user']));
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(4);
                    echo "ok";
                    die();
                }
            }
        }
        
        //new quota
        if(isset($_POST['new_quota_user']) && isset($_POST['new_quota'])){
            $sql=$db->prepare("SELECT COUNT(id) AS count FROM users WHERE id=:id");
            $sql->execute(array(":id"=>$_POST['new_quota_user']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                $sql=$db->prepare("UPDATE users SET quota=:q WHERE id=:id");
                $sql->execute(array(":q"=>$_POST['new_quota'], ":id"=>$_POST['new_quota_user']));
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(4);
                    echo "ok";
                    die();
                }
            }
        }
        
        //finalize request
        if(isset($_POST['admin_finish_request'])){
            $sql=$db->prepare("SELECT COUNT(id) AS count FROM data_requests WHERE id=:id and finished=0");
            $sql->execute(array(":id"=>$_POST['admin_finish_request']));
            $res=$sql->fetch(PDO::FETCH_ASSOC);
            
            if($res['count'] < 1){
                functions::setError(7);
                echo "error";
                die();
            }
            else{
                $sql=$db->prepare("UPDATE data_requests SET finished=1 WHERE id=:id");
                $sql->execute(array(":id"=>$_POST['admin_finish_request']));
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(14);
                    echo "ok";
                    die();
                }
            }
        }
        
        //new user
        if(isset($_POST['usernew_username']) && isset($_POST['usernew_fullname']) && isset($_POST['usernew_email']) && isset($_POST['usernew_accesslevel']) && isset($_POST['usernew_quota']) && isset($_POST['usernew_password']) && isset($_POST['usernew_password_confirm'])){
            if($_POST['usernew_password']!=$_POST['usernew_password_confirm']){
                functions::setError(8);
                echo "error";
                die();
            }
            else{
                $sql=$db->prepare("SELECT COUNT(id) AS count FROM users WHERE username=:username");
                $sql->execute(array(":username"=>$_POST['usernew_username']));
                $res=$sql->fetch(PDO::FETCH_ASSOC);
                
                if($res['count'] > 0){
                    functions::setError(9);
                    echo "error";
                    die();
                }
                else{
                    $passwd=PasswordStorage::create_hash($_POST['usernew_password']);
                    $sql=$db->prepare("INSERT INTO users (username, fullname, email, accesslevel, quota, password) VALUE (:uname, :fname, :email, :al, :quota, :passwd)");
                    $sql->execute(array(":uname"=>$_POST['usernew_username'], ":fname"=>$_POST['usernew_fullname'], ":email"=>$_POST['usernew_email'], ":al"=>$_POST['usernew_accesslevel'], ":quota"=>$_POST['usernew_quota'], ":passwd"=>$passwd));
                    $res=$sql->rowCount();
                    
                    if($res < 1){
                        functions::setError(6);
                        echo "error";
                        die();
                    }
                    else{
                        functions::setMessage(6);
                        echo "ok";
                        die();
                    }
                }
            }
        }
    }
    
    
    /*
     * PROFILE
     */
    //update details
    if(isset($_POST['profile_fullname']) && isset($_POST['profile_email'])){
        $sql=$db->prepare("UPDATE users SET fullname=:fname, email=:email WHERE id=:id");
        $sql->execute(array(":fname"=>$_POST['profile_fullname'], ":email"=>$_POST['profile_email'], ":id"=>$_SESSION['id']));
        $res=$sql->rowCount();
        
        if($res < 1){
            functions::setError(6);
            echo "error";
            die();
        }
        else{
            functions::setMessage(7);
            echo "ok";
            die();
        }
    }
    
    //update password
    if(isset($_POST['profile_password']) && isset($_POST['profile_password_confirm'])){
        if($_POST['profile_password']!=$_POST['profile_password_confirm']){
            functions::setError(8);
            echo "error";
            die();
        }
        else{
            $passwd=PasswordStorage::create_hash($_POST['profile_password']);
            $sql=$db->prepare("UPDATE users SET password=:passwd WHERE id=:id");
            $sql->execute(array(":passwd"=>$passwd, ":id"=>$_SESSION['id']));
            $res=$sql->rowCount();
            
            if($res < 1){
                functions::setError(6);
                echo "error";
                die();
            }
            else{
                functions::setMessage(8);
                echo "ok";
                die();
            }
        }
    }
    
    //update shipping details
    if(isset($_POST['profile_shipping_name']) && isset($_POST['profile_shipping_address']) && isset($_POST['profile_shipping_email']) && isset($_POST['profile_shipping_phone'])){
        //get wich entry to use
        $sql=$db->prepare("SELECT COUNT(id) AS count, orderer FROM users WHERE id=:id and orderer is not null");
        $sql->execute(array(":id"=>$_SESSION['id']));
        $res=$sql->fetch(PDO::FETCH_ASSOC);
        
        if($res['count'] > 0){
            //already exists, just needs to be updated
            $sql=$db->prepare("UPDATE orderers SET name=:name, address=:address, email=:email, phone=:phone WHERE reference=:ref");
            $sql->execute(array(":name"=>$_POST['profile_shipping_name'], ":address"=>$_POST['profile_shipping_address'], ":email"=>$_POST['profile_shipping_email'], ":phone"=>$_POST['profile_shipping_phone'], ":ref"=>$res['orderer']));
            $res=$sql->rowCount();
            
            if($res < 1){
                functions::setError(6);
                echo "error";
                die();
            }
            else{
                functions::setMessage(9);
                echo "ok";
                die();
            }
        }
        else{
            $ref=hash("md5", date("Y-m-d H:i:s")."<<<>>>".functions::randomString(16, functions::RAND_SPEC));
            $sql=$db->prepare("INSERT INTO orderers (reference, name, address, email, phone) VALUES (:ref, :name, :addr, :email, :phone)");
            $sql->execute(array(":ref"=>$ref, ":name"=>$_POST['profile_shipping_name'], ":addr"=>$_POST['profile_shipping_address'], ":email"=>$_POST['profile_shipping_email'], ":phone"=>$_POST['profile_shipping_phone']));
            $res=$sql->rowCount();
            
            if($res < 1){
                functions::setError(6);
                echo "error";
                die();
            }
            else{
                //assign to user
                $sql=$db->prepare("UPDATE users SET orderer=:oref WHERE id=:id");
                $sql->execute(array(":oref"=>$ref, ":id"=>$_SESSION['id']));
                $res=$sql->rowCount();
                
                if($res < 1){
                    functions::setError(6);
                    echo "error";
                    die();
                }
                else{
                    functions::setMessage(10);
                    echo "ok";
                    die();
                }
            }
        }
    }
    
    //delete shipping details
    if(isset($_POST['profile_shipping_delete'])){
        //get wich entry to use
        $sql=$db->prepare("SELECT COUNT(id) AS count, orderer FROM users WHERE id=:id and orderer is not null");
        $sql->execute(array(":id"=>$_SESSION['id']));
        $res=$sql->fetch(PDO::FETCH_ASSOC);
        
        if($res['count'] < 1){
            functions::setError(7);
            echo "error";
            die();
        }
        else{
            $sql=$db->prepare("DELETE FROM orderers WHERE reference=:ref");
            $sql->execute(array(":ref"=>$res['orderer']));
            $res=$sql->rowCount();
            
            if($res < 1){
                functions::setError(6);
                echo "error";
                die();
            }
            else{
                functions::setMessage(11);
                echo "ok";
                die();
            }
        }
    }
    
    //delete profile
    if(isset($_POST['delete_profile'])){
        //delete files
        $sql=$db->prepare("SELECT id FROM files WHERE owner=:uid");
        $sql->execute(array(":uid"=>$_SESSION['id']));
        
        while($res=$sql->fetch(PDO::FETCH_ASSOC)){
            unlink("../uploads/files/".$res['id']);
        }
        
        //delete shipping address
        $sql=$db->prepare("SELECT orderer FROM users WHERE id=:uid");
        $sql->execute(array(":uid"=>$_SESSION['id']));
        $res=$sql->fetch(PDO::FETCH_ASSOC);
        if($res['orderer']!=null){
            $sql=$db->prepare("DELETE FROM orderers WHERE reference=:ref");
            $sql->execute(array(":ref"=>$res['orderer']));
        }
        
        //delete profile
        $sql=$db->prepare("DELETE FROM users WHERE id=:id");
        $sql->execute(array(":id"=>$_SESSION['id']));
        $res=$sql->rowCount();
        
        if($res < 1){
            functions::setError(10);
            echo "error";
            die();
        }
        else{
            functions::setMessage(12);
            echo "ok";
            die();
        }
    }
    
    //request profile data
    if(isset($_POST['request_profile_data']) && isset($_POST['request_profile_data_pgp'])){
        $sql=$db->prepare("SELECT COUNT(id) AS count FROM data_requests WHERE user=:uid and finished=0");
        $sql->execute(array(":uid"=>$_SESSION['id']));
        $res=$sql->fetch(PDO::FETCH_ASSOC);
        
        if($res['count'] > 0){
            functions::setError(11);
        }
        else{
            $sql=$db->prepare("INSERT INTO data_requests (date, user, pgp, finished) VALUES (:date, :uid, :pgp, 0)");
            $sql->execute(array(":date"=>date("Y-m-d H:i:s"), ":uid"=>$_SESSION['id'], ":pgp"=>$_POST['request_profile_data_pgp']));
            $res=$sql->rowCount();
            
            if($res < 1){
                functions::setError(6);
            }
            else{
                functions::setMessage(13);
            }
        }
    }
    
}