Home / Code Examples / Working with Services

Working with Services

Code examples for service management

Working with Services

Create Service

$db = Database::getInstance();

// Calculate next due date based on billing cycle
$nextDueDate = calculateNextDueDate($billingCycle);

$stmt = $db->prepare("
    INSERT INTO services (
        client_id, product_id, domain, status, billing_cycle,
        next_due_date, created_at
    ) VALUES (?, ?, ?, 'active', ?, ?, NOW())
");
$stmt->bind_param("iisss", 
    $clientId, $productId, $domain, $billingCycle, $nextDueDate
);
$stmt->execute();
$serviceId = $db->insert_id;

// Provision on server if module assigned
if (!empty($product['module']) && $product['module'] === 'cpanel') {
    $moduleManager = new ModuleManager();
    $serverModule = $moduleManager->getModule('cpanel');
    
    if ($serverModule) {
        $result = $serverModule->execute('create_account', [
            'domain' => $domain,
            'username' => generateUsername($domain),
            'password' => generatePassword(),
            'package' => $product['whm_package_name']
        ]);
        
        if ($result['success']) {
            // Update service with server account ID
            $stmt = $db->prepare("UPDATE services SET server_account_id = ? WHERE id = ?");
            $stmt->bind_param("si", $result['account_id'], $serviceId);
            $stmt->execute();
        }
    }
}

Suspend Service

$db->begin_transaction();
try {
    // Update service status
    $stmt = $db->prepare("UPDATE services SET status = 'suspended' WHERE id = ?");
    $stmt->bind_param("i", $serviceId);
    $stmt->execute();
    
    // Suspend on server
    if (!empty($service['server_account_id'])) {
        $moduleManager = new ModuleManager();
        $serverModule = $moduleManager->getModule('cpanel');
        
        if ($serverModule) {
            $serverModule->execute('suspend_account', [
                'account_id' => $service['server_account_id']
            ]);
        }
    }
    
    $db->commit();
} catch (Exception $e) {
    $db->rollback();
    throw $e;
}

Get Client Services

$stmt = $db->prepare("
    SELECT s.*, p.name as product_name, p.module
    FROM services s
    INNER JOIN products p ON s.product_id = p.id
    WHERE s.client_id = ?
    ORDER BY s.created_at DESC
");
$stmt->bind_param("i", $clientId);
$stmt->execute();
$services = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);