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

// Step 1: Include DB connection and helpers
include 'connection.php';
include '/home/screensh/private/encryption_helper.php'; // AES-256-CBC if needed
include '/home/screensh/private/privet_key.php';
include 'decrypt_and_validate.php';                     // AES-128-ECB for Android input

$response = [];

try {
    // Step 2: Read POST data
    $uidEnc    = $_POST['User_Id'] ?? '';
    $apiKeyEnc = $_POST['API_Key'] ?? '';

    // Step 3: Decrypt incoming values (AES-128-ECB)
    $userId = decryptData($uidEnc);
    $apiKey = decryptData($apiKeyEnc);

    // Step 4: Validate API key
    $validation = validateApiKey($apiKey);
    if (!$validation['status']) {
        throw new Exception($validation['message']);
    }

    if (empty($userId)) {
        throw new Exception("User ID required");
    }

    // Step 5: Delete user record
    $stmt = $conn->prepare("DELETE FROM User_Database WHERE id = ?");
    $stmt->bind_param("s", $userId);

    if ($stmt->execute()) {
        if ($stmt->affected_rows > 0) {
            $response = ["status" => "success", "message" => "Account deleted successfully."];
        } else {
            throw new Exception("User not found or already deleted.");
        }
    } else {
        throw new Exception("Delete failed: " . $stmt->error);
    }

    $stmt->close();

} catch (Exception $e) {
    $response = ["status" => "error", "message" => $e->getMessage()];
} finally {
    $conn->close();
}

// Step 6: Return JSON response
echo json_encode($response);
?>
