# Championship API - Quick Reference Guide

## Base URL
All API calls go to: `championship_api.php`

## Authentication
Uses existing session authentication from `logged_in.php`

---

## Dashboard Endpoints

### Get Championship Status
**Purpose:** Get real-time status of all locations in tournament  
**Method:** GET  
**Action:** `get_championship_status`

**Parameters:**
- `tourn_ID` (required) - Tournament identifier
- `game_date` (optional) - Defaults to today

**Response:**
```json
{
  "success": true,
  "data": {
    "locations": [
      {
        "loc_ID": 123,
        "location_name": "Denver Downtown",
        "region_name": "Colorado",
        "status": {
          "total_teams": 12,
          "teams_scored": {
            "halftime": 12,
            "final": 8
          },
          "rounds_complete": {
            "1": true,
            "2": true,
            "3": false
          },
          "halftime_finalized": true,
          "final_finalized": false,
          "ready_flags": {
            "halftime": true,
            "second_half": false
          },
          "is_online": true
        }
      }
    ],
    "progress": {
      "halftime_finalized": 5,
      "final_finalized": 2,
      "all_complete": false
    }
  }
}
```

**Usage:**
```javascript
$.get('championship_api.php', {
    action: 'get_championship_status',
    tourn_ID: 1
}, function(response) {
    if (response.success) {
        console.log(response.data.locations);
    }
});
```

---

## Status Update Endpoints

### Update Location Status (Heartbeat)
**Purpose:** Keep location marked as online  
**Method:** POST  
**Action:** `update_location_status`

**Parameters:**
- `tourn_ID` (required)
- `loc_ID` (required)
- `game_date` (optional) - Defaults to today

**Call every 30-60 seconds from nav.php:**
```javascript
setInterval(function() {
    $.post('championship_api.php', {
        action: 'update_location_status',
        tourn_ID: TOURN_ID,
        loc_ID: LOC_ID
    });
}, 30000);
```

### Mark Section Ready
**Purpose:** Indicate location is ready for next phase  
**Method:** POST  
**Action:** `mark_section_ready`

**Parameters:**
- `tourn_ID` (required)
- `loc_ID` (required)
- `section` (required) - One of: `halftime`, `second_half`, `final`, `results`
- `game_date` (optional)

**Usage:**
```javascript
$.post('championship_api.php', {
    action: 'mark_section_ready',
    tourn_ID: 1,
    loc_ID: 123,
    section: 'halftime'
}, function(response) {
    alert(response.message);
});
```

### Finalize Scores
**Purpose:** Lock halftime or final scores  
**Method:** POST  
**Action:** `finalize_scores`

**Parameters:**
- `tourn_ID` (required)
- `loc_ID` (required)
- `score_type` (required) - Either `H` (halftime) or `F` (final)
- `game_date` (optional)

**Usage:**
```javascript
$.post('championship_api.php', {
    action: 'finalize_scores',
    tourn_ID: 1,
    loc_ID: 123,
    score_type: 'H'
}, function(response) {
    if (response.success) {
        alert('Halftime scores finalized!');
    }
});
```

---

## Notification Endpoints

### Get Notifications
**Purpose:** Retrieve new notifications since last check  
**Method:** GET  
**Action:** `get_notifications`

**Parameters:**
- `tourn_ID` (required)
- `loc_ID` (required) - Or 0 for all
- `since` (optional) - Unix timestamp of last check

**Response:**
```json
{
  "success": true,
  "data": {
    "notifications": [
      {
        "id": 1,
        "message": "Denver has finalized halftime scores",
        "notification_type": "success",
        "created_at": "2026-01-09 14:30:00",
        "timestamp": 1736448600
      }
    ],
    "count": 1
  }
}
```

### Send Broadcast
**Purpose:** Send message to all locations  
**Method:** POST  
**Action:** `send_broadcast`

**Parameters:**
- `tourn_ID` (required)
- `loc_ID` (required) - Sender's location
- `message` (required) - Message text
- `type` (optional) - One of: `info`, `success`, `warning`, `alert`

**Usage:**
```javascript
$.post('championship_api.php', {
    action: 'send_broadcast',
    tourn_ID: 1,
    loc_ID: 0,
    message: 'Starting second half in 5 minutes!',
    type: 'warning'
});
```

---

## Chat Endpoints

### Get Chat Messages
**Purpose:** Retrieve new chat messages  
**Method:** GET  
**Action:** `get_chat_messages`

**Parameters:**
- `tourn_ID` (required)
- `room` (required) - Room name (e.g., 'general', 'hq')
- `since` (optional) - Unix timestamp

**Response:**
```json
{
  "success": true,
  "data": {
    "messages": [
      {
        "id": 1,
        "username": "Host Denver",
        "location_name": "Denver Downtown",
        "message": "We're ready for halftime!",
        "created_at": "2026-01-09 14:35:00",
        "timestamp": 1736448900
      }
    ]
  }
}
```

### Send Chat Message
**Purpose:** Send a chat message  
**Method:** POST  
**Action:** `send_chat_message`

**Parameters:**
- `tourn_ID` (required)
- `room` (required) - Room name
- `loc_ID` (required)
- `username` (required)
- `message` (required)

**Usage:**
```javascript
$.post('championship_api.php', {
    action: 'send_chat_message',
    tourn_ID: 1,
    room: 'general',
    loc_ID: 123,
    username: 'Host Denver',
    message: 'Hello everyone!'
});
```

---

## Presence Endpoints

### Update Presence
**Purpose:** Mark user as online  
**Method:** POST  
**Action:** `update_presence`

**Parameters:**
- `tourn_ID` (required)
- `loc_ID` (required)
- `username` (required)

**Call every 30 seconds:**
```javascript
setInterval(function() {
    $.post('championship_api.php', {
        action: 'update_presence',
        tourn_ID: 1,
        loc_ID: 123,
        username: 'Host Name'
    });
}, 30000);
```

### Get Online Users
**Purpose:** Get list of online users  
**Method:** GET  
**Action:** `get_online_users`

**Parameters:**
- `tourn_ID` (required)

**Response:**
```json
{
  "success": true,
  "data": {
    "users": [
      {
        "user_id": 1,
        "username": "Host Denver",
        "loc_ID": 123,
        "location_name": "Denver Downtown",
        "last_seen": "2026-01-09 14:40:00"
      }
    ],
    "count": 1
  }
}
```

---

## Common Patterns

### Polling Pattern
For real-time updates, poll these endpoints regularly:

```javascript
let lastCheck = 0;

function pollUpdates() {
    // Get new messages
    $.get('championship_api.php', {
        action: 'get_chat_messages',
        tourn_ID: TOURN_ID,
        room: currentRoom,
        since: lastCheck
    }, function(response) {
        if (response.success && response.data.messages.length > 0) {
            displayMessages(response.data.messages);
            lastCheck = Date.now() / 1000;
        }
    });
    
    // Get new notifications
    $.get('championship_api.php', {
        action: 'get_notifications',
        tourn_ID: TOURN_ID,
        loc_ID: LOC_ID,
        since: lastCheck
    }, function(response) {
        if (response.success && response.data.count > 0) {
            displayNotifications(response.data.notifications);
        }
    });
}

// Poll every 5 seconds
setInterval(pollUpdates, 5000);
```

### Error Handling
Always handle errors gracefully:

```javascript
$.ajax({
    url: 'championship_api.php',
    method: 'POST',
    data: { ... },
    success: function(response) {
        if (response.success) {
            // Handle success
        } else {
            console.error('API Error:', response.message);
            alert('Error: ' + response.message);
        }
    },
    error: function(xhr, status, error) {
        console.error('Request failed:', error);
        alert('Connection error. Please check your internet connection.');
    }
});
```

---

## Database Tables Reference

### tournament_status
Tracks each location's progress and readiness.

**Key Fields:**
- `tourn_ID`, `loc_ID`, `game_date` - Unique identifier
- `round_1_complete` through `round_6_complete` - Boolean flags
- `halftime_finalized`, `final_finalized` - Y/N flags
- `ready_for_halftime`, `ready_for_final` - Boolean flags
- `last_ping` - Last heartbeat timestamp
- `is_online` - Boolean flag

### championship_notifications
System notifications and broadcasts.

**Key Fields:**
- `tourn_ID` - Tournament ID
- `from_loc_ID` - Sender location (NULL for system)
- `to_loc_ID` - Recipient location (NULL for broadcast)
- `message` - Message text
- `notification_type` - info, success, warning, alert
- `is_read` - Boolean flag

### championship_chat
Chat messages with room support.

**Key Fields:**
- `tourn_ID` - Tournament ID
- `room` - Room name (general, hq, etc.)
- `user_id`, `username` - Sender info
- `loc_ID`, `location_name` - Sender location
- `message` - Message text
- `message_type` - text, system, alert

### championship_presence
Online user tracking.

**Key Fields:**
- `tourn_ID`, `user_id` - Unique identifier
- `username`, `loc_ID`, `location_name` - User info
- `last_seen` - Last activity timestamp
- `is_active` - Boolean flag

Users are considered online if `last_seen` is within last 2 minutes.

---

## Testing Checklist

- [ ] Dashboard loads and shows locations
- [ ] Locations update status every 30 seconds
- [ ] Chat messages send and receive
- [ ] Online users list updates
- [ ] Notifications appear in dashboard
- [ ] Finalize buttons lock scores
- [ ] Broadcast messages reach all locations
- [ ] Offline detection works (stop heartbeat and wait 2 minutes)

---

## Performance Tips

1. **Reduce polling frequency** if server load is high
2. **Cache dashboard data** on client side briefly
3. **Use websockets** for production (future enhancement)
4. **Add database indexes** on commonly queried fields
5. **Clean up old data** periodically (30+ days old)

---

## Common Issues

**Problem:** Dashboard shows stale data  
**Solution:** Check auto-refresh is running, reduce polling interval

**Problem:** Location marked offline but is online  
**Solution:** Verify heartbeat is being sent, check last_ping in database

**Problem:** Chat messages not appearing  
**Solution:** Check `since` timestamp, verify room name matches

**Problem:** Finalize button doesn't appear  
**Solution:** Check `tourn_ID` is set, verify correct round/view state

---

**Version:** 1.0  
**Last Updated:** January 2026
