<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$postsFile = __DIR__ . '/posts.json';
$posts     = file_exists($postsFile) ? json_decode(file_get_contents($postsFile), true) : [];

$postId = isset($_GET['id']) ? $_GET['id'] : '';
$foundIndex = -1;

/* locate record by its unique id */
foreach ($posts as $idx => $p) {
    if (isset($p['id']) && $p['id'] === $postId) {
        $foundIndex = $idx;
        break;
    }
}

if ($foundIndex === -1) {
    echo 'Post not found.';
    exit;
}

/* optional: remove image file */
if (!empty($posts[$foundIndex]['imageurl'])) {
    $img = __DIR__ . '/../' . $posts[$foundIndex]['imageurl'];
    if (file_exists($img)) unlink($img);
}

/* remove post & save file */
array_splice($posts, $foundIndex, 1);
file_put_contents($postsFile, json_encode($posts, JSON_PRETTY_PRINT));

header('Location: dashboard.php');
exit;
?>
