<?php
header("Content-Type: application/json");
session_start();
require_once '../config/db.php'; 

$response = ["success" => false, "message" => "Critical error: Process failed."];

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);

    // 1. Fetch the image path before deleting the record
    $query = "SELECT thumbnail_image, story_id FROM stories WHERE id = $id";
    $res = $conn->query($query);

    if ($res && $res->num_rows > 0) {
        $data = $res->fetch_assoc();
        $story_label = $data['story_id'];
        $file_to_delete = "../" . $data['thumbnail_image'];

        // 2. Delete the physical vertical thumbnail
        if (!empty($data['thumbnail_image']) && file_exists($file_to_delete)) {
            @unlink($file_to_delete);
        }

        // 3. Delete the database record
        $delete = $conn->query("DELETE FROM stories WHERE id = $id");

        if ($delete) {
            $response = [
                "success" => true, 
                "message" => "Story $story_label and its assets have been removed."
            ];
        } else {
            $response = ["success" => false, "message" => "Database Error: " . $conn->error];
        }
    } else {
        $response = ["success" => false, "message" => "Error: Story not found."];
    }
} else {
    $response = ["success" => false, "message" => "Invalid request: No ID provided."];
}

echo json_encode($response);
exit();