<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

require_once __DIR__ . '/../includes/db.php'; 
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

// Require valid auth token
requireAuth();

$device_id = $_POST['device_id'] ?? '';

if (empty($device_id)) {
    echo json_encode(["success" => false, "message" => "Missing device_id"]);
    exit;
}

try {
    $pdo->beginTransaction();

    // Delete related messages
    $stmt1 = $pdo->prepare("DELETE FROM messegedetails WHERE device_id = ?");
    $stmt1->execute([$device_id]);

    // Delete related user(s)
    $stmt2 = $pdo->prepare("DELETE FROM users WHERE device_id = ?");
    $stmt2->execute([$device_id]);

    // Delete device
    $stmt3 = $pdo->prepare("DELETE FROM devices WHERE device_id = ?");
    $stmt3->execute([$device_id]);

    $pdo->commit();

    if ($stmt3->rowCount() > 0) {
        echo json_encode(["success" => true, "message" => "Device and related data deleted successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Device not found"]);
    }

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(["success" => false, "message" => $e->getMessage()]);
}
