<?php
// delete_psot.php
// Autors: Kārlis Mālnieks
// pievieno datubazes savienojumu
require_once 'db_connection.php';

// nolasam ievaddatus no JSON pieprasijuma
$input_data = json_decode(file_get_contents("php://input"), true);
$postId = $input_data['id'];
$userId = $_SESSION['user_id'];
$userLevel = $_SESSION['user_level'];

// parbauda lietotaja limeni un sagatavo atbilstoso SQL pieprasijumu
if ($userLevel == 3) {
    // administrators var dzest jebkuru ierakstu
    $sql = "DELETE FROM posts WHERE id = :id";
} else {
    // parastais lietotajs var dzest tikai savus ierakstus
    $sql = "DELETE FROM posts WHERE id = :id AND user_id = :user_id";
}

$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $postId);

if ($userLevel != 3) {
    $stmt->bindParam(':user_id', $userId);
}

// izpilda pieprasijumu un atgriez rezultatu
if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Neizdevas izdzest ierakstu.']);
}
?>
