<?php
include '../includes/auth.php';
include '../includes/db.php';

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

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !isset($data['event_id']) || !isset($data['participants'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request data']);
    exit;
}

$event_id = intval($data['event_id']);
$participants = $data['participants'];

if (!$event_id || empty($participants)) {
    echo json_encode(['success' => false, 'message' => 'Event ID and participants data are required']);
    exit;
}

try {
    $pdo->beginTransaction();
    
    $imported_count = 0;
    $updated_count = 0;
    $error_count = 0;
    $errors = [];
    
    // Get event details
    $event_stmt = $pdo->prepare("SELECT name FROM events WHERE id = ?");
    $event_stmt->execute([$event_id]);
    $event_info = $event_stmt->fetch();
    
    if (!$event_info) {
        throw new Exception('Event not found');
    }
    
    foreach ($participants as $index => $participant_data) {
        try {
            // Validate required fields
            if (empty($participant_data['bib']) || empty($participant_data['first_name']) || 
                empty($participant_data['last_name']) || empty($participant_data['gender'])) {
                $error_count++;
                $errors[] = "Row " . ($index + 1) . ": Missing required fields";
                continue;
            }
            
            // Validate gender
            if (!in_array($participant_data['gender'], ['M', 'F'])) {
                $error_count++;
                $errors[] = "Row " . ($index + 1) . ": Invalid gender (must be M or F)";
                continue;
            }
            
            // Clean and prepare data
            $clean_data = [
                'bib' => trim($participant_data['bib']),
                'first_name' => trim($participant_data['first_name']),
                'last_name' => trim($participant_data['last_name']),
                'gender' => trim($participant_data['gender']),
                'fis_code' => trim($participant_data['fis_code'] ?? ''),
                'licence_code' => trim($participant_data['licence_code'] ?? ''),
                'licence_type' => trim($participant_data['licence_type'] ?? ''),
                'club' => trim($participant_data['club'] ?? ''),
                'country' => trim($participant_data['country'] ?? ''),
                'date_of_birth' => null,
                'category' => trim($participant_data['category'] ?? '')
            ];
            
            // Handle date_of_birth - support year-only input
            if (!empty($participant_data['date_of_birth'])) {
                $dob_input = trim($participant_data['date_of_birth']);
                
                // Check if it's just a year (4 digits)
                if (preg_match('/^\d{4}$/', $dob_input)) {
                    $clean_data['date_of_birth'] = $dob_input . '-01-01';
                } else {
                    // Try to parse as full date
                    $timestamp = strtotime($dob_input);
                    if ($timestamp !== false) {
                        $clean_data['date_of_birth'] = date('Y-m-d', $timestamp);
                    }
                }
            }
            
            // Check for existing participant by BIB
            $existing_stmt = $pdo->prepare("SELECT id FROM participants WHERE bib = ?");
            $existing_stmt->execute([$clean_data['bib']]);
            $existing = $existing_stmt->fetch();
            
            if ($existing) {
                // Update existing participant
                $update_stmt = $pdo->prepare("
                    UPDATE participants SET
                        first_name = ?,
                        last_name = ?,
                        gender = ?,
                        fis_code = ?,
                        licence_code = ?,
                        licence_type = ?,
                        club = ?,
                        country = ?,
                        date_of_birth = ?,
                        category = ?,
                        updated_at = NOW()
                    WHERE id = ?
                ");
                $update_stmt->execute([
                    $clean_data['first_name'],
                    $clean_data['last_name'],
                    $clean_data['gender'],
                    $clean_data['fis_code'] ?: null,
                    $clean_data['licence_code'] ?: null,
                    $clean_data['licence_type'] ?: null,
                    $clean_data['club'] ?: null,
                    $clean_data['country'] ?: null,
                    $clean_data['date_of_birth'],
                    $clean_data['category'] ?: null,
                    $existing['id']
                ]);
                
                $participant_id = $existing['id'];
                $updated_count++;
            } else {
                // Insert new participant
                $insert_stmt = $pdo->prepare("
                    INSERT INTO participants (
                        bib, first_name, last_name, gender, fis_code, licence_code,
                        licence_type, club, country, date_of_birth, category, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
                ");
                $insert_stmt->execute([
                    $clean_data['bib'],
                    $clean_data['first_name'],
                    $clean_data['last_name'],
                    $clean_data['gender'],
                    $clean_data['fis_code'] ?: null,
                    $clean_data['licence_code'] ?: null,
                    $clean_data['licence_type'] ?: null,
                    $clean_data['club'] ?: null,
                    $clean_data['country'] ?: null,
                    $clean_data['date_of_birth'],
                    $clean_data['category'] ?: null
                ]);
                
                $participant_id = $pdo->lastInsertId();
                $imported_count++;
            }
            
            // Track import for the event
            if ($participant_id && $event_id) {
                $tracking_stmt = $pdo->prepare("
                    INSERT INTO participants_event (participant_id, event_id, imported_at)
                    VALUES (?, ?, CURRENT_TIMESTAMP)
                    ON DUPLICATE KEY UPDATE imported_at = CURRENT_TIMESTAMP
                ");
                $tracking_stmt->execute([$participant_id, $event_id]);
            }
            
        } catch (Exception $e) {
            $error_count++;
            $errors[] = "Row " . ($index + 1) . ": " . $e->getMessage();
            continue;
        }
    }
    
    $pdo->commit();
    
    $response = [
        'success' => true,
        'imported' => $imported_count,
        'updated' => $updated_count,
        'errors' => $error_count,
        'event_name' => $event_info['name']
    ];
    
    if (!empty($errors)) {
        $response['error_details'] = array_slice($errors, 0, 10); // Return first 10 errors
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
