<?php

include_once __DIR__ . '/../secrets.php';
include '../db_connect.php';

$id  = $_POST['id'];
$key = $_POST['key'];

$security_key = decrypData($key);

if ($security_key === false) {
    echo 'Invalid encryption data';
    exit;
}

if ($security_key == SECURITY_KEY_PLAIN) {

    $con = dbConnect();

    /* -----------------------------------
       1️⃣ Get post images first
       ----------------------------------- */
    $imgSql = "SELECT images FROM post_table WHERE id = '$id'";
    $imgResult = mysqli_query($con, $imgSql);

    if ($imgResult && mysqli_num_rows($imgResult) > 0) {

        $row = mysqli_fetch_assoc($imgResult);
        $images = $row['images']; 
        // example: uploads/img1.jpg,uploads/img2.jpg

        if (!empty($images)) {

            $imageArray = explode(',', $images);

            foreach ($imageArray as $imgPath) {
                $imgPath = trim($imgPath);

                if (file_exists($imgPath)) {
                    unlink($imgPath);
                }
            }
        }
    }

    /* -----------------------------------
       2️⃣ Delete post & related data
       ----------------------------------- */

    $sql  = "DELETE FROM post_table WHERE id = '$id'";
    $sql1 = "DELETE FROM post_reactions WHERE post_id = '$id'";
    $sql2 = "DELETE FROM comment_table WHERE postid = '$id'";

    $result  = mysqli_query($con, $sql);
    $result1 = mysqli_query($con, $sql1);
    $result2 = mysqli_query($con, $sql2);

    if ($result && $result1 && $result2) {
        echo "Delete Successfully";
    } else {
        echo "Query Error";
    }

    mysqli_close($con);
}

?>
