# Core Features

## 8.1 Tournament Management

### Tournament Creation
- **Basic Information**: Name, description, location, dates
- **Tournament Type**: Single elimination, double elimination, round robin, group stage
- **Registration Settings**: Open/close dates, participant limits
- **Entry Fees**: Configurable entry fees and payment methods
- **Category Management**: Enable/disable categories with individual fees
- **Location Restrictions**: Configure category-specific location restrictions
- **Rules & Regulations**: Customizable tournament rules
- **Streaming Integration**: YouTube, Twitch, custom streaming URLs

### Tournament Configuration
```php
// Tournament creation example
$tournament = Tournament::create([
    'name' => 'Championship 2025',
    'type' => 'knockout',
    'format' => 'team',
    'start_date' => '2025-02-01',
    'end_date' => '2025-02-15',
    'max_participants' => 16,
    'entry_fee' => 1000,
    'bracket_settings' => [
        'seeding_method' => 'balanced',
        'auto_advance' => true
    ]
]);
```

### Category-Based Location Management
Administrators can configure location restrictions per tournament category:

- **Global Location Settings**: Countries and counties available to all unrestricted categories
- **Category-Specific Restrictions**: Each category (Men, Women, Youth Male, Youth Female, Children) can have:
  - Location restriction toggle (ON/OFF)
  - Custom location list when restrictions enabled
  - Free-form location entry when restrictions disabled

**Configuration Structure:**
```php
'category_locations' => [
    'men' => [
        'restrict_locations' => true,
        'locations' => ['Nairobi', 'Mombasa', 'Kisumu'],
    ],
    'women' => [
        'restrict_locations' => false,
        'locations' => [],
    ],
    // ... other categories
]
```

**Frontend Behavior:**
- When restriction ON: Teams select from dropdown of allowed locations
- When restriction OFF: Teams enter any location via text input
- Location options update dynamically based on selected category

### Tournament Status Management
- **Draft**: Tournament being created
- **Published**: Tournament is live and accepting registrations
- **Active**: Tournament is in progress
- **Completed**: Tournament finished
- **Cancelled**: Tournament cancelled

## 8.2 Team Registration

### Team Creation Process
1. **Tournament Selection**: Choose tournament to register for
2. **Category Selection**: Select team category (only enabled categories shown)
3. **Team Information**: Name, email, phone, contact details
4. **Location Entry**: 
   - If category has restrictions: Select from dropdown of allowed locations
   - If no restrictions: Enter any location via text input
5. **Captain Assignment**: Team manager account creation
6. **Player Addition**: Add team players with details (11-23 players)
7. **Official Addition**: Add team officials (coaches, managers)
8. **Review & Submit**: Final review and terms acceptance
9. **Payment Processing**: Entry fee payment (category-specific fee)
10. **Approval Workflow**: Admin approval process

### Team Registration Flow
```php
// Team registration service
class TeamRegistrationService
{
    public function registerTeamForTournament(array $data, Tournament $tournament): array
    {
        DB::beginTransaction();
        
        try {
            // Create or find team
            $team = $this->createOrFindTeam($data['team']);
            
            // Handle captain
            $captain = $this->handleCaptain($data['captain'], $team);
            
            // Register for tournament
            $this->registerForTournament($team, $tournament);
            
            // Add players
            $this->addPlayers($data['players'], $team);
            
            // Add officials
            $this->addOfficials($data['officials'], $team);
            
            DB::commit();
            return ['success' => true, 'team' => $team];
            
        } catch (\Exception $e) {
            DB::rollback();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
}
```

### Team Approval System
- **First Approval**: Initial admin review
- **Second Approval**: Secondary review (if enabled)
- **Document Verification**: ID and document validation
- **Payment Verification**: Entry fee confirmation
- **Final Approval**: Tournament participation confirmation

## 8.3 Player Management

### Player Registration
- **Personal Information**: Name, date of birth, nationality
- **Contact Details**: Phone, email, emergency contact
- **Physical Attributes**: Height, weight, preferred foot
- **Position**: Playing position and jersey number
- **Documents**: ID front/back images, profile photo
- **Medical Information**: Medical conditions, allergies

### Player Profile Management
```php
// Player model with relationships
class Player extends Model
{
    protected $fillable = [
        'user_id', 'team_id', 'jersey_number', 'position',
        'height', 'weight', 'preferred_foot', 'date_of_birth',
        'nationality', 'id_number', 'phone', 'email',
        'emergency_contact', 'medical_conditions', 'profile_image',
        'id_front_image', 'id_back_image', 'status', 'otp_verified'
    ];

    public function team() { return $this->belongsTo(Team::class); }
    public function user() { return $this->belongsTo(User::class); }
    public function statistics() { return $this->hasOne(PlayerStatistics::class); }
}
```

### Player Statistics Tracking
- **Match Statistics**: Goals, assists, cards, saves
- **Performance Metrics**: Pass accuracy, tackles, interceptions
- **Tournament History**: Previous tournament participation
- **Achievements**: Awards, recognitions, milestones

## 8.4 Match Management

### Match Creation
- **Automatic Generation**: Bracket-based match creation
- **Manual Creation**: Custom match scheduling
- **Round Management**: Tournament round progression
- **Venue Assignment**: Match location and facilities
- **Referee Assignment**: Match official assignment

### Match Lifecycle
```php
// Match status progression
'scheduled' => 'live' => 'completed'
     ↓           ↓         ↓
'cancelled'  'paused'  'verified'
```

### Match Operations
- **Start Match**: Begin match with timestamp
- **Update Score**: Real-time score updates
- **Pause/Resume**: Match interruption handling
- **Complete Match**: Finalize match results
- **Verify Results**: Admin verification process

### Match Results
```php
// Match result structure
$match->update([
    'status' => 'completed',
    'team1_score' => 2,
    'team2_score' => 1,
    'winner_id' => $team1->id,
    'completed_at' => now()
]);
```

## 8.5 Bracket System

### Bracket Generation
- **Single Elimination**: Classic knockout tournament
- **Double Elimination**: Winners and losers brackets
- **Round Robin**: Every team plays every other team
- **Group Stage**: Group phase followed by knockout
- **Swiss System**: Performance-based pairing

### Bracket Service
```php
class TournamentBracketService
{
    public function generateBracket(array $participants, string $type): Bracket
    {
        $bracket = Bracket::create([
            'tournament_id' => $this->tournament->id,
            'name' => $this->getBracketName($type),
            'type' => $type,
            'is_active' => true
        ]);

        // Apply seeding
        $seededParticipants = $this->applySeeding($participants);
        
        // Generate matches based on type
        switch ($this->tournament->type) {
            case 'knockout':
                $this->generateSingleElimination($bracket, $seededParticipants);
                break;
            case 'round-robin':
                $this->generateRoundRobin($bracket, $seededParticipants);
                break;
            // ... other types
        }

        return $bracket;
    }
}
```

### Seeding Algorithms
- **Random Seeding**: Completely random placement
- **Ranking Seeding**: Based on participant rankings
- **Rating Seeding**: Based on skill ratings/ELO scores
- **Balanced Seeding**: Strategic placement to avoid early top-seed matchups

## 8.6 Payment Integration

### M-Pesa Integration
- **STK Push**: Direct mobile payment initiation
- **Payment Status**: Real-time payment tracking
- **Callback Handling**: Automatic payment confirmation
- **Receipt Generation**: Payment receipt creation

### Payment Service
```php
class MpesaService
{
    public function stkPush(string $phoneNumber, float $amount, string $accountReference): array
    {
        $accessToken = $this->generateAccessToken();
        
        $payload = [
            'BusinessShortCode' => $this->shortcode,
            'Password' => $this->generatePassword(),
            'Timestamp' => now()->format('YmdHis'),
            'TransactionType' => 'CustomerPayBillOnline',
            'Amount' => $amount,
            'PartyA' => $this->formatPhoneNumber($phoneNumber),
            'PartyB' => $this->shortcode,
            'PhoneNumber' => $this->formatPhoneNumber($phoneNumber),
            'CallBackURL' => $this->callbackUrl,
            'AccountReference' => $accountReference,
            'TransactionDesc' => 'Tournament Registration'
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $accessToken,
            'Content-Type' => 'application/json'
        ])->post($this->baseUrl . '/mpesa/stkpush/v1/processrequest', $payload);

        return $response->json();
    }
}
```

### Payment Status Tracking
- **Pending**: Payment initiated
- **Processing**: Payment in progress
- **Completed**: Payment successful
- **Failed**: Payment failed
- **Cancelled**: Payment cancelled

## 8.7 Certificate Generation

### Certificate Types
- **Participation Certificates**: For all participants
- **Achievement Certificates**: For winners and special achievements
- **Digital IDs**: Player identification cards
- **Team Certificates**: Team participation recognition

### Certificate Service
```php
class CertificateService
{
    public function generatePlayerCertificate(Player $player, Tournament $tournament): string
    {
        $certificateData = [
            'player_name' => $player->name,
            'team_name' => $player->team->name,
            'tournament_name' => $tournament->name,
            'tournament_date' => $tournament->start_date,
            'position' => $player->position,
            'jersey_number' => $player->jersey_number
        ];

        return $this->generatePDF($certificateData, 'player-certificate');
    }
}
```

### Certificate Features
- **PDF Generation**: High-quality PDF certificates
- **Digital Signatures**: Authentic digital signatures
- **Verification System**: Certificate authenticity verification
- **Bulk Generation**: Mass certificate creation
- **Custom Templates**: Customizable certificate designs

## 8.8 Notification System

### Email Notifications
- **Registration Confirmations**: Team and player registration
- **Payment Confirmations**: Payment success/failure notifications
- **Match Reminders**: Upcoming match notifications
- **Tournament Updates**: Tournament status changes
- **Certificate Notifications**: Certificate generation alerts

### Notification Types
```php
// Email notification examples
class TeamRegistrationNotification extends Notification
{
    public function toMail($notifiable)
    {
        return (new MailMessage)
            ->subject('Team Registration Confirmation')
            ->greeting('Hello ' . $notifiable->name)
            ->line('Your team has been successfully registered.')
            ->action('View Tournament', $this->tournamentUrl)
            ->line('Thank you for participating!');
    }
}
```

### Notification Channels
- **Email**: Primary notification channel
- **SMS**: Future SMS integration
- **In-App**: System notifications
- **Push**: Mobile push notifications (future)

---

## Feature Integration

### Complete Tournament Flow
1. **Tournament Creation**: Admin creates tournament
2. **Team Registration**: Teams register with players
3. **Approval Process**: Admin approves teams
4. **Payment Processing**: Teams pay entry fees
5. **Bracket Generation**: Automatic bracket creation
6. **Match Scheduling**: Match schedule generation
7. **Match Execution**: Live match management
8. **Result Entry**: Score and result entry
9. **Certificate Generation**: Automatic certificate creation
10. **Tournament Completion**: Final results and awards

### Data Flow
```
Tournament → Teams → Players → Matches → Results → Certificates
     ↓         ↓        ↓         ↓         ↓          ↓
  Admin    Payment   OTP      Bracket   Statistics  Awards
  Panel    System   System    System     System     System
```

---

## Next Steps

- [Advanced Features](09_Advanced_Features.md) - Advanced system features
- [Business Logic](10_Business_Logic.md) - Service layer implementation
- [User Guide](17_User_Guide.md) - User documentation
- [API Documentation](05_API_Documentation.md) - API usage
