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

$db = new Database();

$startDate = date('Y-m-d', strtotime('monday this week'));
$endDate = date('Y-m-d');

echo "Performans algoritması debug - {$startDate} ile {$endDate} arası\n";
echo "================================================================\n\n";

// Aynı sorguyu çalıştır
$userStats = $db->fetchAll("
    SELECT
        u.id,
        u.username,
        u.full_name,
        u.extension,
        COUNT(oc.id) as record_count,
        SUM(oc.call_count) as total_calls,
        SUM(oc.answered_count) as total_answered,
        SUM(oc.unanswered_count) as total_unanswered,
        ROUND(AVG(oc.answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(oc.total_duration))) as total_talk_time,
        SUM(TIME_TO_SEC(oc.total_duration)) as total_talk_seconds,
        SEC_TO_TIME(FLOOR(AVG(TIME_TO_SEC(oc.avg_duration)))) as avg_call_duration,
        ROUND(SUM(oc.call_count) / COUNT(oc.id), 0) as daily_avg_calls,
        MAX(oc.call_date) as last_record_date,
        MIN(oc.call_date) as first_record_date
    FROM users u
    INNER JOIN outgoing_calls oc ON u.id = oc.user_id
    WHERE u.is_active = 1
        AND oc.call_date BETWEEN ? AND ?
    GROUP BY u.id, u.username, u.full_name, u.extension
    ORDER BY SUM(oc.call_count) DESC
", [$startDate, $endDate]);

echo "1. SQL sorgusu sonucu (performans hesaplamadan ÖNCE):\n";
echo "=====================================================\n";
foreach($userStats as $index => $stat) {
    echo "Index: {$index}, ID: {$stat['id']}, Name: {$stat['full_name']}, Extension: {$stat['extension']}, Total Calls: {$stat['total_calls']}\n";
}

echo "\n2. Performans skoru hesaplama başlıyor...\n";
echo "==========================================\n";

// Performans Skoru Algoritması ile Sıralama
if (!empty($userStats)) {
    // Normalize etmek için maksimum değerleri bul
    $answeredValues = array_column($userStats, 'total_answered');
    $talkSecondsValues = array_column($userStats, 'total_talk_seconds');
    $answerRateValues = array_column($userStats, 'avg_answer_rate');
    $dailyAvgValues = array_column($userStats, 'daily_avg_calls');
    
    echo "Answered Values: " . implode(', ', $answeredValues) . "\n";
    echo "Talk Seconds Values: " . implode(', ', $talkSecondsValues) . "\n";
    echo "Answer Rate Values: " . implode(', ', $answerRateValues) . "\n";
    echo "Daily Avg Values: " . implode(', ', $dailyAvgValues) . "\n\n";
    
    // Boş değerleri filtrele ve maksimumları bul
    $maxAnswered = !empty($answeredValues) ? max($answeredValues) : 1;
    $maxTalkSeconds = !empty($talkSecondsValues) ? max($talkSecondsValues) : 1;
    $maxAnswerRate = !empty($answerRateValues) ? max($answerRateValues) : 1;
    $maxDailyAvg = !empty($dailyAvgValues) ? max($dailyAvgValues) : 1;
    
    echo "Max Values - Answered: {$maxAnswered}, TalkSeconds: {$maxTalkSeconds}, AnswerRate: {$maxAnswerRate}, DailyAvg: {$maxDailyAvg}\n\n";
    
    // Her personel için performans skoru hesapla
    foreach ($userStats as $index => &$user) {
        echo "Processing user {$index}: {$user['full_name']}\n";
        
        // Güvenli değer alma (null kontrolü)
        $totalAnswered = $user['total_answered'] ?? 0;
        $totalTalkSeconds = $user['total_talk_seconds'] ?? 0;
        $avgAnswerRate = $user['avg_answer_rate'] ?? 0;
        $dailyAvgCalls = $user['daily_avg_calls'] ?? 0;
        
        echo "  Raw values - Answered: {$totalAnswered}, TalkSeconds: {$totalTalkSeconds}, AnswerRate: {$avgAnswerRate}, DailyAvg: {$dailyAvgCalls}\n";
        
        // Normalize edilmiş skorlar (0-100 arası)
        $answeredScore = $maxAnswered > 0 ? ($totalAnswered / $maxAnswered) * 100 : 0;
        $talkTimeScore = $maxTalkSeconds > 0 ? ($totalTalkSeconds / $maxTalkSeconds) * 100 : 0;
        $answerRateScore = $maxAnswerRate > 0 ? ($avgAnswerRate / $maxAnswerRate) * 100 : 0;
        $dailyAvgScore = $maxDailyAvg > 0 ? ($dailyAvgCalls / $maxDailyAvg) * 100 : 0;
        
        echo "  Normalized scores - Answered: {$answeredScore}, TalkTime: {$talkTimeScore}, AnswerRate: {$answerRateScore}, DailyAvg: {$dailyAvgScore}\n";
        
        // Ağırlıklı toplam performans skoru
        $user['performance_score'] = 
            ($answeredScore * 0.40) +     // Cevaplanan arama sayısı %40
            ($talkTimeScore * 0.30) +     // Toplam konuşma süresi %30
            ($answerRateScore * 0.20) +   // Cevaplama oranı %20
            ($dailyAvgScore * 0.10);      // Günlük ortalama %10
            
        $user['performance_score'] = round($user['performance_score'], 1);
        
        echo "  Final performance score: {$user['performance_score']}\n";
        
        // Performans kategorisi belirle
        if ($user['performance_score'] >= 85) {
            $user['performance_category'] = 'Mükemmel';
            $user['performance_class'] = 'excellent';
        } elseif ($user['performance_score'] >= 70) {
            $user['performance_category'] = 'Çok İyi';
            $user['performance_class'] = 'good';
        } elseif ($user['performance_score'] >= 55) {
            $user['performance_category'] = 'İyi';
            $user['performance_class'] = 'average';
        } else {
            $user['performance_category'] = 'Gelişmeli';
            $user['performance_class'] = 'poor';
        }
        
        echo "  Category: {$user['performance_category']}\n\n";
    }
    
    echo "3. Performans hesaplama sonrası (sıralamadan ÖNCE):\n";
    echo "===================================================\n";
    foreach($userStats as $index => $stat) {
        echo "Index: {$index}, ID: {$stat['id']}, Name: {$stat['full_name']}, Score: " . ($stat['performance_score'] ?? 'N/A') . "\n";
    }
    
    // Performans skoruna göre sırala (yüksekten düşüğe)
    usort($userStats, function($a, $b) {
        $scoreA = $a['performance_score'] ?? 0;
        $scoreB = $b['performance_score'] ?? 0;
        return $scoreB <=> $scoreA;
    });
    
    echo "\n4. Final sonuç (sıralama sonrası):\n";
    echo "==================================\n";
    foreach($userStats as $index => $stat) {
        echo "Index: {$index}, ID: {$stat['id']}, Name: {$stat['full_name']}, Score: " . ($stat['performance_score'] ?? 'N/A') . "\n";
    }
}

echo "\n5. Array size kontrolü:\n";
echo "========================\n";
echo "userStats array size: " . count($userStats) . "\n";

// Unique ID kontrolü
$userIds = array_column($userStats, 'id');
$uniqueIds = array_unique($userIds);
echo "Unique IDs count: " . count($uniqueIds) . "\n";
echo "User IDs: " . implode(', ', $userIds) . "\n";
echo "Unique IDs: " . implode(', ', $uniqueIds) . "\n";

if(count($userIds) !== count($uniqueIds)) {
    echo "⚠️ PROBLEM: Duplicate user IDs found!\n";
    $duplicates = array_diff_assoc($userIds, $uniqueIds);
    echo "Duplicates: " . implode(', ', $duplicates) . "\n";
}
?>
