<?php
require_once 'connect.php';

try {
    $conn = getDatabaseConnection();
    $input = json_decode(file_get_contents('php://input'), true);
    $id = $input['id'] ?? null;

    if (!$id) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'message' => 'Blog ID is required',
        ]);
        exit();
    }

    $conn->beginTransaction();
    //delete emails
    $stmt = $conn->prepare("DELETE nr FROM notification_recipients nr
    JOIN notifications n ON nr.notification_id = n.id
    WHERE n.blog_id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

 // delete notifications
 $stmt = $conn->prepare('DELETE FROM notifications WHERE blog_id = :id');
 $stmt->bindParam(':id', $id, PDO::PARAM_INT);
 $stmt->execute();
 
    // Delete tags and comments
    $tables = ['blog_tags', 'comments'];
    foreach ($tables as $table) {
        $stmt = $conn->prepare("DELETE FROM $table WHERE blog_id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
    }
   

   

    // Delete blog
    $stmt = $conn->prepare('DELETE FROM blogs WHERE id = :id');
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
        $conn->commit();
        echo json_encode([
            'success' => true,
            'message' => 'Blog deleted successfully',
        ]);
    } else {
        $conn->rollBack();
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Blog not found',
        ]);
    }
} catch (PDOException $e) {
    if (isset($conn) && $conn->inTransaction()) {
        $conn->rollBack();
    }
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage(),
    ]);
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage(),
    ]);
}
?>
