<?php
/**
 * /subs/parts/blog_backend.php
 * @version 1.0
 * @desc Blog page 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(isset($_GET['posts_offset']) && isset($_GET['posts_limit'])){
    $sql=$db->prepare("SELECT b.id, b.title, u.fullname AS owner, b.date, b.content, 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.published=1 GROUP BY b.id ORDER BY b.date DESC LIMIT :lim OFFSET :off");
    $sql->execute(array(":lim"=>$_GET['posts_limit'], ":off"=>$_GET['posts_offset']));
    
    $blog=array();

    while($row=$sql->fetch(PDO::FETCH_ASSOC)){
        array_push($blog, json_encode($row));
    }
    
    echo json_encode($blog);
    die();
}

if(isset($_GET['posts_tag']) && isset($_GET['posts_tag_offset']) && isset($_GET['posts_tag_limit'])){
    $sql=$db->prepare("SELECT b.id, b.title, u.fullname AS owner, b.date, b.content, 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.published=1 and bt.tag=:tag GROUP BY b.id ORDER BY b.date DESC LIMIT :lim OFFSET :off");
    $sql->execute(array(":tag"=>$_GET['posts_tag'], ":lim"=>$_GET['posts_tag_limit'], ":off"=>$_GET['posts_tag_offset']));
    
    $blog=array();
    
    while($row=$sql->fetch(PDO::FETCH_ASSOC)){
        array_push($blog, json_encode($row));
    }
    
    echo json_encode($blog);
    die();
}

if(isset($_GET['post'])){
    $sql=$db->prepare("SELECT b.id, b.title, u.fullname AS owner, b.date, b.content, 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.published=1 and b.id=:id GROUP BY b.id ORDER BY b.date DESC");
    $sql->execute(array(":id"=>$_GET['post']));
    $res=$sql->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode($res);
    die();
}
