<?php
// Quick test of the calculation
include '../includes/db.php';

// Test the calculation function directly
$judge_scores = [33, 67, 56, 44, 55, 54];
$scoring_format = [
    'scale_type' => 'numeric',
    'drop_rule' => 'highest_and_lowest',
    'precision_decimal' => 2
];

// Load the function
function calculateRunScoreByFormat($judge_scores, $scoring_format) {
    if ($scoring_format['scale_type'] !== 'numeric') {
        return 'Custom';
    }
    
    if (empty($judge_scores)) {
        return 0;
    }
    
    $working_scores = array_map('floatval', $judge_scores);
    
    // Debug logging
    echo "Original scores: " . implode(',', $working_scores) . "\n";
    echo "Drop rule: " . ($scoring_format['drop_rule'] ?? 'none') . "\n";
    echo "Precision decimal: " . ($scoring_format['precision_decimal'] ?? 'undefined') . "\n";
    
    // Apply drop rule from scoring format
    switch ($scoring_format['drop_rule']) {
        case 'highest':
            if (count($working_scores) > 1) {
                rsort($working_scores);
                array_shift($working_scores); // Remove highest
            }
            break;
        case 'lowest':
            if (count($working_scores) > 1) {
                sort($working_scores);
                array_shift($working_scores); // Remove lowest
            }
            break;
        case 'highest_lowest':
        case 'highest_and_lowest': // Handle "Drop High/Low" rule
            if (count($working_scores) > 2) {
                sort($working_scores);
                array_shift($working_scores); // Remove lowest
                array_pop($working_scores);   // Remove highest
            }
            break;
        case 'none':
        default:
            // No drops
            break;
    }
    
    // Debug logging after drops
    echo "Scores after drops: " . implode(',', $working_scores) . "\n";
    
    // Calculate average and apply precision
    $average = count($working_scores) > 0 ? array_sum($working_scores) / count($working_scores) : 0;
    echo "Raw average: " . $average . "\n";
    
    $result = round($average, $scoring_format['precision_decimal']);
    echo "Final result: " . $result . "\n";
    
    return $result;
}

echo "Testing calculation with scores: " . implode(',', $judge_scores) . "\n";
echo "Expected result: 52.25\n\n";

$result = calculateRunScoreByFormat($judge_scores, $scoring_format);
echo "\nActual result: " . $result . "\n";

// Let's also test the manual calculation
$test_scores = [56, 44, 55, 54];
$manual_average = array_sum($test_scores) / count($test_scores);
echo "Manual calculation: (" . implode(' + ', $test_scores) . ") / " . count($test_scores) . " = " . $manual_average . "\n";
?>
