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

// Copiar funciones necesarias de generate-project.php sin ejecutar el código principal
function csvToJson($csvFile) {
    $rows = [];
    $headers = [];
    
    if (!file_exists($csvFile)) {
        throw new Exception("El archivo CSV no existe");
    }
    
    if (filesize($csvFile) == 0) {
        throw new Exception("El archivo CSV está vacío");
    }
    
    if (($handle = fopen($csvFile, 'r')) === false) {
        throw new Exception("No se pudo abrir el archivo CSV");
    }
    
    $lineNumber = 0;
    $dataLines = 0;
    $headerLineNumber = 0;
    
    while (($data = fgetcsv($handle, 10000, ',')) !== false) {
        $lineNumber++;
        
        if (empty($data) || (count($data) == 1 && trim($data[0]) == '')) {
            continue;
        }
        
        $firstCell = isset($data[0]) ? trim($data[0]) : '';
        if ($firstCell == 'All races' || strpos($firstCell, 'All races') !== false) {
            continue;
        }
        
        if (empty($headers)) {
            $headers = array_map('trim', $data);
            $headerLineNumber = $lineNumber;
            
            if (empty($headers) || count(array_filter($headers)) == 0) {
                fclose($handle);
                throw new Exception("El CSV no contiene encabezados válidos");
            }
            
            $hasPos = in_array('Pos', $headers);
            $hasGender = in_array('Gender', $headers);
            $hasAthlete = in_array('Athlete', $headers) || in_array('Name', $headers);
            $hasBib = in_array('Bib', $headers) || in_array('Bib#', $headers);
            $hasFinish = in_array('Chip Time', $headers) || in_array('FinishTime', $headers);
            
            $missingFields = [];
            if (!$hasPos) $missingFields[] = 'Pos';
            if (!$hasGender) $missingFields[] = 'Gender';
            if (!$hasAthlete) $missingFields[] = 'Athlete o Name';
            if (!$hasBib) $missingFields[] = 'Bib o Bib#';
            if (!$hasFinish) $missingFields[] = 'Chip Time o FinishTime';
            
            if (!empty($missingFields)) {
                fclose($handle);
                throw new Exception("El CSV no contiene los campos requeridos: " . implode(', ', $missingFields));
            }
            
            continue;
        }
        
        $row = [];
        $hasData = false;
        
        foreach ($headers as $index => $header) {
            if (!empty($header)) {
                $value = isset($data[$index]) ? trim($data[$index]) : '';
                
                if ($header === 'Pos') {
                    if (is_numeric($value)) {
                        $row[$header] = (int)$value;
                        $hasData = true;
                    } else {
                        continue 2;
                    }
                } elseif (($header === 'Bib' || $header === 'Bib#') && is_numeric($value)) {
                    $row[$header] = (int)$value;
                } else {
                    $row[$header] = $value;
                }
            }
        }
        
        if ($hasData && isset($row['Pos'])) {
            $rows[] = $row;
            $dataLines++;
        }
    }
    
    fclose($handle);
    
    if (empty($rows)) {
        throw new Exception("El CSV no contiene filas de datos válidas");
    }
    
    return $rows;
}

function addUniqueIdsToRunners($runners) {
    if (!is_array($runners)) {
        return $runners;
    }
    
    $processedRunners = [];
    
    foreach ($runners as $runner) {
        if (!isset($runner['UniqueId']) || empty($runner['UniqueId'])) {
            $uniqueString = '';
            
            if (isset($runner['Athlete'])) {
                $uniqueString .= $runner['Athlete'];
            } elseif (isset($runner['name'])) {
                $uniqueString .= $runner['name'];
            }
            
            if (isset($runner['Bib'])) {
                $uniqueString .= '-' . $runner['Bib'];
            } elseif (isset($runner['bib'])) {
                $uniqueString .= '-' . $runner['bib'];
            }
            
            if (isset($runner['Race'])) {
                $uniqueString .= '-' . $runner['Race'];
            } elseif (isset($runner['distance'])) {
                $uniqueString .= '-' . $runner['distance'];
            }
            
            if (isset($runner['Category'])) {
                $uniqueString .= '-' . $runner['Category'];
            } elseif (isset($runner['category'])) {
                $uniqueString .= '-' . $runner['category'];
            }
            
            if (!empty($uniqueString)) {
                $runner['UniqueId'] = strtoupper(substr(md5($uniqueString . microtime(true)), 0, 9));
            } else {
                $runner['UniqueId'] = strtoupper(substr(bin2hex(random_bytes(5)), 0, 9));
            }
        }
        
        $normalizedRunner = normalizeRunnerData($runner);
        $processedRunners[] = $normalizedRunner;
    }
    
    return $processedRunners;
}

function normalizeRunnerData($runner) {
    $normalized = [];
    
    if (isset($runner['UniqueId'])) {
        $normalized['UniqueId'] = $runner['UniqueId'];
    }
    
    if (isset($runner['Pos'])) {
        $normalized['Pos'] = is_numeric($runner['Pos']) ? (int)$runner['Pos'] : 0;
    }
    
    $normalized['Athlete'] = $runner['Athlete'] ?? $runner['name'] ?? '';
    $normalized['Bib'] = $runner['Bib#'] ?? $runner['Bib'] ?? $runner['bib'] ?? $runner['NumeroCorredor'] ?? '';
    $normalized['Category'] = $runner['Category'] ?? $runner['category'] ?? $runner['Class'] ?? '';
    $normalized['Race'] = $runner['Race'] ?? $runner['distance'] ?? '';
    $normalized['Gender'] = $runner['Gender'] ?? $runner['gender'] ?? '';
    
    $parciales = [];
    foreach ($runner as $key => $value) {
        if (preg_match('/^(\d+(?:\.\d+)?)\s*km$/i', $key)) {
            $parciales[$key] = normalizeTimeString($value);
        } elseif (preg_match('/^(Parcial\s+\d+|MP\d+)$/i', $key)) {
            $parciales[$key] = normalizeTimeString($value);
        }
    }
    
    uksort($parciales, function($a, $b) {
        $distA = 0;
        $distB = 0;
        if (preg_match('/(\d+(?:\.\d+)?)/', $a, $matchA)) {
            $distA = floatval($matchA[1]);
        }
        if (preg_match('/(\d+(?:\.\d+)?)/', $b, $matchB)) {
            $distB = floatval($matchB[1]);
        }
        return $distA <=> $distB;
    });
    
    foreach ($parciales as $key => $value) {
        $normalized[$key] = $value;
    }
    
    if (isset($runner['Chip Time'])) {
        $normalized['FinishTime'] = normalizeTimeString($runner['Chip Time']);
    } elseif (isset($runner['FinishTime'])) {
        $normalized['FinishTime'] = normalizeTimeString($runner['FinishTime']);
    } elseif (isset($runner['finishTime'])) {
        if (is_array($runner['finishTime']) && isset($runner['finishTime']['time'])) {
            $normalized['FinishTime'] = $runner['finishTime']['time'];
        } else {
            $normalized['FinishTime'] = normalizeTimeString($runner['finishTime']);
        }
    }
    
    if (isset($runner['Gun Time'])) {
        $normalized['GunTime'] = normalizeTimeString($runner['Gun Time']);
    } elseif (isset($runner['GunTime'])) {
        $normalized['GunTime'] = normalizeTimeString($runner['GunTime']);
    } elseif (isset($runner['gunTime'])) {
        if (is_array($runner['gunTime']) && isset($runner['gunTime']['time'])) {
            $normalized['GunTime'] = $runner['gunTime']['time'];
        } else {
            $normalized['GunTime'] = normalizeTimeString($runner['gunTime']);
        }
    }
    
    if (!isset($normalized['GunTime']) && isset($normalized['FinishTime'])) {
        $normalized['GunTime'] = $normalized['FinishTime'];
    }
    
    if (!isset($normalized['FinishTime']) && isset($normalized['GunTime'])) {
        $normalized['FinishTime'] = $normalized['GunTime'];
    }
    
    return $normalized;
}

function normalizeTimeString($timeValue) {
    if (is_array($timeValue)) {
        if (isset($timeValue['time'])) {
            $timeValue = $timeValue['time'];
        } else {
            $timeValue = reset($timeValue);
        }
    }
    
    if (!is_string($timeValue)) {
        return '';
    }
    
    $timeValue = trim($timeValue);
    
    if (empty($timeValue)) {
        return '';
    }
    
    if (preg_match('/^(\d{1,2}):(\d{2}):(\d{2})$/', $timeValue, $matches)) {
        $hours = str_pad($matches[1], 2, '0', STR_PAD_LEFT);
        $minutes = $matches[2];
        $seconds = $matches[3];
        return "{$hours}:{$minutes}:{$seconds}";
    } elseif (preg_match('/^(\d{1,2}):(\d{2})$/', $timeValue, $matches)) {
        $minutes = str_pad($matches[1], 2, '0', STR_PAD_LEFT);
        $seconds = $matches[2];
        return "00:{$minutes}:{$seconds}";
    }
    
    return '';
}

$response = ['success' => false, 'message' => '', 'updates' => []];

try {
    if (!isset($_POST['slug']) || empty($_POST['slug'])) {
        throw new Exception('El slug del proyecto es requerido');
    }
    
    $slug = trim($_POST['slug']);
    
    if (!preg_match('/^[a-z0-9-]+$/', $slug)) {
        throw new Exception('Formato de slug inválido');
    }
    
    $baseDir = dirname(__DIR__);
    $projectsDir = dirname($baseDir) . '/crono-projects';
    $projectPath = $projectsDir . '/' . $slug;
    
    if (!file_exists($projectPath)) {
        throw new Exception('El proyecto no existe');
    }
    
    $metadataPath = $projectPath . '/project-metadata.json';
    if (!file_exists($metadataPath)) {
        throw new Exception('No se encontró la metadata del proyecto');
    }
    
    $metadata = json_decode(file_get_contents($metadataPath), true);
    if ($metadata === null) {
        throw new Exception('Error al leer la metadata del proyecto');
    }
    
    $raceName = $metadata['name'];
    $distances = $metadata['distances'];
    $updatesCount = 0;
    
    // Actualizar imagen
    if (isset($_FILES['coverImage']) && $_FILES['coverImage']['error'] === UPLOAD_ERR_OK) {
        $uploadFile = $_FILES['coverImage'];
        $ext = strtolower(pathinfo($uploadFile['name'], PATHINFO_EXTENSION));
        $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        
        if (!in_array($ext, $allowedExts)) {
            throw new Exception('Formato de imagen no válido');
        }
        
        $imagesDir = $projectPath . '/assets/images';
        foreach ($allowedExts as $oldExt) {
            $oldImage = $imagesDir . '/cover-image.' . $oldExt;
            if (file_exists($oldImage)) {
                unlink($oldImage);
            }
        }
        
        $coverImageName = 'cover-image.' . $ext;
        $coverImagePath = $imagesDir . '/' . $coverImageName;
        
        if (move_uploaded_file($uploadFile['tmp_name'], $coverImagePath)) {
            $relativePath = 'assets/images/' . $coverImageName;
            updateCoverImageInProject($projectPath, $relativePath, $raceName);
            $response['updates'][] = 'Imagen de portada actualizada';
            $updatesCount++;
        }
    }
    
    // Actualizar CSVs
    $dataDir = $projectPath . '/data';
    $backupDir = $dataDir . '/backups';
    
    if (!file_exists($backupDir)) {
        mkdir($backupDir, 0755, true);
    }
    
    $updatedDistances = [];
    
    foreach ($distances as $dist) {
        if (isset($_FILES['dataFiles']) && isset($_FILES['dataFiles']['tmp_name'][$dist])) {
            $tmpName = $_FILES['dataFiles']['tmp_name'][$dist];
            $fileName = $_FILES['dataFiles']['name'][$dist];
            $fileError = $_FILES['dataFiles']['error'][$dist];
            
            if ($fileError === UPLOAD_ERR_NO_FILE || empty($tmpName)) {
                continue;
            }
            
            if ($fileError === UPLOAD_ERR_OK) {
                $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
                
                if ($ext !== 'csv') {
                    throw new Exception("El archivo para {$dist} debe ser CSV");
                }
                
                try {
                    $targetFile = $dataDir . '/data_' . $dist . '.json';
                    if (file_exists($targetFile)) {
                        $backupName = 'data_' . $dist . '_' . date('Y-m-d_H-i-s') . '.json';
                        copy($targetFile, $backupDir . '/' . $backupName);
                    }
                    
                    $jsonData = csvToJson($tmpName);
                    
                    if (empty($jsonData)) {
                        throw new Exception("No se pudieron extraer datos del CSV");
                    }
                    
                    $processedData = addUniqueIdsToRunners($jsonData);
                    $jsonOutput = json_encode($processedData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                    
                    if ($jsonOutput === false) {
                        throw new Exception("Error al codificar JSON");
                    }
                    
                    if (file_put_contents($targetFile, $jsonOutput) === false) {
                        throw new Exception("No se pudo guardar el archivo");
                    }
                    
                    $updatedDistances[] = strtoupper($dist);
                    $updatesCount++;
                    
                } catch (Exception $e) {
                    throw new Exception("Error procesando CSV para {$dist}: " . $e->getMessage());
                }
            }
        }
    }
    
    if (!empty($updatedDistances)) {
        $response['updates'][] = 'Datos actualizados: ' . implode(', ', $updatedDistances);
    }
    
    // Actualizar configuración de tiempos en config.js
    $configUpdated = false;
    $configPath = $projectPath . '/config.js';
    
    if (file_exists($configPath)) {
        $configContent = file_get_contents($configPath);
        $originalContent = $configContent;
        
        // Actualizar baseStartTime si se proporcionó
        if (isset($_POST['baseStartTime']) && !empty($_POST['baseStartTime'])) {
            $baseStartTime = trim($_POST['baseStartTime']);
            
            // Validar formato HH:MM:SS
            if (preg_match('/^([0-9]|[0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/', $baseStartTime)) {
                $configContent = preg_replace(
                    '/baseStartTime:\s*["\']([^"\']+)["\']/',
                    'baseStartTime: "' . $baseStartTime . '"',
                    $configContent
                );
            }
        }
        
        // Actualizar startTimes si se proporcionaron
        if (isset($_POST['startTimes']) && is_array($_POST['startTimes'])) {
            $startTimesObj = '';
            
            foreach ($_POST['startTimes'] as $dist => $time) {
                $time = trim($time);
                
                // Validar formato HH:MM:SS
                if (preg_match('/^([0-9]|[0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]$/', $time)) {
                    $startTimesObj .= "        '{$dist}': \"{$time}\",\n";
                }
            }
            
            if (!empty($startTimesObj)) {
                $configContent = preg_replace(
                    '/startTimes:\s*\{[^}]*\}/s',
                    "startTimes: {\n{$startTimesObj}    }",
                    $configContent
                );
            }
        }
        
        // Guardar solo si hubo cambios
        if ($configContent !== $originalContent) {
            file_put_contents($configPath, $configContent);
            $response['updates'][] = 'Configuración de tiempos actualizada';
            $updatesCount++;
            $configUpdated = true;
        }
    }
    
    if ($updatesCount === 0) {
        $response['success'] = true;
        $response['message'] = 'No se realizaron cambios';
        echo json_encode($response);
        exit;
    }
    
    $metadata['lastModified'] = date('Y-m-d H:i:s');
    file_put_contents($metadataPath, json_encode($metadata, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    
    $response['success'] = true;
    $response['message'] = implode('. ', $response['updates']);
    
} catch (Exception $e) {
    $response['message'] = $e->getMessage();
}

echo json_encode($response);

function updateCoverImageInProject($projectPath, $coverImage, $raceName) {
    $htmlFiles = [
        $projectPath . '/index.html',
        $projectPath . '/certificado.html',
        $projectPath . '/analisis/index.html',
        $projectPath . '/analisis/analisis.html',
        $projectPath . '/analisis/certificado.html'
    ];
    
    foreach ($htmlFiles as $htmlFile) {
        if (file_exists($htmlFile)) {
            $content = file_get_contents($htmlFile);
            $isAnalisis = strpos($htmlFile, '/analisis/') !== false;
            $imagePath = $isAnalisis ? '../' . $coverImage : $coverImage;
            
            if (strpos($htmlFile, 'certificado.html') !== false) {
                $content = preg_replace(
                    '/<img[^>]+class="event-header-img"[^>]*>/',
                    '<img src="' . $imagePath . '" alt="' . htmlspecialchars($raceName) . '" class="event-header-img">',
                    $content
                );
            } elseif (strpos($htmlFile, 'analisis.html') !== false) {
                $content = preg_replace(
                    '/<img[^>]+class="race-banner-img"[^>]*>/',
                    '<img src="' . $imagePath . '" alt="' . htmlspecialchars($raceName) . '" class="race-banner-img">',
                    $content
                );
            } elseif (strpos($htmlFile, 'index.html') !== false) {
                if ($isAnalisis) {
                    $content = preg_replace(
                        '/<img[^>]+class="header-image"[^>]*>/',
                        '<img src="' . $imagePath . '" alt="' . htmlspecialchars($raceName) . '" class="header-image">',
                        $content
                    );
                } else {
                    $content = preg_replace(
                        '/src="assets\/images\/[^"]*(?:head|cover)[^"]*"/',
                        'src="' . $imagePath . '"',
                        $content
                    );
                }
            }
            
            file_put_contents($htmlFile, $content);
        }
    }
}
?>
