# Heat Status System Documentation

## Overview

The heat status system provides a comprehensive workflow management for heats in events. Instead of a simple binary active/inactive state, heats now support multiple statuses that reflect their lifecycle.

## Heat Status Values

### 1. **pending** (Default)
- **Description**: Heat is configured but not yet started
- **Use Case**: Initial state for all newly created heats
- **Available Actions**:
  - ✅ Activate Heat → active
  - ✅ Cancel → cancelled
  - ✅ Reschedule → rescheduled
  - ✅ Edit Configuration
  - ✅ View Results
- **Badge Color**: Gray (Secondary)
- **Icon**: fa-pause

### 2. **active**
- **Description**: Heat is currently in progress
- **Use Case**: Heat is live and judges are scoring
- **Available Actions**:
  - ✅ Finish Heat → finished
  - ✅ Set Pending → pending (pause/deactivate)
  - ✅ Cancel → cancelled
  - ✅ Reschedule → rescheduled
  - ✅ Change Active Run (Previous/Next)
  - ✅ View Real-time Results
- **Badge Color**: Yellow/Warning
- **Icon**: fa-bolt
- **Special Features**:
  - Shows "ACTIVE" badge
  - Displays current run number
  - Green border on heat card
  - Run navigation controls visible

### 3. **finished**
- **Description**: Heat has been completed successfully
- **Use Case**: All scoring is done, heat is closed
- **Available Actions**:
  - ✅ Reactivate → active (reopen for corrections)
  - ✅ Set Pending → pending (reset for re-running)
  - ✅ View Final Results
  - ✅ View Configuration
- **Badge Color**: Blue/Info
- **Icon**: fa-check-circle
- **Special Features**:
  - Blue border on heat card
  - Shows "FINISHED" badge
  - Can be reopened if needed

### 4. **cancelled**
- **Description**: Heat was cancelled and did not complete
- **Use Case**: Weather issues, technical problems, insufficient participants
- **Available Actions**:
  - ✅ Activate → active (resume)
  - ✅ Reschedule → rescheduled
  - ✅ Set Pending → pending (reset)
  - ✅ View Partial Results
  - ✅ Edit Configuration
- **Badge Color**: Red/Danger
- **Icon**: fa-ban
- **Special Features**:
  - Red border on heat card
  - Shows "CANCELLED" badge
  - Can be reactivated or rescheduled

### 5. **rescheduled**
- **Description**: Heat was postponed to another time
- **Use Case**: Timing conflicts, weather delays
- **Available Actions**:
  - ✅ Activate → active (start when ready)
  - ✅ Cancel → cancelled
  - ✅ Set Pending → pending (reset)
  - ✅ Edit Configuration (update time/settings)
  - ✅ View Results
- **Badge Color**: Orange/Warning
- **Icon**: fa-clock
- **Special Features**:
  - Orange border on heat card
  - Shows "RESCHEDULED" badge
  - Flexible return to any state

## Database Schema

### Table: `event_heat_settings`

```sql
ALTER TABLE event_heat_settings 
ADD COLUMN status ENUM('pending', 'active', 'finished', 'cancelled', 'rescheduled') 
NOT NULL DEFAULT 'pending'
AFTER is_active;

-- Indexes for performance
ADD INDEX idx_status (status);
ADD INDEX idx_event_status (event_id, status);
```

### Backward Compatibility

The `is_active` column is retained for backward compatibility:
- `status = 'active'` → `is_active = 1`
- All other statuses → `is_active = 0`

**Migration Path**: The `is_active` column can be removed after full testing by running:
```sql
ALTER TABLE event_heat_settings DROP COLUMN is_active;
```

## Status Transitions

### Valid Transitions (Flexible System)

The system now supports flexible transitions between all statuses to handle real-world event scenarios:

#### From **pending**:
```
pending → active       (Start the heat)
pending → cancelled    (Cancel before starting)
pending → rescheduled  (Postpone before starting)
```

#### From **active**:
```
active → finished      (Complete the heat normally)
active → pending       (Pause/deactivate temporarily)
active → cancelled     (Abort the heat)
active → rescheduled   (Postpone mid-heat)
```

#### From **finished**:
```
finished → active      (Reopen for corrections)
finished → pending     (Reset for re-running)
```

#### From **cancelled**:
```
cancelled → active     (Resume cancelled heat)
cancelled → pending    (Reset to pending)
cancelled → rescheduled (Reschedule cancelled heat)
```

#### From **rescheduled**:
```
rescheduled → active   (Start rescheduled heat)
rescheduled → pending  (Return to pending)
rescheduled → cancelled (Cancel rescheduled heat)
```

### Transition Flow Diagram

```
       ┌─────────────┐
       │   PENDING   │◄─────────┐
       └──────┬──────┘          │
              │                 │
     ┌────────┼────────┐        │
     │        │        │        │
     ▼        ▼        ▼        │
┌─────────┐ ┌────────┐ ┌──────────────┐
│CANCELLED│ │ ACTIVE │ │ RESCHEDULED  │
└────┬────┘ └───┬────┘ └──────┬───────┘
     │          │              │
     │     ┌────┼────┐         │
     │     │    │    │         │
     └─────►    ▼    ◄─────────┘
           ┌─────────┐
           │FINISHED │
           └─────────┘

Legend:
→ = Can transition to
◄ = Can transition from
```

### Status Transition Use Cases

#### **Scenario 1**: Heat needs adjustment mid-competition
- **Active** → **Pending** → modify settings → **Active**
- Allows pausing for technical issues

#### **Scenario 2**: Results need correction
- **Finished** → **Active** → fix scores → **Finished**
- Reopens completed heat for corrections

#### **Scenario 3**: Weather delay
- **Active** → **Rescheduled** → wait for conditions → **Active**
- Handles interruptions gracefully

#### **Scenario 4**: False start / reset
- **Active** → **Pending** → reset participants → **Active**
- Clean slate without cancelling

#### **Scenario 5**: Cancelled heat gets rescheduled
- **Cancelled** → **Rescheduled** → new time → **Active**
- Flexibility in event management

## Implementation Files

### 1. Database Migration
- **File**: `admin/migrations/add_heat_status_column.php`
- **Purpose**: Adds status column and migrates existing data
- **Usage**: Run once via CLI: `php add_heat_status_column.php`

### 2. Backend Logic
- **File**: `admin/admin_heat_config.php`
- **Changes**:
  - POST handlers for status changes
  - SQL queries include status field
  - Default status values in heat configuration
  - JavaScript functions for status management

### 3. API Endpoint
- **File**: `admin/heat_cards_api.php`
- **Changes**:
  - Returns status field
  - Conditional UI based on status
  - Status badges and colors
  - Action buttons per status

### 4. JavaScript Functions

#### New Functions
```javascript
closeHeat(heatNumber)      // Mark heat as finished
cancelHeat(heatNumber)     // Cancel the heat
rescheduleHeat(heatNumber) // Reschedule the heat
activateHeat(heatNumber)   // Activate/reactivate heat
```

#### Updated Functions
```javascript
// Now uses status === 'active' instead of is_active == 1
confirmActivateHeat()
loadHeatCards()
```

## User Interface Changes

### Heat Card Display

#### Pending Heat
```
┌─────────────────────────────┐
│ 🔥 Heat 1      [PENDING]   │
│ Qualification Round         │
├─────────────────────────────┤
│ 👥 24 athletes  🔄 2 runs  │
│ ⏰ Start: 10:00            │
│ Progress: 0%                │
├─────────────────────────────┤
│ [▶️ Activate Heat]         │
│ [❌ Cancel] [🕒 Reschedule]│
│ [⚙️ Config] [🏆 Results]   │
└─────────────────────────────┘
```

#### Active Heat
```
┌─────────────────────────────┐
│ 🔥 Heat 1      [ACTIVE]    │ ← Green border
│ Qualification Round         │
├─────────────────────────────┤
│ Current Run: 1/2            │
│ [← Prev] [Next →]          │
│                             │
│ Progress: 45%               │
├─────────────────────────────┤
│ [✓ Finish] [⏸️ Pending]    │
│ [❌ Cancel] [🕒 Reschedule]│
│ [⚙️ Config] [🏆 Results]   │
└─────────────────────────────┘
```

#### Finished Heat
```
┌─────────────────────────────┐
│ 🔥 Heat 1    [FINISHED]    │ ← Blue border
│ Qualification Round         │
├─────────────────────────────┤
│ Progress: 100% ✓            │
├─────────────────────────────┤
│ [🔄 Reactivate][⏸️ Pending]│
│ [⚙️ Config] [🏆 Results]   │
└─────────────────────────────┘
```

#### Cancelled Heat
```
┌─────────────────────────────┐
│ 🔥 Heat 1   [CANCELLED]    │ ← Red border
│ Qualification Round         │
├─────────────────────────────┤
│ Status: Cancelled           │
├─────────────────────────────┤
│ [▶️ Activate Heat]          │
│ [🕒 Reschedule][⏸️ Pending]│
│ [⚙️ Config] [🏆 Results]   │
└─────────────────────────────┘
```

#### Rescheduled Heat
```
┌─────────────────────────────┐
│ 🔥 Heat 1  [RESCHEDULED]   │ ← Orange border
│ Qualification Round         │
├─────────────────────────────┤
│ New Time: TBD               │
├─────────────────────────────┤
│ [▶️ Activate When Ready]   │
│ [❌ Cancel] [⏸️ Pending]    │
│ [⚙️ Config] [🏆 Results]   │
└─────────────────────────────┘
```

## API Integration

### Judge Scoring Panel
**File**: `api/judge_score_api.php`

Judges can only score participants in heats with `status = 'active'`:

```php
// Check if heat is active
$stmt = $pdo->prepare("
    SELECT status 
    FROM event_heat_settings 
    WHERE event_id = ? AND heat_number = ?
");
$stmt->execute([$event_id, $heat_number]);
$heat = $stmt->fetch();

if ($heat['status'] !== 'active') {
    throw new Exception('This heat is not currently active for scoring');
}
```

### Public Dashboard
**File**: `api/public_dashboard_api.php`

Display logic based on status:
- **pending**: Show "Starting Soon"
- **active**: Show live scoring
- **finished**: Show final results
- **cancelled**: Show "Event Cancelled"
- **rescheduled**: Show "Rescheduled - New Time TBD"

## Benefits of Status System

### 1. **Better Event Management**
- Clear lifecycle tracking
- Prevents accidental data changes
- Professional event flow

### 2. **Data Protection**
- Finished heats cannot be modified
- Clear audit trail
- Prevents scoring in inactive heats

### 3. **Improved Communication**
- Athletes/spectators see clear heat status
- Organizers can plan better
- Judges know exactly what's scorable

### 4. **Reporting & Analytics**
- Query heats by status
- Track completion rates
- Identify problematic heats

### 5. **Flexibility**
- Handle weather delays
- Manage schedule changes
- Support multi-day events

## Migration Guide

### For Existing Events

1. **Run Migration Script**
   ```bash
   cd admin/migrations
   php add_heat_status_column.php
   ```

2. **Verify Data**
   ```sql
   SELECT heat_number, is_active, status 
   FROM event_heat_settings 
   WHERE event_id = YOUR_EVENT_ID;
   ```

3. **Update Bookmarks/Links**
   - No changes needed - all existing functionality preserved

4. **Train Users**
   - Educate organizers on new status options
   - Update documentation/help guides

### For New Integrations

When building new features that interact with heats:

```php
// ✅ CORRECT - Use status field
$active_heats = $pdo->query("
    SELECT * FROM event_heat_settings 
    WHERE status = 'active'
")->fetchAll();

// ❌ AVOID - Old approach
$active_heats = $pdo->query("
    SELECT * FROM event_heat_settings 
    WHERE is_active = 1
")->fetchAll();
```

## Future Enhancements

Potential additions to the status system:

1. **Status Timestamps**
   - Track when each status was set
   - Enable time-based queries

2. **Status Comments**
   - Allow notes when cancelling/rescheduling
   - Provide context for status changes

3. **Automated Status Transitions**
   - Auto-finish when all participants scored
   - Auto-activate at scheduled time

4. **Status History Log**
   - Full audit trail of status changes
   - Who changed status and when

5. **Email Notifications**
   - Notify stakeholders on status changes
   - Automated alerts for cancelled/rescheduled heats

## Troubleshooting

### Heat stuck in "active" status
```php
// Manually set to finished
UPDATE event_heat_settings 
SET status = 'finished', is_active = 0, active_run = 0 
WHERE event_id = ? AND heat_number = ?;
```

### Need to reopen finished heat
```sql
-- Careful! Only do if absolutely necessary
UPDATE event_heat_settings 
SET status = 'active', is_active = 1 
WHERE event_id = ? AND heat_number = ?;
```

### Status not updating in UI
1. Clear browser cache
2. Check AJAX endpoint: `admin/heat_cards_api.php`
3. Verify JavaScript console for errors
4. Refresh heat cards manually

## Support

For issues or questions:
1. Check console logs in browser DevTools
2. Review PHP error logs
3. Verify database migration completed
4. Test with a new event first

---

**Version**: 1.0  
**Last Updated**: November 2025  
**Compatibility**: StyleScore v2.0+
