<?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 "HTML Output Debug - outgoing_calls.php için\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 Query Result (BEFORE performance algorithm):\n";
echo "===================================================\n";
foreach($userStats as $index => $stat) {
    echo "Index: {$index}, ID: {$stat['id']}, Name: {$stat['full_name']}, Total: {$stat['total_calls']}\n";
}

// Performans skorunu hesapla - EXACT same code as in outgoing_calls.php
if (!empty($userStats)) {
    $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');
    
    $maxAnswered = !empty($answeredValues) ? max($answeredValues) : 1;
    $maxTalkSeconds = !empty($talkSecondsValues) ? max($talkSecondsValues) : 1;
    $maxAnswerRate = !empty($answerRateValues) ? max($answerRateValues) : 1;
    $maxDailyAvg = !empty($dailyAvgValues) ? max($dailyAvgValues) : 1;
    
    foreach ($userStats as &$user) {
        $totalAnswered = $user['total_answered'] ?? 0;
        $totalTalkSeconds = $user['total_talk_seconds'] ?? 0;
        $avgAnswerRate = $user['avg_answer_rate'] ?? 0;
        $dailyAvgCalls = $user['daily_avg_calls'] ?? 0;
        
        $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;
        
        $user['performance_score'] = 
            ($answeredScore * 0.40) +
            ($talkTimeScore * 0.30) +
            ($answerRateScore * 0.20) +
            ($dailyAvgScore * 0.10);
            
        $user['performance_score'] = round($user['performance_score'], 1);
        
        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';
        }
    }
    
    usort($userStats, function($a, $b) {
        $scoreA = $a['performance_score'] ?? 0;
        $scoreB = $b['performance_score'] ?? 0;
        return $scoreB <=> $scoreA;
    });
}

echo "\n2. AFTER Performance Calculation and Sorting:\n";
echo "==============================================\n";
foreach($userStats as $index => $stat) {
    echo "Index: {$index}, ID: {$stat['id']}, Name: {$stat['full_name']}, Score: {$stat['performance_score']}\n";
}

echo "\n3. HTML Table Simulation (what outgoing_calls.php should show):\n";
echo "===============================================================\n";

foreach ($userStats as $index => $stat) {
    $answerRate = $stat['avg_answer_rate'] ?? 0;
    $ratingClass = $answerRate >= 90 ? 'excellent' : ($answerRate >= 75 ? 'good' : ($answerRate >= 60 ? 'average' : 'poor'));
    
    echo "ROW " . ($index + 1) . ":\n";
    echo "  Sıra: " . ($index + 1) . "\n";
    echo "  Personel: " . htmlspecialchars($stat['full_name']) . "\n";
    echo "  Dahili: " . htmlspecialchars($stat['extension'] ?? '-') . "\n";
    echo "  Performans: " . ($stat['performance_score'] ?? 0) . " puan (" . ($stat['performance_category'] ?? 'Hesaplanmadı') . ")\n";
    echo "  Toplam Arama: " . number_format($stat['total_calls'] ?? 0) . "\n";
    echo "  Cevaplanan: " . number_format($stat['total_answered'] ?? 0) . "\n";
    echo "  Cevaplanmayan: " . number_format($stat['total_unanswered'] ?? 0) . "\n";
    echo "  Cevaplama %: " . number_format($answerRate, 1) . "\n";
    echo "  Toplam Konuşma: " . ($stat['total_talk_time'] ?? '00:00:00') . "\n";
    echo "  Ort. Konuşma: " . ($stat['avg_call_duration'] ?? '00:00:00') . "\n";
    echo "  Günlük Ort.: " . number_format($stat['daily_avg_calls'] ?? 0) . " arama/gün\n";
    echo "  onclick=\"showUserDetail(" . $stat['id'] . ")\"\n";
    echo "\n";
}

echo "4. Array integrity check:\n";
echo "=========================\n";
$userIds = array_column($userStats, 'id');
$uniqueIds = array_unique($userIds);
echo "Total users: " . count($userStats) . "\n";
echo "Unique user IDs: " . count($uniqueIds) . "\n";
echo "User IDs: " . implode(', ', $userIds) . "\n";

if (count($userIds) !== count($uniqueIds)) {
    echo "⚠️ DUPLICATE USER IDs DETECTED!\n";
} else {
    echo "✅ No duplicate user IDs\n";
}

echo "\n5. Memory check:\n";
echo "================\n";
echo "Memory usage: " . memory_get_usage(true) . " bytes\n";
echo "Peak memory: " . memory_get_peak_usage(true) . " bytes\n";
?>
