<?php
require_once 'config/config.php';
require_once 'includes/scoring_functions.php';

$database = new Database();
$db = $database->getConnection();

// Check if total_score column exists
$stmt = $db->query("SHOW COLUMNS FROM job_applications LIKE 'total_score'");
if (!$stmt->fetch()) {
    die("Error: total_score column doesn't exist in job_applications table. Please run the survey scoring system setup first.");
}

// Find applications without scores (total_score = 0 or NULL)
$stmt = $db->prepare("
    SELECT ja.id, ja.job_id, ja.candidate_id, ja.total_score, j.title, 
           CONCAT(c.first_name, ' ', c.last_name) as candidate_name
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN candidates c ON ja.candidate_id = c.id
    WHERE (ja.total_score IS NULL OR ja.total_score = 0)
    ORDER BY ja.applied_at DESC
");
$stmt->execute();
$applications_without_scores = $stmt->fetchAll();

echo "<h2>Dummy Survey Score Generator</h2>";
echo "<p>Found " . count($applications_without_scores) . " applications without survey scores.</p>";

if (empty($applications_without_scores)) {
    echo "<p>No applications need dummy scores. All applications already have scores assigned.</p>";
    exit;
}

// Score distribution patterns for realistic variation
$score_patterns = [
    // Excellent performers (15%)
    ['min' => 85, 'max' => 95, 'weight' => 15],
    // Good performers (25%)  
    ['min' => 70, 'max' => 84, 'weight' => 25],
    // Average performers (35%)
    ['min' => 50, 'max' => 69, 'weight' => 35],
    // Below average (20%)
    ['min' => 30, 'max' => 49, 'weight' => 20],
    // Poor performers (5%)
    ['min' => 10, 'max' => 29, 'weight' => 5]
];

// Function to generate weighted random score
function generateWeightedScore($patterns) {
    $total_weight = array_sum(array_column($patterns, 'weight'));
    $random = rand(1, $total_weight);
    
    $current_weight = 0;
    foreach ($patterns as $pattern) {
        $current_weight += $pattern['weight'];
        if ($random <= $current_weight) {
            return rand($pattern['min'], $pattern['max']) + (rand(0, 99) / 100); // Add decimal precision
        }
    }
    
    // Fallback
    return rand(40, 75) + (rand(0, 99) / 100);
}

// Additional score variations based on job characteristics
function adjustScoreByJob($base_score, $job_title) {
    $title_lower = strtolower($job_title);
    
    // Senior positions tend to have higher standards (slightly lower average scores)
    if (strpos($title_lower, 'senior') !== false || strpos($title_lower, 'manager') !== false || strpos($title_lower, 'lead') !== false) {
        $base_score *= 0.9; // 10% reduction for senior roles
    }
    
    // Entry level positions might have more variation
    if (strpos($title_lower, 'junior') !== false || strpos($title_lower, 'intern') !== false || strpos($title_lower, 'graduate') !== false) {
        $base_score += rand(-10, 15); // More variation for entry level
    }
    
    // Technical roles might have more precise scoring
    if (strpos($title_lower, 'developer') !== false || strpos($title_lower, 'engineer') !== false || strpos($title_lower, 'analyst') !== false) {
        // Technical roles: more likely to have clear pass/fail criteria
        if ($base_score > 60) {
            $base_score += rand(0, 10); // Boost good technical candidates
        }
    }
    
    // Ensure score stays within bounds
    return max(5, min(95, $base_score));
}

$updated_count = 0;

echo "<div style='max-height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 10px; margin: 10px 0;'>";
echo "<h3>Generating Scores...</h3>";

foreach ($applications_without_scores as $app) {
    // Generate base score using weighted distribution
    $base_score = generateWeightedScore($score_patterns);
    
    // Adjust based on job characteristics
    $final_score = adjustScoreByJob($base_score, $app['title']);
    
    // Round to 2 decimal places
    $final_score = round($final_score, 2);
    
    // Update the application
    $update_stmt = $db->prepare("UPDATE job_applications SET total_score = ? WHERE id = ?");
    $success = $update_stmt->execute([$final_score, $app['id']]);
    
    if ($success) {
        $updated_count++;
        $score_category = getScoreCategory($final_score);
        echo "<div style='margin: 5px 0; padding: 5px; background: #f8f9fa;'>";
        echo "<strong>Application #{$app['id']}</strong> - {$app['candidate_name']} → {$app['title']}<br>";
        echo "Score: <span style='color: " . ($score_category['class'] == 'success' ? 'green' : ($score_category['class'] == 'danger' ? 'red' : 'orange')) . ";'>";
        echo "<strong>{$final_score}%</strong> ({$score_category['category']})</span>";
        echo "</div>";
    } else {
        echo "<div style='color: red;'>Failed to update Application #{$app['id']}</div>";
    }
}

echo "</div>";

echo "<h3>Summary</h3>";
echo "<p><strong>Successfully updated {$updated_count} applications</strong> with dummy survey scores.</p>";

if ($updated_count > 0) {
    // Show score distribution
    $stmt = $db->prepare("
        SELECT 
            CASE 
                WHEN total_score >= 85 THEN 'Excellent (85-95%)'
                WHEN total_score >= 70 THEN 'Good (70-84%)'
                WHEN total_score >= 50 THEN 'Average (50-69%)'
                WHEN total_score >= 30 THEN 'Below Average (30-49%)'
                ELSE 'Poor (10-29%)'
            END as score_range,
            COUNT(*) as count,
            ROUND(AVG(total_score), 2) as avg_score
        FROM job_applications 
        WHERE total_score > 0
        GROUP BY score_range
        ORDER BY avg_score DESC
    ");
    $stmt->execute();
    $distribution = $stmt->fetchAll();
    
    echo "<h4>Current Score Distribution</h4>";
    echo "<table border='1' cellpadding='10' cellspacing='0' style='border-collapse: collapse; width: 100%;'>";
    echo "<tr style='background: #f8f9fa;'><th>Score Range</th><th>Count</th><th>Average Score</th></tr>";
    
    foreach ($distribution as $dist) {
        echo "<tr>";
        echo "<td>{$dist['score_range']}</td>";
        echo "<td>{$dist['count']}</td>";
        echo "<td>{$dist['avg_score']}%</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<p style='margin-top: 20px;'><em>Note: These are dummy scores for demonstration purposes. In a real system, scores would be based on actual candidate survey responses.</em></p>";
}

echo "<p><a href='company/applications.php'>← Back to Applications</a></p>";
?>