<?php
// delete-user.php
session_start();
require_once 'auth/db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    echo json_encode(['success'=>false,'message'=>'Unauthorized']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$userId = intval($data['user_id'] ?? 0);
if (!$userId) { echo json_encode(['success'=>false,'message'=>'Missing user id']); exit; }

try {
    $conn->begin_transaction();

    // delete related rows (example table names - change to yours)
    $stmt = $conn->prepare("DELETE FROM transactions WHERE user_id = ?");
    $stmt->bind_param("i",$userId); $stmt->execute(); $stmt->close();

    $stmt = $conn->prepare("DELETE FROM referrals WHERE user_id = ?");
    $stmt->bind_param("i",$userId); $stmt->execute(); $stmt->close();

    $stmt = $conn->prepare("DELETE FROM mining_records WHERE user_id = ?");
    $stmt->bind_param("i",$userId); $stmt->execute(); $stmt->close();

    // ... add any other user-specific tables you have ...

    // delete user
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i",$userId); $stmt->execute(); $stmt->close();

    $conn->commit();
    echo json_encode(['success'=>true]);
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}
