# Championship System - Deployment Guide
## For `/champ/` Folder Setup

---

## Directory Structure

```
/var/www/gamesys.teamtrivia.com/
├── conn.php                      (existing - database connection)
├── logged_in.php                 (existing - authentication)
├── css/                          (existing - bootstrap, etc.)
├── js/                           (existing - jquery, etc.)
├── champ/                        (NEW - championship system)
│   ├── championship_api.php
│   ├── championship_dashboard.php
│   └── championship_chat.php
```

---

## Step 1: Create the `/champ/` Directory

SSH into your server and create the directory:

```bash
cd /var/www/gamesys.teamtrivia.com/
mkdir champ
chmod 755 champ
```

---

## Step 2: Upload Championship Files

Upload these 3 files to `/var/www/gamesys.teamtrivia.com/champ/`:
- `championship_api.php`
- `championship_dashboard.php`
- `championship_chat.php`

**Using SCP (from your local machine):**
```bash
scp championship_api.php your-server:/var/www/gamesys.teamtrivia.com/champ/
scp championship_dashboard.php your-server:/var/www/gamesys.teamtrivia.com/champ/
scp championship_chat.php your-server:/var/www/gamesys.teamtrivia.com/champ/
```

**Or using FTP/SFTP:**
- Connect to your server
- Navigate to `/var/www/gamesys.teamtrivia.com/champ/`
- Upload the three files

**Set proper permissions:**
```bash
cd /var/www/gamesys.teamtrivia.com/champ/
chmod 644 *.php
```

---

## Step 3: Run the Database Schema

Upload `championship_schema.sql` to your server, then run:

```bash
mysql -u your_db_user -p your_db_name < championship_schema.sql
```

This creates 4 new tables:
- `tournament_status` - Tracks location progress
- `championship_notifications` - System messages
- `championship_chat` - Chat messages
- `championship_presence` - Online users

It also adds championship columns to your existing `team_scoring` table:
- `tourn_ID` - Tournament identifier
- `H_finalized` - Halftime finalized flag
- `F_finalized` - Final finalized flag

---

## Step 4: Verify File Paths

The updated files already have the correct paths configured:

### Database & Auth (in all 3 files):
```php
require_once('../conn.php');        // Points to parent directory
require_once('../logged_in.php');   // Points to parent directory
```

### CSS & JavaScript (in dashboard and chat):
```html
<link href="../css/bootstrap.min.css" rel="stylesheet">
<script src="../js/jquery.min.js"></script>
```

**No additional path changes needed!** Everything is already configured for the `/champ/` subdirectory.

---

## Step 5: Test the Installation

### Test 1: API Endpoint
Visit in your browser:
```
https://gamesys.teamtrivia.com/champ/championship_api.php?action=get_championship_status&tourn_ID=1
```

**Expected Result:** JSON response (even if no data, should not show errors)

### Test 2: Dashboard
Visit:
```
https://gamesys.teamtrivia.com/champ/championship_dashboard.php?tourn_ID=1
```

**Expected Result:** Dashboard page loads with "No locations found" message (if no test data)

### Test 3: Chat
Visit:
```
https://gamesys.teamtrivia.com/champ/championship_chat.php?tourn_ID=1&username=TestUser
```

**Expected Result:** Chat interface loads with rooms visible

---

## Step 6: Create Test Data (Optional)

To test with sample data, run these SQL queries:

```sql
-- Create a test tournament
INSERT INTO tournaments (tournament_name, tournament_date, active) 
VALUES ('Test Championship', '2026-02-15', 1);

-- Get the tourn_ID (let's say it's 1)
-- Create test tournament status
INSERT INTO tournament_status 
(tourn_ID, loc_ID, location_name, region_name, game_date, total_teams) 
VALUES 
(1, 101, 'Denver Downtown', 'Colorado', '2026-02-15', 12),
(1, 102, 'Boulder Brewery', 'Colorado', '2026-02-15', 8),
(1, 103, 'Fort Collins Tap', 'Colorado', '2026-02-15', 10);

-- Now refresh the dashboard - you should see 3 locations!
```

---

## Step 7: Integration with Main System

When you're ready to integrate with your main trivia system (nav.php), add these buttons to the navigation menu:

### In your existing nav.php:
```php
<?php if ($tourn_ID > 0) { // Only show for championships ?>
<div class="championship-controls">
    <a href="/champ/championship_dashboard.php" target="_blank" class="btn btn-warning">
        <i class="fas fa-trophy"></i> Championship Dashboard
    </a>
    <a href="/champ/championship_chat.php" target="_blank" class="btn btn-info">
        <i class="fas fa-comments"></i> Championship Chat
    </a>
</div>
<?php } ?>
```

### Add the heartbeat (keeps location marked as online):
```javascript
<?php if ($tourn_ID > 0) { ?>
// Send location heartbeat every 30 seconds
setInterval(function() {
    $.post('/champ/championship_api.php', {
        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);
<?php } ?>
```

---

## Troubleshooting

### "500 Internal Server Error"
**Check:**
- File permissions (should be 644 for .php files)
- Apache error log: `tail -f /var/log/apache2/error.log`
- PHP syntax: `php -l championship_api.php`

### "Connection failed" or database errors
**Check:**
- `conn.php` exists in parent directory
- Database credentials are correct
- Tables were created successfully: `SHOW TABLES LIKE 'championship%';`

### CSS/JavaScript not loading
**Check:**
- Paths are correct (`../css/` and `../js/`)
- Bootstrap and jQuery files exist in parent directories
- Browser console for 404 errors

### "Not authorized" or login issues
**Check:**
- `logged_in.php` exists and works
- Session is started properly
- User is logged into main system

### Dashboard shows "No locations found"
**This is normal if:**
- No championship data exists yet
- tourn_ID doesn't match any teams in database
- Try adding test data (see Step 6)

---

## Security Checklist

- ✅ All files use prepared statements (SQL injection protected)
- ✅ Session authentication required (via logged_in.php)
- ✅ Error display disabled in production
- ✅ File permissions set to 644 (not world-writable)
- ✅ Input validation on all API endpoints

**Additional recommendations:**
- Use HTTPS (should already be configured on Digital Ocean)
- Consider IP whitelist for dashboard in production
- Regularly review championship_chat table and purge old messages
- Back up database before major championships

---

## File Summary

**What's been updated for `/champ/` folder:**

1. ✅ Database includes point to `../conn.php`
2. ✅ Auth includes point to `../logged_in.php`  
3. ✅ CSS paths point to `../css/bootstrap.min.css`
4. ✅ JS paths point to `../js/jquery.min.js`

**Everything is ready to deploy!**

---

## Quick Start Command Sequence

```bash
# 1. Create directory
cd /var/www/gamesys.teamtrivia.com/
mkdir champ
chmod 755 champ

# 2. Upload files to /champ/
# (use SCP/FTP to upload 3 PHP files)

# 3. Set permissions
chmod 644 champ/*.php

# 4. Run SQL schema
mysql -u your_user -p your_database < championship_schema.sql

# 5. Test in browser
# Visit: https://gamesys.teamtrivia.com/champ/championship_dashboard.php?tourn_ID=1
```

---

## Need Help?

**Common Issues:**
- Path problems? Double-check `../` syntax
- Database errors? Verify schema ran successfully
- Page not loading? Check Apache error logs

**Questions?** Review the full documentation in:
- `README_CHAMPIONSHIP.md` - Complete feature documentation
- `CHAMPIONSHIP_API_REFERENCE.md` - API endpoint details
- `IMPLEMENTATION_SUMMARY.md` - Architecture overview

---

**Version:** 1.0 - Updated for `/champ/` Deployment  
**Last Updated:** February 2026  
**Ready to Deploy!** ✅
