<?php
session_start();

// Check if user is logged in and has admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

require_once '../includes/config.php';

header('Content-Type: application/json');

try {
    $action = $_POST['action'] ?? '';
    $event_id = $_POST['event_id'] ?? '';
    
    if (empty($event_id)) {
        throw new Exception('Event ID is required');
    }
    
    switch ($action) {
        case 'create_series':
            createSeries($pdo, $_POST);
            break;
            
        case 'update_series':
            updateSeries($pdo, $_POST);
            break;
            
        case 'delete_series':
            deleteSeries($pdo, $_POST);
            break;
            
        default:
            throw new Exception('Invalid action');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

function createSeries($pdo, $data) {
    // Validate required fields
    $required = ['series_name', 'start_number', 'end_number', 'series_color', 'event_id'];
    foreach ($required as $field) {
        if (empty($data[$field])) {
            throw new Exception("Field {$field} is required");
        }
    }
    
    // Validate number range
    $start = (int)$data['start_number'];
    $end = (int)$data['end_number'];
    
    if ($start >= $end) {
        throw new Exception('End number must be greater than start number');
    }
    
    // Check for overlapping series in the same event
    $stmt = $pdo->prepare("
        SELECT id, name, start_number, end_number 
        FROM bib_series 
        WHERE event_id = ? 
        AND (
            (start_number <= ? AND end_number >= ?) OR
            (start_number <= ? AND end_number >= ?) OR
            (start_number >= ? AND end_number <= ?)
        )
    ");
    $stmt->execute([$data['event_id'], $start, $start, $end, $end, $start, $end]);
    
    if ($stmt->fetch()) {
        throw new Exception('Number range overlaps with existing series');
    }
    
    // Prepare optional fields
    $missing_numbers = !empty($data['missing_numbers']) ? trim($data['missing_numbers']) : null;
    $additional_numbers = !empty($data['additional_numbers']) ? trim($data['additional_numbers']) : null;
    $description = !empty($data['description']) ? trim($data['description']) : null;
    
    // Validate color format
    if (!preg_match('/^#[a-fA-F0-9]{6}$/', $data['series_color'])) {
        throw new Exception('Invalid color format');
    }
    
    // Insert new series
    $stmt = $pdo->prepare("
        INSERT INTO bib_series (
            event_id, name, start_number, end_number, color, 
            missing_numbers, additional_numbers, description, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    
    $success = $stmt->execute([
        $data['event_id'],
        trim($data['series_name']),
        $start,
        $end,
        $data['series_color'],
        $missing_numbers,
        $additional_numbers,
        $description
    ]);
    
    if (!$success) {
        throw new Exception('Failed to create series');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Series created successfully',
        'series_id' => $pdo->lastInsertId()
    ]);
}

function updateSeries($pdo, $data) {
    // Validate required fields
    $required = ['series_id', 'series_name', 'start_number', 'end_number', 'series_color', 'event_id'];
    foreach ($required as $field) {
        if (empty($data[$field])) {
            throw new Exception("Field {$field} is required");
        }
    }
    
    $series_id = (int)$data['series_id'];
    $start = (int)$data['start_number'];
    $end = (int)$data['end_number'];
    
    if ($start >= $end) {
        throw new Exception('End number must be greater than start number');
    }
    
    // Check if series exists and belongs to the event
    $stmt = $pdo->prepare("SELECT id FROM bib_series WHERE id = ? AND event_id = ?");
    $stmt->execute([$series_id, $data['event_id']]);
    
    if (!$stmt->fetch()) {
        throw new Exception('Series not found or access denied');
    }
    
    // Check for overlapping series (excluding current series)
    $stmt = $pdo->prepare("
        SELECT id, name, start_number, end_number 
        FROM bib_series 
        WHERE event_id = ? AND id != ?
        AND (
            (start_number <= ? AND end_number >= ?) OR
            (start_number <= ? AND end_number >= ?) OR
            (start_number >= ? AND end_number <= ?)
        )
    ");
    $stmt->execute([$data['event_id'], $series_id, $start, $start, $end, $end, $start, $end]);
    
    if ($stmt->fetch()) {
        throw new Exception('Number range overlaps with existing series');
    }
    
    // Check if there are existing BIB assignments that would be affected
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count
        FROM event_participants ep
        WHERE ep.event_id = ? 
        AND ep.bib_number IS NOT NULL 
        AND (ep.bib_number < ? OR ep.bib_number > ?)
        AND EXISTS (
            SELECT 1 FROM bib_series bs 
            WHERE bs.id = ? 
            AND ep.bib_number BETWEEN bs.start_number AND bs.end_number
        )
    ");
    $stmt->execute([$data['event_id'], $start, $end, $series_id]);
    $result = $stmt->fetch();
    
    if ($result['count'] > 0) {
        throw new Exception('Cannot modify range: there are existing BIB assignments outside the new range');
    }
    
    // Prepare optional fields
    $missing_numbers = !empty($data['missing_numbers']) ? trim($data['missing_numbers']) : null;
    $additional_numbers = !empty($data['additional_numbers']) ? trim($data['additional_numbers']) : null;
    $description = !empty($data['description']) ? trim($data['description']) : null;
    
    // Validate color format
    if (!preg_match('/^#[a-fA-F0-9]{6}$/', $data['series_color'])) {
        throw new Exception('Invalid color format');
    }
    
    // Update series
    $stmt = $pdo->prepare("
        UPDATE bib_series SET 
            name = ?, 
            start_number = ?, 
            end_number = ?, 
            color = ?, 
            missing_numbers = ?, 
            additional_numbers = ?, 
            description = ?,
            updated_at = NOW()
        WHERE id = ? AND event_id = ?
    ");
    
    $success = $stmt->execute([
        trim($data['series_name']),
        $start,
        $end,
        $data['series_color'],
        $missing_numbers,
        $additional_numbers,
        $description,
        $series_id,
        $data['event_id']
    ]);
    
    if (!$success) {
        throw new Exception('Failed to update series');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Series updated successfully'
    ]);
}

function deleteSeries($pdo, $data) {
    if (empty($data['series_id']) || empty($data['event_id'])) {
        throw new Exception('Series ID and Event ID are required');
    }
    
    $series_id = (int)$data['series_id'];
    
    // Check if series exists and belongs to the event
    $stmt = $pdo->prepare("SELECT name FROM bib_series WHERE id = ? AND event_id = ?");
    $stmt->execute([$series_id, $data['event_id']]);
    $series = $stmt->fetch();
    
    if (!$series) {
        throw new Exception('Series not found or access denied');
    }
    
    // Check if there are existing BIB assignments
    $stmt = $pdo->prepare("
        SELECT COUNT(*) as count
        FROM event_participants ep
        JOIN bib_series bs ON ep.event_id = bs.event_id
        WHERE bs.id = ? 
        AND ep.bib_number IS NOT NULL 
        AND ep.bib_number BETWEEN bs.start_number AND bs.end_number
    ");
    $stmt->execute([$series_id]);
    $result = $stmt->fetch();
    
    if ($result['count'] > 0) {
        throw new Exception('Cannot delete series: there are existing BIB assignments in this series');
    }
    
    // Delete series
    $stmt = $pdo->prepare("DELETE FROM bib_series WHERE id = ? AND event_id = ?");
    $success = $stmt->execute([$series_id, $data['event_id']]);
    
    if (!$success) {
        throw new Exception('Failed to delete series');
    }
    
    echo json_encode([
        'success' => true,
        'message' => "Series '{$series['name']}' deleted successfully"
    ]);
}
?>
