# EventBookings Plugin API Reference

Complete API documentation for the EventBookings WordPress plugin, including AJAX endpoints, PHP classes, and JavaScript integration.

## Table of Contents

1. [AJAX Endpoints](#ajax-endpoints)
2. [PHP Classes and Methods](#php-classes-and-methods)
3. [Shortcodes](#shortcodes)
4. [Database Schema](#database-schema)
5. [JavaScript API](#javascript-api)
6. [Configuration](#configuration)

## AJAX Endpoints

### eventbookings_wp_get_events_public

Retrieves public events with pagination support.

**Endpoint**: `wp-admin/admin-ajax.php`
**Method**: GET
**Action**: `eventbookings_wp_get_events_public`
**Access**: Public (logged in and non-logged in users)

#### Parameters
- `ajax_nonce` (string, required): WordPress nonce for security
- `position` (int, optional): Page position for pagination (default: 1)

#### Response Format
```json
{
  "success": true,
  "data": {
    "result": {
      "events": [
        {
          "uuid": "event-uuid-here",
          "name": "Event Name",
          "description": "Event description",
          "start_date": "2024-01-01T10:00:00Z",
          "end_date": "2024-01-01T18:00:00Z",
          // ... additional event data
        }
      ],
      "pagination": {
        "current_page": 1,
        "total_pages": 5,
        "total_items": 25
      },
      "customized_settings": {
        "display_event_description": true,
        "display_countdown": true,
        // ... other display settings
      }
    }
  }
}
```

#### Error Response
```json
{
  "success": false,
  "data": {
    "message": "Invalid nonce" | "No events found or API error."
  }
}
```

#### Usage Example
```javascript
jQuery.ajax({
    url: ajaxurl,
    type: 'GET',
    data: {
        action: 'eventbookings_wp_get_events_public',
        ajax_nonce: nonce_value,
        position: 1
    },
    success: function(response) {
        if (response.success) {
            // Handle events data
            console.log(response.data.result.events);
        }
    }
});
```

---

### eventbookings_wp_get_events_featured

Retrieves featured events for carousel display.

**Endpoint**: `wp-admin/admin-ajax.php`
**Method**: GET
**Action**: `eventbookings_wp_get_events_featured`
**Access**: Public

#### Parameters
- `position` (int, optional): Page position for pagination (default: 1)

#### Response Format
Similar to `eventbookings_wp_get_events_public` but returns up to 16 featured events.

#### Configuration
- Maximum events per request: 16
- Cache duration: 30,000 seconds (8.33 hours)
- Source table: `wp_eb_feature_events`

---

### eventbookings_wp_get_event_details

Retrieves detailed information for a specific event.

**Endpoint**: `wp-admin/admin-ajax.php`
**Method**: POST
**Action**: `eventbookings_wp_get_event_details`
**Access**: Public

#### Parameters
- `eventUuid` (string, required): UUID of the event to retrieve

#### Response Format
```json
{
  "success": true,
  "data": {
    "event": {
      "uuid": "event-uuid-here",
      "name": "Event Name",
      "description": "Detailed event description",
      "tickets": [
        {
          "id": "ticket-id",
          "name": "Ticket Type",
          "price": 25.00,
          "currency": "USD"
        }
      ],
      // ... complete event data
    },
    "customized_settings": {
      "display_event_description": true,
      // ... display settings
    }
  }
}
```

---

### eventbookings_wp_ticket_purchase

Handles ticket purchase and booking submissions.

**Endpoint**: `wp-admin/admin-ajax.php`
**Method**: POST
**Action**: `eventbookings_wp_ticket_purchase`
**Access**: Public

#### Parameters
- `ajax_nonce` (string, required): WordPress nonce for security
- `order` (string, required): JSON encoded order data

#### Order Data Structure
```json
{
  "event_uuid": "event-uuid-here",
  "tickets": [
    {
      "ticket_id": "ticket-id",
      "quantity": 2,
      "price": 25.00
    }
  ],
  "attendees": [
    {
      "first_name": "John",
      "last_name": "Doe",
      "email": "john@example.com",
      "phone": "+1234567890"
    }
  ],
  "payment_method": "stripe",
  "billing_address": {
    "street": "123 Main St",
    "city": "City",
    "state": "State",
    "zip": "12345",
    "country": "US"
  }
}
```

#### Response Format
```json
{
  "success": true,
  "payment_url": "https://payment-gateway-url",
  "order_id": "order-uuid",
  "status": "pending_payment"
}
```

## PHP Classes and Methods

### EVENTBOOKINGS_Plugin

Main plugin initialization class.

#### Properties
- `$settings` (Eventbookings_Settings): Settings manager instance
- `$shortcode` (Eventbookings_Plugin_Shortcode): Shortcode handler instance

#### Methods

##### `__construct()`
Initializes the plugin by loading dependencies and setting up hooks.

```php
public function __construct()
```

##### `eventbookings_includes()`
Loads required plugin files.

```php
private function eventbookings_includes()
```

---

### Eventbookings_Settings

Handles admin settings and menu management.

#### Methods

##### `eventbookings_add_admin_menu()`
Registers admin menu pages.

```php
public static function eventbookings_add_admin_menu()
```

##### `eventbookings_register_settings()`
Registers plugin settings with WordPress.

```php
public static function eventbookings_register_settings()
```

##### `eventbookings_settings_page()`
Renders the settings page interface.

```php
public static function eventbookings_settings_page()
```

##### `eventbookings_has_saved_credentials()`
Checks if API credentials are saved in database.

```php
private static function eventbookings_has_saved_credentials(): object|false
```

**Returns**: Database row object with credentials or false if not found.

---

### Eventbookings_Api_Service

Handles all API communication with EventBookings service.

#### Methods

##### `eventbookings_api_request_handler()`
Main API request handler with automatic token refresh.

```php
public static function eventbookings_api_request_handler(
    string $method,
    string $endpoint,
    array $body = [],
    bool $retry = true
): array
```

**Parameters**:
- `$method` (string): HTTP method (GET, POST, PUT, DELETE)
- `$endpoint` (string): Full API endpoint URL
- `$body` (array): Request body data for POST/PUT requests
- `$retry` (bool): Whether to retry on authentication failure

**Returns**: API response array or error array

**Usage Example**:
```php
$response = Eventbookings_Api_Service::eventbookings_api_request_handler(
    'GET',
    'https://api-rto.eventbookings.com/v3/events?rows=10'
);

if (isset($response['error'])) {
    // Handle error
    error_log('API Error: ' . $response['error']);
} else {
    // Process successful response
    $events = $response['events'];
}
```

##### `eventbookings_get_access_token()`
Retrieves stored access token from database.

```php
public static function eventbookings_get_access_token(): string
```

**Returns**: Access token string or empty string if not found.

##### `eventbookings_fetch_new_token()`
Refreshes expired access token using refresh token.

```php
public static function eventbookings_fetch_new_token(): string|false
```

**Returns**: New access token or false on failure.

---

### Eventbookings_Plugin_Shortcode

Manages WordPress shortcodes for event display.

#### Methods

##### `eventbookings_register_shortcode()`
Registers all available shortcodes with WordPress.

```php
public static function eventbookings_register_shortcode()
```

##### `eventbookings_render_shortcode()`
Renders the main events listing shortcode.

```php
public static function eventbookings_render_shortcode(array $atts): string
```

**Parameters**:
- `$atts` (array): Shortcode attributes (currently unused)

**Returns**: HTML output for event listing

##### `eventbookings_render_features_shortcode()`
Renders the featured events carousel shortcode.

```php
public static function eventbookings_render_features_shortcode(array $atts): string
```

##### `eventbookings_render_details_shortcode()`
Renders the event details page shortcode.

```php
public static function eventbookings_render_details_shortcode(array $atts): string
```

## Shortcodes

### [eventbookings_events_shortcode]

Displays a paginated list of public events.

**Usage**: `[eventbookings_events_shortcode]`

**Output**: Grid layout of event cards with pagination

**Features**:
- Responsive grid layout
- AJAX pagination
- Event filtering
- Click-through to event details

### [eventbookings_feature_events_shortcode]

Displays featured events in a carousel format.

**Usage**: `[eventbookings_feature_events_shortcode]`

**Output**: Owl Carousel slider with featured events

**Features**:
- Touch/swipe navigation
- Automatic slideshow
- Responsive breakpoints
- Navigation dots and arrows

### [eventbookings_feature_event_details]

Displays detailed view of a specific event.

**Usage**: `[eventbookings_feature_event_details]`

**Output**: Complete event information page

**Features**:
- Event description and media
- Ticket selection and booking
- Location map integration
- Countdown timers
- Terms and conditions

## Database Schema

### wp_eb_plugin_users

Stores OAuth credentials and user data.

```sql
CREATE TABLE wp_eb_plugin_users (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    access_token TEXT NULL,
    refresh_token TEXT NULL,
    client_id VARCHAR(255) NULL UNIQUE,
    client_secret VARCHAR(255) NULL,
    user_data TEXT NULL,
    org_uuid TEXT NULL,
    PRIMARY KEY (id)
);
```

### wp_events

Caches event data from the API.

```sql
CREATE TABLE wp_events (
    uuid VARCHAR(100) NOT NULL,
    organisation_uuid VARCHAR(100) NOT NULL,
    event_data TEXT NOT NULL,
    is_published TINYINT(1) NOT NULL DEFAULT 0,
    is_ended TINYINT(1) NOT NULL DEFAULT 0,
    event_name VARCHAR(200) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (uuid),
    INDEX idx_organisation_uuid (organisation_uuid),
    INDEX idx_published (is_published),
    INDEX idx_ended (is_ended),
    INDEX idx_created_at (created_at)
);
```

### wp_eb_feature_events

Stores featured events configuration.

```sql
CREATE TABLE wp_eb_feature_events (
    uuid VARCHAR(100) NOT NULL,
    organisation_uuid VARCHAR(100) NOT NULL,
    event_data TEXT NOT NULL,
    is_published TINYINT(1) NOT NULL DEFAULT 0,
    is_ended TINYINT(1) NOT NULL DEFAULT 0,
    event_name VARCHAR(200) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (uuid),
    INDEX idx_organisation_uuid (organisation_uuid),
    INDEX idx_published (is_published),
    INDEX idx_ended (is_ended),
    INDEX idx_created_at (created_at)
);
```

### wp_customized_events

Stores display customization settings per organization.

```sql
CREATE TABLE wp_customized_events (
    id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    organisation_uuid VARCHAR(100) NOT NULL,
    display_event_description TINYINT(1) NOT NULL DEFAULT 1,
    display_countdown TINYINT(1) NOT NULL DEFAULT 1,
    display_booking_start_countdown TINYINT(1) NOT NULL DEFAULT 1,
    display_discount_end_countdown TINYINT(1) NOT NULL DEFAULT 1,
    display_event_start_countdown TINYINT(1) NOT NULL DEFAULT 1,
    display_event_end_countdown TINYINT(1) NOT NULL DEFAULT 1,
    display_event_location_map TINYINT(1) NOT NULL DEFAULT 1,
    display_ticket_price_on_event_page TINYINT(1) NOT NULL DEFAULT 1,
    display_terms_and_condition TINYINT(1) NOT NULL DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE INDEX idx_organisation_uuid (organisation_uuid)
);
```

## JavaScript API

### Event Handlers

The plugin provides several JavaScript objects for frontend interaction:

#### eventbookings_events_obj_{render_id}

Available in pages with `[eventbookings_events_shortcode]`.

**Properties**:
- `ajaxurl`: WordPress AJAX endpoint URL
- `ajax_nonce`: Security nonce for AJAX requests
- `details_slug`: Slug for event details page
- `render_id`: Unique identifier for shortcode instance
- `EVENTBOOKINGS_REMOTE_PAYMENT_URL`: Payment gateway URL
- `seatplan`: Seat plan service URL

#### Usage Example
```javascript
// Access the localized object (replace {render_id} with actual ID)
const config = window.eventbookings_events_obj_abc123;

// Make AJAX request
jQuery.post(config.ajaxurl, {
    action: 'eventbookings_wp_get_events_public',
    ajax_nonce: config.ajax_nonce,
    position: 1
}, function(response) {
    // Handle response
});
```

## Configuration

### Environment Configuration

The plugin supports multiple environments configured via `eventbookings_get_config()`:

#### Development
- **Base URL**: `https://api.diywebsite.net.au/v2`
- **App URL**: `https://api.diywebsite.net.au`
- **Identity URL**: `https://identity.diywebsite.net.au`

#### Staging
- **Base URL**: `https://api.doyour.events/v3`
- **App URL**: `https://api.doyour.events`
- **Identity URL**: `https://identity.doyour.events`

#### Production (Default)
- **Base URL**: `https://api-rto.eventbookings.com/v3`
- **App URL**: `https://api-rto.eventbookings.com`
- **Identity URL**: `https://identity.eventbookings.com`

### Setting Environment
```php
// Set environment in wp-config.php or through admin
update_option('eventbookings_environment', 'staging'); // or 'development', 'production'
```

### Constants

The plugin defines several constants:

- `EVENTBOOKINGS_PLUGIN_PATH`: Plugin directory path
- `EVENTBOOKINGS_PLUGIN_URL`: Plugin directory URL
- `EVENTBOOKINGS_BASE_URL`: API base URL
- `EVENTBOOKINGS_APP_URL`: Application URL
- `EVENTBOOKINGS_IDENTITY_URL`: Identity service URL
- `EVENTBOOKINGS_REMOTE_PAYMENT_URL`: Remote payment URL
- `EVENTBOOKINGS_SEATPLAN_URL`: Seat plan service URL

## Error Handling

### Common Error Responses

#### Authentication Errors
```json
{
  "success": false,
  "data": {
    "message": "Invalid or missing access token"
  }
}
```

#### Validation Errors
```json
{
  "success": false,
  "data": {
    "message": "Order data is required"
  }
}
```

#### API Errors
```json
{
  "success": false,
  "data": {
    "message": "No events found or API error."
  }
}
```

### Debug Logging

Enable WordPress debug logging to capture detailed error information:

```php
// In wp-config.php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);

// Check logs in /wp-content/debug.log
```

The plugin uses `eventbookings_log()` function for structured logging:

```php
eventbookings_log('error', 'API request failed', [
    'endpoint' => $endpoint,
    'method' => $method,
    'response_code' => $http_code
]);
```