<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Use correct config path
$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (file_exists($config_path)) {
    include($config_path);
} else {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = filter_var($_POST['user_id'], FILTER_VALIDATE_INT);
    
    if (!$user_id) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid user ID']);
        exit();
    }
    
    // Prevent admin from deleting themselves
    if ($user_id == $_SESSION['user_id']) {
        echo json_encode(['status' => '0', 'msg' => 'You cannot delete your own account']);
        exit();
    }
    
    try {
        // Check if user exists
        $stmt = $pdo->prepare("SELECT username, is_admin FROM users WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            echo json_encode(['status' => '0', 'msg' => 'User not found']);
            exit();
        }
        
        // Prevent deletion of admin accounts (optional security measure)
        if ($user['is_admin'] == 1 && $user_id != $_SESSION['user_id']) {
            // You can comment this out if you want to allow deleting other admins
            // echo json_encode(['status' => '0', 'msg' => 'Cannot delete admin accounts']);
            // exit();
        }
        
        // Begin transaction
        $pdo->beginTransaction();

        // Delete from optional tables that may or may not exist.
        // Tables with ON DELETE CASCADE (smm_orders, referrals, etc.)
        // are handled automatically by the database FK constraints.
        $optional_tables = [
            "DELETE FROM transactions  WHERE user_id = :user_id",
            "DELETE FROM active_number WHERE user_id = :user_id",
            "DELETE FROM smm_orders    WHERE user_id = :user_id",
            "DELETE FROM sm_purchases  WHERE user_id = :user_id",
            "DELETE FROM referrals     WHERE referrer_id = :user_id",
            "DELETE FROM referrals     WHERE referred_user_id = :user_id",
            "DELETE FROM api_keys      WHERE user_id = :user_id",
            "DELETE FROM user_numbers  WHERE user_id = :user_id",
        ];

        foreach ($optional_tables as $sql) {
            try {
                $s = $pdo->prepare($sql);
                $s->bindParam(':user_id', $user_id, PDO::PARAM_INT);
                $s->execute();
            } catch (PDOException $e) {
                // Table or column doesn't exist — safe to skip
            }
        }

        // Nullify referred_by references if the column exists
        try {
            $s = $pdo->prepare("UPDATE users SET referred_by = NULL WHERE referred_by = :user_id");
            $s->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $s->execute();
        } catch (PDOException $e) {
            // Column doesn't exist — skip
        }

        // Finally delete the user
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->execute();
        
        // Commit transaction
        $pdo->commit();
        
        echo json_encode([
            'status' => '1', 
            'msg' => 'User ' . $user['username'] . ' and all associated data have been permanently deleted'
        ]);
        
    } catch (PDOException $e) {
        // Rollback transaction on error
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
}
?>