<?php

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

header('Content-Type: application/json; charset=utf-8');

// POST ডেটা গ্রহণ
$id  = $_POST['id'] ?? '';
$key = $_POST['key'] ?? '';

$response = [];

// কী ভ্যালিডেশন
$security_key = decrypData($key);

if ($security_key === false) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid encryption data'
    ]);
    exit;
}

if ($security_key !== SECURITY_KEY_PLAIN) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Unauthorized access'
    ]);
    exit;
}

$con = dbConnect();

// Transaction শুরু
mysqli_begin_transaction($con);

try {
    // conversations ডিলিট
    $stmt = $con->prepare("DELETE FROM conversations WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();

    // messages ডিলিট
    $stmt2 = $con->prepare("DELETE FROM messages WHERE conversation_id = ?");
    $stmt2->bind_param("i", $id);
    $stmt2->execute();

    // সব ঠিক থাকলে commit
    mysqli_commit($con);

    echo json_encode([
        'status' => 'success',
        'message' => 'Conversation and messages deleted successfully'
    ]);

} catch (Exception $e) {

    // কোনো সমস্যা হলে rollback
    mysqli_rollback($con);

    echo json_encode([
        'status' => 'error',
        'message' => 'Delete failed'
    ]);
}

?>
