> ## Documentation Index
> Fetch the complete documentation index at: https://docs-restapi.wplimit.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Delete Customer

> Delete a customer from the system

## Description

This endpoint allows you to delete a customer from the LatePoint system. The customer will be permanently removed from the database along with their associated data.

<Warning>
  **Important**: Deleting a customer is irreversible. Make sure you want to permanently remove this customer and all their associated data before proceeding.
</Warning>

<Info>
  **Booking Protection**: Customers with existing bookings cannot be deleted to maintain data integrity. You must first cancel or delete all associated bookings before deleting the customer.
</Info>

## Authentication

<ParamField header="X-API-Key" type="string" required>
  Your LatePoint API Key with delete permissions
</ParamField>

## Path Parameters

<ParamField path="id" type="integer" required>
  Unique ID of the customer to delete
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Indicates if the deletion was successful
</ResponseField>

<ResponseField name="message" type="string">
  Success or error message
</ResponseField>

<ResponseField name="data" type="object">
  Additional information about the deletion

  <Expandable title="Deletion Data">
    <ResponseField name="deleted_customer_id" type="integer">
      ID of the deleted customer
    </ResponseField>

    <ResponseField name="deleted_at" type="string">
      Timestamp when the customer was deleted
    </ResponseField>
  </Expandable>
</ResponseField>

## Examples

### Delete Customer

```bash theme={null}
curl -X DELETE "https://your-site.com/wp-json/latepoint-api/v1/customers/123" \
  -H "X-API-Key: your_api_key_here"
```

## Response Examples

### Successful Deletion

```json theme={null}
{
  "success": true,
  "message": "Customer deleted successfully",
  "data": {
    "deleted_customer_id": 123,
    "deleted_at": "2024-01-15 14:30:25"
  }
}
```

### Customer Not Found

```json theme={null}
{
  "code": "customer_not_found",
  "message": "Customer not found",
  "data": {
    "status": 404
  }
}
```

### Customer Has Bookings

```json theme={null}
{
  "code": "customer_has_bookings",
  "message": "Cannot delete customer with existing bookings",
  "data": {
    "status": 400,
    "booking_count": 3
  }
}
```

### Deletion Failed

```json theme={null}
{
  "code": "customer_delete_failed",
  "message": "Error deleting customer: Database error",
  "data": {
    "status": 500
  }
}
```

## Error Codes

| Code                      | Status | Description                                          |
| ------------------------- | ------ | ---------------------------------------------------- |
| `customer_not_found`      | 404    | Customer with specified ID doesn't exist             |
| `customer_has_bookings`   | 400    | Customer has existing bookings and cannot be deleted |
| `customer_delete_failed`  | 500    | Database error or deletion failed                    |
| `latepoint_not_available` | 503    | LatePoint plugin not loaded                          |
| `server_error`            | 500    | Internal server error                                |

## JavaScript Example

```javascript theme={null}
// Delete customer function
async function deleteCustomer(customerId) {
  try {
    const response = await fetch(`https://your-site.com/wp-json/latepoint-api/v1/customers/${customerId}`, {
      method: 'DELETE',
      headers: {
        'X-API-Key': 'your_api_key_here'
      }
    });
    
    const result = await response.json();
    
    if (result.success) {
      console.log('Customer deleted successfully:', result.data);
      return result.data;
    } else {
      throw new Error(result.message);
    }
  } catch (error) {
    console.error('Error deleting customer:', error);
    throw error;
  }
}

// Usage with confirmation
async function deleteCustomerWithConfirmation(customerId) {
  const confirmed = confirm('Are you sure you want to delete this customer? This action cannot be undone.');
  
  if (confirmed) {
    try {
      const result = await deleteCustomer(customerId);
      alert('Customer deleted successfully!');
      return result;
    } catch (error) {
      if (error.message.includes('existing bookings')) {
        alert('Cannot delete customer: They have existing bookings. Please cancel or delete all bookings first.');
      } else {
        alert('Error deleting customer: ' + error.message);
      }
      throw error;
    }
  }
}

// Delete customer with ID 123
deleteCustomerWithConfirmation(123);
```

## PHP Example

```php theme={null}
<?php
// Delete customer using WordPress HTTP API
function delete_customer($customer_id) {
    $url = 'https://your-site.com/wp-json/latepoint-api/v1/customers/' . $customer_id;
    
    $response = wp_remote_request($url, array(
        'method' => 'DELETE',
        'headers' => array(
            'X-API-Key' => 'your_api_key_here'
        )
    ));
    
    if (is_wp_error($response)) {
        throw new Exception('Request failed: ' . $response->get_error_message());
    }
    
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    
    if (!$data['success']) {
        throw new Exception('Deletion failed: ' . $data['message']);
    }
    
    return $data['data'];
}

// Safe deletion with booking check
function safe_delete_customer($customer_id) {
    try {
        // First, check if customer has bookings
        $bookings_url = 'https://your-site.com/wp-json/latepoint-api/v1/bookings?customer_id=' . $customer_id;
        $bookings_response = wp_remote_get($bookings_url, array(
            'headers' => array(
                'X-API-Key' => 'your_api_key_here'
            )
        ));
        
        if (!is_wp_error($bookings_response)) {
            $bookings_data = json_decode(wp_remote_retrieve_body($bookings_response), true);
            
            if (!empty($bookings_data['data']) && count($bookings_data['data']) > 0) {
                throw new Exception('Customer has ' . count($bookings_data['data']) . ' existing bookings. Please handle them first.');
            }
        }
        
        // Proceed with deletion
        $result = delete_customer($customer_id);
        
        echo 'Customer deleted successfully. ID: ' . $result['deleted_customer_id'];
        return $result;
        
    } catch (Exception $e) {
        echo 'Error: ' . $e->getMessage();
        return false;
    }
}

// Usage
safe_delete_customer(123);
?>
```

## Bulk Deletion Example

```javascript theme={null}
// Bulk delete customers (use with caution)
async function bulkDeleteCustomers(customerIds) {
  const results = [];
  const errors = [];
  
  for (const customerId of customerIds) {
    try {
      const result = await deleteCustomer(customerId);
      results.push({ id: customerId, success: true, data: result });
    } catch (error) {
      errors.push({ id: customerId, success: false, error: error.message });
    }
    
    // Add delay to avoid overwhelming the server
    await new Promise(resolve => setTimeout(resolve, 100));
  }
  
  return { results, errors };
}

// Usage
const customerIdsToDelete = [123, 124, 125];
const bulkResult = await bulkDeleteCustomers(customerIdsToDelete);

console.log('Successful deletions:', bulkResult.results.length);
console.log('Failed deletions:', bulkResult.errors.length);

if (bulkResult.errors.length > 0) {
  console.log('Errors:', bulkResult.errors);
}
```

## Best Practices

### Before Deleting

1. **Check for Bookings**: Always verify that the customer has no existing bookings before deletion
2. **Backup Data**: Consider exporting customer data before deletion for record-keeping
3. **User Confirmation**: Always require explicit user confirmation for deletion operations
4. **Audit Trail**: Log deletion operations for audit purposes

### Alternative to Deletion

Instead of deleting customers, consider:

* **Deactivating**: Set customer status to `inactive` instead of deleting
* **Archiving**: Move customer data to an archive table
* **Soft Delete**: Mark as deleted without removing from database

```javascript theme={null}
// Alternative: Deactivate instead of delete
async function deactivateCustomer(customerId) {
  return await fetch(`https://your-site.com/wp-json/latepoint-api/v1/customers/${customerId}`, {
    method: 'PUT',
    headers: {
      'X-API-Key': 'your_api_key_here',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      status: 'inactive'
    })
  });
}
```

## Important Notes

**Irreversible Action**: Customer deletion is permanent and cannot be undone. All customer data will be lost.

**Booking Dependencies**: Customers with existing bookings cannot be deleted. You must first handle all associated bookings.

**WordPress User**: If the customer has an associated WordPress user account, you may need to handle that separately.

**Related Data**: Deletion may affect other related data such as customer notes, custom fields, and historical records.

**Permissions**: Ensure your API key has the necessary permissions to delete customers.

**Rate Limiting**: When performing bulk deletions, implement appropriate delays to avoid overwhelming the server.
