<?php

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/comentarios.php';
if (!isset($_SESSION["rol"]) || isset($_SESSION["rol"]) && $_SESSION["rol"] < 1) {
    header('Location:permissions.php');
} else {
    $id_comment = $_GET['id'];
    deleteComentario($id_comment);
    header("Location:" . $_SERVER['HTTP_REFERER']);
}
}
$data = file_get_contents("php://input");
$decoded = json_decode($data);
if ($decoded != null) {
    if ($decoded->function == 'saveNoticia') {
        saveNoticia($decoded->noticia);
    } elseif ($decoded->function == 'updateNoticia') {
        updateNoticia($decoded->noticia);
    } elseif ($decoded->function == 'deleteNoticia') {
        deleteNoticia($decoded->noticia_id);
    } elseif ($decoded->function == 'saveComentario') {
        saveComentario($decoded->comentario);
    } elseif ($decoded->function == 'updateComentario') {
        updateComentario($decoded->comentario);
    } elseif ($decoded->function == 'deleteComentario') {
        deleteComentario($decoded->comentario_id);
    }
} else {
    $function = $_GET["function"];
    if ($function == 'getNoticias') {
        getNoticias();
    }
}
function deleteComentario($comentario_id)
{
    $db = new MysqliDb();
    $db->where("noticia_comentario_id", $comentario_id);
    $db->where("parent_id", $comentario_id);
    $results = $db->delete('noticias_comentarios');
    echo json_encode(1);
}
}
$data = file_get_contents("php://input");
$decoded = json_decode($data);
if ($decoded != null) {
    if ($decoded->function == 'saveNoticia') {
        saveNoticia($decoded->noticia);
    } elseif ($decoded->function == 'updateNoticia') {
        updateNoticia($decoded->noticia);
    } elseif ($decoded->function == 'deleteNoticia') {
        deleteNoticia($decoded->id);
    } elseif ($decoded->function == 'saveComentario') {
        saveComentario($decoded->comentario);
    } elseif ($decoded->function == 'updateComentario') {
        updateComentario($decoded->comentario);
    } elseif ($decoded->function == 'deleteComentario') {
        deleteComentario($decoded->id);
    }
} else {
    $function = $_GET["function"];
    if ($function == 'getNoticias') {
        getNoticias();
    } elseif ($function == 'getComentarios') {
        getComentarios();
    }
}
function getComentarios()
{
    $db = new MysqliDb();
    $results = $db->rawQuery('SELECT noticia_comentario_id,
    noticia_id,
    titulo,