# Championship Features - Installation & Integration Guide

## Overview
This package adds championship/tournament features to your modern trivia system, enabling multi-location coordination, real-time status tracking, improved chat, and centralized control.

## Files Included
- `championship_schema.sql` - Database schema for championship features
- `championship_api.php` - Backend API for championship operations
- `championship_dashboard.php` - Real-time multi-location status dashboard
- `championship_chat.php` - Improved chat system with rooms and presence
- `championship_nav_additions.php` - Code snippets to add to nav.php
- `README_CHAMPIONSHIP.md` - This file

## Installation Steps

### 1. Database Setup
Run the SQL schema on your Digital Ocean server:

```bash
mysql -u root -p triviocity_local < championship_schema.sql
```

This will create the following tables:
- `tournament_status` - Tracks each location's progress
- `championship_notifications` - System notifications and alerts
- `championship_chat` - Chat messages
- `championship_presence` - Online user tracking

It will also add championship columns to your existing `team_scoring` table if they don't exist:
- `tourn_ID` - Tournament identifier
- `H_finalized` - Halftime finalization status
- `F_finalized` - Final finalization status

### 2. File Deployment
Upload these files to your trivia directory on Digital Ocean:

```bash
scp championship_api.php your-server:/path/to/trivia/
scp championship_dashboard.php your-server:/path/to/trivia/
scp championship_chat.php your-server:/path/to/trivia/
```

### 3. Integration with Existing System

#### A. Add Championship Controls to nav.php

Open your existing `modern/trivia/nav.php` and add these buttons to the menu section (around line 108-130):

```php
<?php if ($tourn_ID > 0) { // Only show for championship games ?>
<a href="championship_dashboard.php" target="_blank" class="btn btn-warning btn-block">
    <i class="fas fa-trophy"></i> Championship Dashboard
</a>
<a href="championship_chat.php" target="_blank" class="btn btn-info btn-block">
    <i class="fas fa-comments"></i> Championship Chat
</a>
<a href="#" id="btn-finalize-halftime" class="btn btn-success btn-block" style="display: none;">
    <i class="fas fa-check-circle"></i> Finalize Halftime
</a>
<a href="#" id="btn-finalize-final" class="btn btn-danger btn-block" style="display: none;">
    <i class="fas fa-flag-checkered"></i> Finalize Final
</a>
<?php } ?>
```

#### B. Add Championship JavaScript to nav.php

Add this JavaScript code at the bottom of nav.php (before the closing `</script>` tag):

```javascript
// Championship Features
<?php if ($tourn_ID > 0) { ?>

// Show finalization buttons when appropriate
$(document).ready(function() {
    // Show halftime finalize button when on halftime scoring
    if (state.round === 'H' && state.view === 'scores') {
        $('#btn-finalize-halftime').show();
    }
    
    // Show final finalize button when on final scoring
    if (state.round === 'F' && state.view === 'scores') {
        $('#btn-finalize-final').show();
    }
});

// Finalize halftime scores
$('#btn-finalize-halftime').click(function(e) {
    e.preventDefault();
    
    if (!confirm('Are you sure you want to finalize halftime scores? This cannot be undone!')) {
        return;
    }
    
    $.ajax({
        url: 'championship_api.php',
        method: 'POST',
        data: {
            action: 'finalize_scores',
            tourn_ID: <?php echo $tourn_ID; ?>,
            loc_ID: <?php echo $loc_ID; ?>,
            score_type: 'H',
            game_date: '<?php echo date('Y-m-d'); ?>'
        },
        success: function(response) {
            if (response.success) {
                alert('Halftime scores finalized!');
                $('#btn-finalize-halftime').hide();
                
                // Mark location as ready
                $.ajax({
                    url: 'championship_api.php',
                    method: 'POST',
                    data: {
                        action: 'mark_section_ready',
                        tourn_ID: <?php echo $tourn_ID; ?>,
                        loc_ID: <?php echo $loc_ID; ?>,
                        section: 'halftime',
                        game_date: '<?php echo date('Y-m-d'); ?>'
                    }
                });
            } else {
                alert('Error: ' + response.message);
            }
        }
    });
});

// Finalize final scores
$('#btn-finalize-final').click(function(e) {
    e.preventDefault();
    
    if (!confirm('Are you sure you want to finalize FINAL scores? This cannot be undone!')) {
        return;
    }
    
    $.ajax({
        url: 'championship_api.php',
        method: 'POST',
        data: {
            action: 'finalize_scores',
            tourn_ID: <?php echo $tourn_ID; ?>,
            loc_ID: <?php echo $loc_ID; ?>,
            score_type: 'F',
            game_date: '<?php echo date('Y-m-d'); ?>'
        },
        success: function(response) {
            if (response.success) {
                alert('Final scores finalized!');
                $('#btn-finalize-final').hide();
                
                // Mark location as ready
                $.ajax({
                    url: 'championship_api.php',
                    method: 'POST',
                    data: {
                        action: 'mark_section_ready',
                        tourn_ID: <?php echo $tourn_ID; ?>,
                        loc_ID: <?php echo $loc_ID; ?>,
                        section: 'final',
                        game_date: '<?php echo date('Y-m-d'); ?>'
                    }
                });
            } else {
                alert('Error: ' + response.message);
            }
        }
    });
});

// Send heartbeat to update location status
setInterval(function() {
    $.ajax({
        url: 'championship_api.php',
        method: 'POST',
        data: {
            action: 'update_location_status',
            tourn_ID: <?php echo $tourn_ID; ?>,
            loc_ID: <?php echo $loc_ID; ?>,
            game_date: '<?php echo date('Y-m-d'); ?>'
        }
    });
}, 30000); // Every 30 seconds

<?php } ?>
```

### 4. Testing

#### Test Championship Dashboard
1. Set a `tourn_ID` cookie in your browser (or pass it in the URL):
   ```
   https://your-server.com/championship_dashboard.php?tourn_ID=1
   ```

2. The dashboard should show:
   - All locations participating in the tournament
   - Their scoring progress
   - Online/offline status
   - Finalization status

#### Test Championship Chat
1. Open the chat in multiple browser windows/tabs:
   ```
   https://your-server.com/championship_chat.php?tourn_ID=1&username=TestHost1
   ```

2. Test features:
   - Send messages
   - Switch between rooms (General, Championship HQ)
   - See online users
   - Messages appear in real-time

## How It Works

### During a Championship Event:

1. **Setup Phase:**
   - Central coordinator opens Championship Dashboard
   - Each location loads their normal nav.php (with championship buttons visible)

2. **Game Play:**
   - Each location runs their game independently
   - Locations score their teams normally
   - Dashboard shows real-time progress of all locations

3. **Halftime:**
   - Each location finishes scoring rounds 1-3
   - Host clicks "Finalize Halftime" button
   - Dashboard shows location as "Finalized"
   - Central coordinator can see when all locations are ready

4. **Second Half:**
   - Central coordinator gives the "go ahead" (via chat or broadcast)
   - Locations proceed with second half
   - Same process for final scoring

5. **Communication:**
   - Hosts use Championship Chat for coordination
   - Central coordinator uses Broadcast Message for announcements
   - Notifications show in dashboard when locations complete sections

## Key Features

### Championship Dashboard
- **Real-time status** - See all locations at once
- **Color-coded indicators** - Quickly identify who's ready/waiting
- **Progress tracking** - Monitor completion of each section
- **Broadcast messaging** - Send announcements to all locations
- **Online status** - See which locations are connected

### Improved Chat
- **Multiple rooms** - General chat + Championship HQ for coordinators
- **User presence** - See who's online from each location
- **Better UI** - Modern, easy-to-read interface
- **Fast updates** - 5-second refresh rate
- **Message history** - Scrollable conversation log

### Smart Coordination
- **Finalization locks** - Prevent accidental score changes
- **Readiness tracking** - Locations mark when they're ready to proceed
- **Automatic notifications** - System alerts when milestones are reached
- **Heartbeat monitoring** - Detect if a location goes offline

## Troubleshooting

### Dashboard shows no locations
- Check that `tourn_ID` is set correctly
- Verify teams have `tourn_ID` in their records
- Check `team_active = 1` in database

### Chat messages not appearing
- Check browser console for errors
- Verify championship_api.php is accessible
- Check file permissions (should be 644)

### Finalize button doesn't work
- Ensure location has teams with scores entered
- Check database connection
- Look for JavaScript errors in console

### Location shows as offline
- Location needs to send heartbeats (auto-happens in nav.php)
- Check last_ping timestamp in tournament_status table
- Verify internet connection at location

## Customization

### Adjust Refresh Rates
In championship_dashboard.php, find this line:
```javascript
setInterval(() => { ... }, 10000); // Change 10000 to desired milliseconds
```

In championship_chat.php, find:
```javascript
setInterval(() => { ... }, 5000); // Change 5000 to desired milliseconds
```

### Modify Color Scheme
Edit CSS variables at the top of each file:
```css
:root {
    --status-ready: #28a745;    /* Green */
    --status-waiting: #ffc107;  /* Yellow */
    --status-progress: #17a2b8; /* Blue */
    --status-offline: #dc3545;  /* Red */
    --status-complete: #6f42c1; /* Purple */
}
```

### Add More Chat Rooms
In championship_chat.php, add rooms to the sidebar:
```html
<div class="room-item" data-room="your-room-name">
    <i class="fas fa-hashtag"></i>
    <span>Your Room Name</span>
</div>
```

## Security Notes

- Championship API uses session authentication from your existing system
- All database queries use prepared statements
- No raw user input is executed
- Consider adding IP whitelist for dashboard access in production
- Use HTTPS in production (already configured on Digital Ocean)

## Support

For issues or questions:
- Check error logs: `/var/log/apache2/error.log` (or your server's log location)
- Enable debugging: Set `ini_set('display_errors', 1);` temporarily
- Contact: q@teamtrivia.com

## Future Enhancements

Possible additions for future versions:
- Mobile-responsive dashboard
- Push notifications (browser notifications API)
- Score validation/verification tools
- Historical tournament data viewer
- Export results to PDF/Excel
- Video streaming integration
- Automated scoring checks

---

**Version:** 1.0  
**Date:** January 2026  
**Compatible with:** Modern Trivia System v5.0+
