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

Auth::requireLogin();

$pageTitle = 'Gelen Aramalar Analizi';
include 'includes/header.php';

$db = new Database();

// Hızlı filtre parametresi
$quickFilter = $_GET['quick_filter'] ?? '';

// Türkçe ay isimleri
$turkishMonths = [
    1 => 'Ocak', 2 => 'Şubat', 3 => 'Mart', 4 => 'Nisan',
    5 => 'Mayıs', 6 => 'Haziran', 7 => 'Temmuz', 8 => 'Ağustos',
    9 => 'Eylül', 10 => 'Ekim', 11 => 'Kasım', 12 => 'Aralık'
];

// Tarih filtresi - Varsayılan Bu Hafta (Pazartesi - Cuma/Bugün)
if ($quickFilter) {
    switch ($quickFilter) {
        case 'this_month':
            $startDate = date('Y-m-01');
            $endDate = date('Y-m-d');
            break;
        case 'last_month':
            $startDate = date('Y-m-01', strtotime('-1 month'));
            $endDate = date('Y-m-t', strtotime('-1 month'));
            break;
        case 'today':
            $startDate = date('Y-m-d');
            $endDate = date('Y-m-d');
            break;
        case 'yesterday':
            $startDate = date('Y-m-d', strtotime('-1 day'));
            $endDate = date('Y-m-d', strtotime('-1 day'));
            break;
        case 'this_week':
            $startDate = date('Y-m-d', strtotime('monday this week'));
            $endDate = date('Y-m-d');
            break;
        // Ay filtreleri (month_0 = bu ay, month_-1 = geçen ay, vs.)
        default:
            if (strpos($quickFilter, 'month_') === 0) {
                $monthOffset = (int)str_replace('month_', '', $quickFilter);
                $startDate = date('Y-m-01', strtotime("$monthOffset months"));
                $endDate = date('Y-m-t', strtotime("$monthOffset months"));
            } else {
                $startDate = date('Y-m-d', strtotime('monday this week'));
                $endDate = date('Y-m-d');
            }
    }
} else {
    // Manuel tarih seçimi veya varsayılan (Bu Hafta)
    if (isset($_GET['start_date']) && isset($_GET['end_date'])) {
        $startDate = $_GET['start_date'];
        $endDate = $_GET['end_date'];
    } else {
        // Varsayılan: Bu Hafta (Pazartesi - Bugün)
        $startDate = date('Y-m-d', strtotime('monday this week'));
        $endDate = date('Y-m-d');
    }
}

$selectedUser = $_GET['user_id'] ?? '';

// Personel listesi
$users = $db->fetchAll("SELECT id, username, full_name, extension FROM users WHERE is_active = 1 ORDER BY full_name");

// Genel istatistikler
$generalStats = $db->fetchOne("
    SELECT
        COUNT(DISTINCT user_id) as total_users,
        COUNT(*) as total_records,
        SUM(call_count) as total_calls,
        SUM(answered_count) as total_answered,
        SUM(unanswered_count) as total_unanswered,
        ROUND(AVG(answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_talk_time,
        SEC_TO_TIME(FLOOR(AVG(TIME_TO_SEC(avg_duration)))) as avg_call_duration
    FROM incoming_calls
    WHERE call_date BETWEEN ? AND ?
    " . ($selectedUser ? "AND user_id = ?" : ""),
    $selectedUser ? [$startDate, $endDate, $selectedUser] : [$startDate, $endDate]
);

// Bu ay, geçen ay ve bir önceki ay istatistikleri
$thisMonth = date('Y-m-01');
$lastMonth = date('Y-m-01', strtotime('-1 month'));
$lastMonthEnd = date('Y-m-t', strtotime('-1 month'));
$twoMonthsAgo = date('Y-m-01', strtotime('-2 months'));
$twoMonthsAgoEnd = date('Y-m-t', strtotime('-2 months'));

$thisMonthStats = $db->fetchOne("
    SELECT
        SUM(call_count) as total_calls,
        SUM(answered_count) as total_answered,
        SUM(unanswered_count) as total_unanswered,
        ROUND(AVG(answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_talk_time
    FROM incoming_calls
    WHERE call_date BETWEEN ? AND ?
", [$thisMonth, date('Y-m-d')]);

$lastMonthStats = $db->fetchOne("
    SELECT
        SUM(call_count) as total_calls,
        SUM(answered_count) as total_answered,
        SUM(unanswered_count) as total_unanswered,
        ROUND(AVG(answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_talk_time
    FROM incoming_calls
    WHERE call_date BETWEEN ? AND ?
", [$lastMonth, $lastMonthEnd]);

$twoMonthsAgoStats = $db->fetchOne("
    SELECT
        SUM(call_count) as total_calls,
        SUM(answered_count) as total_answered,
        SUM(unanswered_count) as total_unanswered,
        ROUND(AVG(answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_talk_time
    FROM incoming_calls
    WHERE call_date BETWEEN ? AND ?
", [$twoMonthsAgo, $twoMonthsAgoEnd]);

// Aylık personel bazlı detaylar (modallar için)
$thisMonthUserStats = $db->fetchAll("
    SELECT
        u.id,
        u.full_name,
        u.extension,
        SUM(ic.call_count) as total_calls,
        SUM(ic.answered_count) as total_answered,
        SUM(ic.unanswered_count) as total_unanswered,
        ROUND(AVG(ic.answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_talk_time
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    ORDER BY total_calls DESC
", [$thisMonth, date('Y-m-d')]);

$lastMonthUserStats = $db->fetchAll("
    SELECT
        u.id,
        u.full_name,
        u.extension,
        SUM(ic.call_count) as total_calls,
        SUM(ic.answered_count) as total_answered,
        SUM(ic.unanswered_count) as total_unanswered,
        ROUND(AVG(ic.answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_talk_time
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    ORDER BY total_calls DESC
", [$lastMonth, $lastMonthEnd]);

$twoMonthsAgoUserStats = $db->fetchAll("
    SELECT
        u.id,
        u.full_name,
        u.extension,
        SUM(ic.call_count) as total_calls,
        SUM(ic.answered_count) as total_answered,
        SUM(ic.unanswered_count) as total_unanswered,
        ROUND(AVG(ic.answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_talk_time
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    ORDER BY total_calls DESC
", [$twoMonthsAgo, $twoMonthsAgoEnd]);

// Kullanıcı bazında detaylı istatistikler (modallar için)
$userDetailedStats = $db->fetchAll("
    SELECT
        u.id,
        u.username,
        u.full_name,
        u.extension,
        SUM(ic.call_count) as total_calls,
        SUM(ic.answered_count) as total_answered,
        SUM(ic.unanswered_count) as total_unanswered,
        ROUND(AVG(ic.answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_talk_time,
        SEC_TO_TIME(
            FLOOR(
                CASE
                    WHEN SUM(ic.answered_count) > 0
                    THEN SUM(TIME_TO_SEC(ic.total_duration)) / SUM(ic.answered_count)
                    ELSE 0
                END
            )
        ) as avg_call_duration
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    ORDER BY total_calls DESC
", [$startDate, $endDate]);

// Personel bazında detaylı istatistikler
$userStats = $db->fetchAll("
    SELECT
        u.id,
        u.username,
        u.full_name,
        u.extension,
        COUNT(ic.id) as record_count,
        SUM(ic.call_count) as total_calls,
        SUM(ic.answered_count) as total_answered,
        SUM(ic.unanswered_count) as total_unanswered,
        ROUND(AVG(ic.answer_percentage), 2) as avg_answer_rate,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_talk_time,
        SUM(TIME_TO_SEC(ic.total_duration)) as total_talk_seconds,
        SEC_TO_TIME(FLOOR(AVG(TIME_TO_SEC(ic.avg_duration)))) as avg_call_duration,
        ROUND(SUM(ic.call_count) / COUNT(ic.id), 0) as daily_avg_calls,
        MAX(ic.call_date) as last_record_date,
        MIN(ic.call_date) as first_record_date
    FROM users u
    LEFT JOIN incoming_calls ic ON u.id = ic.user_id
        AND ic.call_date BETWEEN ? AND ?
    WHERE u.is_active = 1
    " . ($selectedUser ? "AND u.id = ?" : "") . "
    GROUP BY u.id
    HAVING total_calls > 0
    ORDER BY total_calls DESC
", $selectedUser ? [$startDate, $endDate, $selectedUser] : [$startDate, $endDate]);

// Performans Skoru Algoritması ile Sıralama
// Bu algoritma şu faktörleri dikkate alır:
// 1. Cevaplanan Arama Sayısı (40% ağırlık)
// 2. Toplam Konuşma Süresi (30% ağırlık)
// 3. Cevaplama Oranı (20% ağırlık)
// 4. Günlük Ortalama Arama (10% ağırlık)

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');

    // 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;

    // Her personel için performans skoru hesapla
    foreach ($userStats as &$user) {
        // 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;

        // 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;

        // 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);

        // 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';
        }
    }

    unset($user); // Referansı temizle - önemli!

    // 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;
    });

    // Duplicate kayıtları temizle (user_id'ye göre)
    $uniqueUserStats = [];
    $seenIds = [];
    foreach ($userStats as $stat) {
        if (!in_array($stat['id'], $seenIds)) {
            $uniqueUserStats[] = $stat;
            $seenIds[] = $stat['id'];
        }
    }
    $userStats = $uniqueUserStats;
}

// En iyi cevaplama oranları (35/40 formatında)
$topAnswerRate = $db->fetchAll("
    SELECT
        u.full_name,
        u.extension,
        SUM(ic.call_count) as total_calls,
        SUM(ic.answered_count) as total_answered,
        ROUND(AVG(ic.answer_percentage), 2) as avg_answer_rate
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    HAVING total_calls > 0
    ORDER BY avg_answer_rate DESC
    LIMIT 5
", [$startDate, $endDate]);

// En çok cevapsız
$mostUnanswered = $db->fetchAll("
    SELECT
        u.full_name,
        u.extension,
        SUM(ic.unanswered_count) as total_unanswered,
        SUM(ic.call_count) as total_calls
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    HAVING total_unanswered > 0
    ORDER BY total_unanswered DESC
    LIMIT 5
", [$startDate, $endDate]);

// En uzun konuşma süreleri
$mostTalkTime = $db->fetchAll("
    SELECT
        u.full_name,
        u.extension,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_talk_time,
        SUM(ic.answered_count) as answered_calls
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    ORDER BY SUM(TIME_TO_SEC(ic.total_duration)) DESC
    LIMIT 5
", [$startDate, $endDate]);

// Her personel için günlük detaylar (modal için)
$dailyDetails = [];
foreach ($userStats as $user) {
    $daily = $db->fetchAll("
        SELECT
            call_date,
            call_count,
            answered_count,
            unanswered_count,
            answer_percentage,
            total_duration,
            avg_duration
        FROM incoming_calls
        WHERE user_id = ? AND call_date BETWEEN ? AND ?
        ORDER BY call_date DESC
    ", [$user['id'], $startDate, $endDate]);
    $dailyDetails[$user['id']] = $daily;
}

// Grafik verileri - Günlük trendler
$dailyTrends = $db->fetchAll("
    SELECT
        call_date,
        SUM(call_count) as total_calls,
        SUM(answered_count) as total_answered,
        SUM(unanswered_count) as total_unanswered,
        SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_duration_str,
        SUM(TIME_TO_SEC(total_duration)) / 3600.0 as total_duration_hours
    FROM incoming_calls
    WHERE call_date BETWEEN ? AND ?
    GROUP BY call_date
    ORDER BY call_date ASC
", [$startDate, $endDate]);

// Personel bazında dağılım (top 6 - radar chart için)
$topPerformersChart = $db->fetchAll("
    SELECT
        u.full_name,
        SUM(ic.call_count) as total_calls,
        SUM(ic.answered_count) as total_answered,
        SUM(ic.unanswered_count) as total_unanswered,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_duration_str,
        SUM(TIME_TO_SEC(ic.total_duration)) / 3600.0 as total_duration_hours
    FROM users u
    JOIN incoming_calls ic ON u.id = ic.user_id
    WHERE ic.call_date BETWEEN ? AND ?
    GROUP BY u.id
    ORDER BY total_calls DESC
    LIMIT 6
", [$startDate, $endDate]);

?>

<style>
    .filter-section {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
        margin-bottom: 30px;
    }

    .quick-filters {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;
        flex-wrap: wrap;
    }

    .quick-filter-btn {
        padding: 8px 16px;
        border: 2px solid #e0e0e0;
        background: white;
        border-radius: 8px;
        font-size: 13px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        text-decoration: none;
        color: #555;
        display: inline-block;
    }

    .quick-filter-btn:hover {
        border-color: #667eea;
        color: #667eea;
        background: #f8f9ff;
    }

    .quick-filter-btn.active {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-color: #667eea;
    }

    .filter-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        align-items: end;
    }

    .form-group {
        margin-bottom: 0;
    }

    .form-group label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #333;
        font-size: 14px;
    }

    .form-group input,
    .form-group select {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.3s;
        outline: none;
    }

    .form-group input:focus,
    .form-group select:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .stats-overview {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .stat-card {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
        transition: all 0.3s;
        position: relative;
        overflow: hidden;
        cursor: pointer;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 4px;
        height: 100%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }

    .stat-card.blue::before { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
    .stat-card.green::before { background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); }
    .stat-card.orange::before { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
    .stat-card.red::before { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
    .stat-card.purple::before { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }

    .stat-label {
        font-size: 13px;
        color: #7f8c8d;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        margin-bottom: 10px;
    }

    .stat-value {
        font-size: 32px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 5px;
    }

    .stat-subtitle {
        font-size: 13px;
        color: #95a5a6;
    }

    .comparison-cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .comparison-card {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
    }

    .comparison-header {
        font-size: 16px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #f0f0f0;
    }

    .comparison-item {
        display: flex;
        justify-content: space-between;
        padding: 10px 0;
        border-bottom: 1px solid #f8f9fa;
        cursor: pointer;
        transition: all 0.3s;
    }

    .comparison-item:hover {
        background: #f8f9fa;
        padding-left: 10px;
        padding-right: 10px;
        border-radius: 8px;
    }

    .comparison-label {
        color: #7f8c8d;
        font-size: 14px;
    }

    .comparison-value {
        font-weight: 700;
        color: #2c3e50;
        font-size: 16px;
    }

    .comparison-value.positive {
        color: #27ae60;
    }

    .comparison-value.negative {
        color: #e74c3c;
    }

    .top-performers-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .top-performers {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
    }

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f0f0f0;
    }

    .section-title {
        font-size: 18px;
        font-weight: 700;
        color: #2c3e50;
    }

    .performer-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px;
        background: #f8f9fa;
        border-radius: 10px;
        margin-bottom: 10px;
        transition: all 0.3s;
    }

    .performer-item:hover {
        background: #e9ecef;
        transform: translateX(5px);
    }

    .performer-rank {
        width: 35px;
        height: 35px;
        border-radius: 50%;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 14px;
        flex-shrink: 0;
    }

    .performer-info {
        flex: 1;
        margin-left: 12px;
    }

    .performer-name {
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 2px;
        font-size: 14px;
    }

    .performer-extension {
        font-size: 11px;
        color: #7f8c8d;
    }

    .performer-stats {
        text-align: right;
    }

    .performer-value {
        font-size: 16px;
        font-weight: 700;
        color: #2c3e50;
    }

    .performer-subtitle {
        font-size: 11px;
        color: #7f8c8d;
        margin-top: 2px;
    }

    .data-table-container {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
        margin-bottom: 30px;
        overflow-x: auto;
    }

    table {
        width: 100%;
        border-collapse: collapse;
    }

    thead {
        background: #f8f9fa;
    }

    th {
        padding: 15px;
        text-align: center;
        font-weight: 600;
        color: #2c3e50;
        font-size: 13px;
        border-bottom: 2px solid #e0e0e0;
        white-space: nowrap;
    }

    td {
        padding: 15px;
        border-bottom: 1px solid #f0f0f0;
        font-size: 14px;
        text-align: center;
    }

    tbody tr {
        cursor: pointer;
        transition: all 0.2s;
    }

    tbody tr:hover {
        background: #f8f9fa;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    }

    .badge {
        padding: 5px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    .badge.excellent {
        background: #d4edda;
        color: #155724;
    }

    .badge.good {
        background: #d1ecf1;
        color: #0c5460;
    }

    .badge.average {
        background: #fff3cd;
        color: #856404;
    }

    .badge.poor {
        background: #f8d7da;
        color: #721c24;
    }

    .progress-bar {
        width: 100%;
        height: 8px;
        background: #e0e0e0;
        border-radius: 10px;
        overflow: hidden;
        margin-top: 5px;
    }

    .progress-fill {
        height: 100%;
        transition: width 0.3s;
    }

    .progress-fill.excellent { background: linear-gradient(90deg, #11998e 0%, #38ef7d 100%); }
    .progress-fill.good { background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); }
    .progress-fill.average { background: linear-gradient(90deg, #f093fb 0%, #f5576c 100%); }
    .progress-fill.poor { background: linear-gradient(90deg, #fa709a 0%, #fee140 100%); }

    .btn {
        padding: 10px 20px;
        border-radius: 8px;
        text-decoration: none;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.3s;
        border: none;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }

    .btn-secondary {
        background: #e0e0e0;
        color: #333;
    }

    .btn-secondary:hover {
        background: #d0d0d0;
    }

    .empty-state {
        text-align: center;
        padding: 80px 20px;
    }

    .empty-state-icon {
        font-size: 80px;
        margin-bottom: 20px;
        opacity: 0.3;
    }

    .empty-state-title {
        font-size: 24px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 10px;
    }

    .empty-state-text {
        font-size: 16px;
        color: #7f8c8d;
        margin-bottom: 30px;
    }

    /* Modal */
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.7);
        z-index: 10000;
        align-items: center;
        justify-content: center;
        animation: fadeIn 0.3s;
    }

    .modal.active {
        display: flex;
    }

    @keyframes fadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }

    .modal-content {
        background: white;
        border-radius: 20px;
        padding: 0;
        max-width: 800px;
        width: 90%;
        max-height: 90vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        animation: slideUp 0.3s;
    }

    @keyframes slideUp {
        from {
            opacity: 0;
            transform: translateY(50px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .modal-header {
        padding: 25px 30px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .modal-title {
        font-size: 22px;
        font-weight: 700;
    }

    .close-modal {
        background: rgba(255, 255, 255, 0.2);
        border: none;
        width: 35px;
        height: 35px;
        border-radius: 50%;
        font-size: 24px;
        cursor: pointer;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s;
    }

    .close-modal:hover {
        background: rgba(255, 255, 255, 0.3);
        transform: rotate(90deg);
    }

    .modal-body {
        padding: 30px;
        overflow-y: auto;
        flex: 1;
    }

    .modal-table {
        width: 100%;
        margin-top: 20px;
    }

    .modal-table th {
        background: #f8f9fa;
        padding: 12px;
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        text-align: center;
    }

    .modal-table td {
        padding: 12px;
        font-size: 13px;
        text-align: center;
    }

    .click-hint {
        font-size: 11px;
        color: #95a5a6;
        margin-top: 5px;
        font-style: italic;
    }

    /* Grafik Stilleri */
    .charts-section {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }

    .chart-container {
        background: white;
        border-radius: 15px;
        padding: 25px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
    }

    .chart-title {
        font-size: 18px;
        font-weight: 700;
        color: #2c3e50;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 2px solid #f0f0f0;
    }

    .chart-wrapper {
        position: relative;
        height: 300px;
    }

    @media (max-width: 768px) {
        .charts-section {
            grid-template-columns: 1fr;
        }
    }

    /* Karşılaştırma Oranları Stilleri */
    .comparison-value-with-change {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-end;
        gap: 8px;
    }

    .change-indicator {
        font-size: 11px;
        font-weight: 600;
        padding: 2px 6px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        gap: 2px;
    }

    .change-indicator.positive {
        background: rgba(39, 174, 96, 0.1);
        color: #27ae60;
    }

    .change-indicator.negative {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
    }

    /* Performans Skoru Info Tooltip */
    .performance-info {
        position: relative;
        display: inline-flex;
        align-items: center;
        gap: 5px;
    }

    .info-icon {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 18px;
        height: 18px;
        border-radius: 50%;
        background: #667eea;
        color: white;
        font-size: 12px;
        font-weight: bold;
        cursor: help;
        transition: all 0.3s;
    }

    .info-icon:hover {
        background: #764ba2;
        transform: scale(1.1);
    }

    .info-tooltip {
        visibility: hidden;
        opacity: 0;
        position: absolute;
        top: 100%;
        left: 50%;
        transform: translateX(-50%) translateY(10px);
        margin-top: 8px;
        background: rgba(44, 62, 80, 0.95);
        color: white;
        padding: 15px;
        border-radius: 10px;
        font-size: 12px;
        line-height: 1.6;
        width: 320px;
        z-index: 10000;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        transition: all 0.3s;
        pointer-events: none;
        text-align: left;
        font-weight: normal;
        white-space: normal;
    }

    .info-tooltip::after {
        content: '';
        position: absolute;
        bottom: 100%;
        left: 50%;
        transform: translateX(-50%);
        border: 8px solid transparent;
        border-bottom-color: rgba(44, 62, 80, 0.95);
    }

    .performance-info:hover .info-tooltip {
        visibility: visible;
        opacity: 1;
        transform: translateX(-50%) translateY(0);
    }

    .info-tooltip strong {
        color: #f39c12;
        font-weight: 600;
    }

    .info-tooltip .tooltip-title {
        font-size: 13px;
        font-weight: 700;
        margin-bottom: 10px;
        color: #3498db;
        border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        padding-bottom: 8px;
    }

    .info-tooltip .tooltip-item {
        margin: 6px 0;
        padding-left: 8px;
    }
</style>

<!-- Filtre Bölümü -->
<div class="filter-section">
    <!-- Hızlı Filtreler -->
    <div class="quick-filters">
        <a href="?quick_filter=today<?php echo $selectedUser ? '&user_id='.$selectedUser : ''; ?>"
           class="quick-filter-btn <?php echo $quickFilter == 'today' ? 'active' : ''; ?>">
            📍 Bugün
        </a>
        <a href="?quick_filter=yesterday<?php echo $selectedUser ? '&user_id='.$selectedUser : ''; ?>"
           class="quick-filter-btn <?php echo $quickFilter == 'yesterday' ? 'active' : ''; ?>">
            ⏮️ Dün
        </a>
        <a href="?quick_filter=this_week<?php echo $selectedUser ? '&user_id='.$selectedUser : ''; ?>"
           class="quick-filter-btn <?php echo (!$quickFilter || $quickFilter == 'this_week') ? 'active' : ''; ?>">
            📊 Bu Hafta
        </a>

        <?php
        // Sadece bu yılın aylarını göster
        $currentYear = date('Y');
        for ($i = 0; $i >= -11; $i--) {
            $monthDate = strtotime("$i months");
            $monthNum = (int)date('n', $monthDate);
            $year = date('Y', $monthDate);

            // Sadece şu anki yıldaki ayları göster
            if ($year != $currentYear) {
                continue;
            }

            $monthValue = "month_$i";
            $isActive = $quickFilter === $monthValue;
            ?>
            <a href="?quick_filter=<?php echo $monthValue; ?><?php echo $selectedUser ? '&user_id='.$selectedUser : ''; ?>"
               class="quick-filter-btn <?php echo $isActive ? 'active' : ''; ?>">
                📆 <?php echo $turkishMonths[$monthNum]; ?>
            </a>
        <?php } ?>
    </div>

    <form method="GET" action="">
        <div class="filter-grid">
            <div class="form-group">
                <label for="start_date">Başlangıç Tarihi</label>
                <input type="date" id="start_date" name="start_date" value="<?php echo $startDate; ?>">
            </div>
            <div class="form-group">
                <label for="end_date">Bitiş Tarihi</label>
                <input type="date" id="end_date" name="end_date" value="<?php echo $endDate; ?>">
            </div>
            <div class="form-group">
                <label for="user_id">Personel</label>
                <select id="user_id" name="user_id">
                    <option value="">Tüm Personeller</option>
                    <?php foreach ($users as $user): ?>
                        <option value="<?php echo $user['id']; ?>" <?php echo $selectedUser == $user['id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($user['full_name']); ?> (<?php echo htmlspecialchars($user['extension']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group" style="display: flex; gap: 10px;">
                <button type="submit" class="btn btn-primary" style="flex: 1;">Filtrele</button>
                <a href="incoming_calls.php" class="btn btn-secondary" style="flex: 1; justify-content: center;">Temizle</a>
            </div>
            <?php if (Auth::isAdmin()): ?>
            <div class="form-group">
                <a href="upload_incoming.php" class="btn btn-secondary" style="width: 100%; justify-content: center;">Excel Yükle</a>
            </div>
            <?php endif; ?>
        </div>
    </form>
</div>

<?php if (empty($userStats)): ?>
    <div class="data-table-container">
        <div class="empty-state">
            <div class="empty-state-icon">📊</div>
            <h2 class="empty-state-title">Henüz Veri Yok</h2>
            <p class="empty-state-text">
                Seçili tarih aralığında gelen arama verisi bulunamadı.<?php if (Auth::isAdmin()): ?><br>
                Excel dosyanızı yükleyerek başlayın.<?php endif; ?>
            </p>
            <?php if (Auth::isAdmin()): ?>
            <a href="upload_incoming.php" class="btn btn-primary">Excel Yükle</a>
            <?php endif; ?>
        </div>
    </div>
<?php else: ?>

<!-- Genel İstatistikler -->
<div class="stats-overview">
    <div class="stat-card blue" onclick="showCallsDetail('total')">
        <div class="stat-label">Toplam Gelen Arama</div>
        <div class="stat-value"><?php echo number_format($generalStats['total_calls'] ?? 0); ?></div>
        <div class="stat-subtitle"><?php
            $startFormatted = date('d.m', strtotime($startDate));
            $endFormatted = date('d.m.Y', strtotime($endDate));
            echo $startFormatted . ' - ' . $endFormatted;
        ?></div>
        <div class="click-hint">Detay için tıklayın</div>
    </div>
    <div class="stat-card green" onclick="showCallsDetail('answered')">
        <div class="stat-label">Cevaplanan</div>
        <div class="stat-value"><?php echo number_format($generalStats['total_answered'] ?? 0); ?></div>
        <div class="stat-subtitle">%<?php echo number_format($generalStats['avg_answer_rate'] ?? 0, 1); ?> oran</div>
        <div class="click-hint">Detay için tıklayın</div>
    </div>
    <div class="stat-card red" onclick="showCallsDetail('unanswered')">
        <div class="stat-label">Cevaplanmayan</div>
        <div class="stat-value"><?php echo number_format($generalStats['total_unanswered'] ?? 0); ?></div>
        <div class="stat-subtitle">Kaçırılan arama</div>
        <div class="click-hint">Detay için tıklayın</div>
    </div>
    <div class="stat-card purple" onclick="showCallsDetail('talktime')">
        <div class="stat-label">Toplam Konuşma</div>
        <div class="stat-value"><?php echo $generalStats['total_talk_time'] ?? '00:00:00'; ?></div>
        <div class="stat-subtitle">Ort: <?php echo $generalStats['avg_call_duration'] ?? '00:00:00'; ?></div>
        <div class="click-hint">Detay için tıklayın</div>
    </div>
    <div class="stat-card orange">
        <div class="stat-label">Aktif Personel</div>
        <div class="stat-value"><?php echo $generalStats['total_users'] ?? 0; ?></div>
        <div class="stat-subtitle">Veri kaydı olan</div>
    </div>
</div>

<!-- Üç Aylık Karşılaştırma -->
<div class="comparison-cards">
    <div class="comparison-card">
        <div class="comparison-header">📅 Bu Ay (<?php 
            $months = [
                'January' => 'Ocak', 'February' => 'Şubat', 'March' => 'Mart',
                'April' => 'Nisan', 'May' => 'Mayıs', 'June' => 'Haziran',
                'July' => 'Temmuz', 'August' => 'Ağustos', 'September' => 'Eylül',
                'October' => 'Ekim', 'November' => 'Kasım', 'December' => 'Aralık'
            ];
            echo $months[date('F')] . ' ' . date('Y'); 
        ?>)</div>
        
        <?php
        // Bu ay vs geçen ay karşılaştırma oranları
        $thisVsLastCalls = $lastMonthStats['total_calls'] > 0 ?
            round((($thisMonthStats['total_calls'] - $lastMonthStats['total_calls']) / $lastMonthStats['total_calls']) * 100, 1) : 0;
        $thisVsLastAnswered = $lastMonthStats['total_answered'] > 0 ?
            round((($thisMonthStats['total_answered'] - $lastMonthStats['total_answered']) / $lastMonthStats['total_answered']) * 100, 1) : 0;
        $thisVsLastUnanswered = $lastMonthStats['total_unanswered'] > 0 ?
            round((($thisMonthStats['total_unanswered'] - $lastMonthStats['total_unanswered']) / $lastMonthStats['total_unanswered']) * 100, 1) : 0;
        $thisVsLastRate = $lastMonthStats['avg_answer_rate'] > 0 ?
            round($thisMonthStats['avg_answer_rate'] - $lastMonthStats['avg_answer_rate'], 1) : 0;

        // Toplam konuşma süresi karşılaştırması (saniye cinsinden)
        $thisMonthTalkSeconds = 0;
        $lastMonthTalkSeconds = 0;
        if (!empty($thisMonthStats['total_talk_time'])) {
            list($h, $m, $s) = explode(':', $thisMonthStats['total_talk_time']);
            $thisMonthTalkSeconds = ($h * 3600) + ($m * 60) + $s;
        }
        if (!empty($lastMonthStats['total_talk_time'])) {
            list($h, $m, $s) = explode(':', $lastMonthStats['total_talk_time']);
            $lastMonthTalkSeconds = ($h * 3600) + ($m * 60) + $s;
        }
        $thisVsLastTalkTime = $lastMonthTalkSeconds > 0 ?
            round((($thisMonthTalkSeconds - $lastMonthTalkSeconds) / $lastMonthTalkSeconds) * 100, 1) : 0;
        ?>
        
        <div class="comparison-item" onclick="showMonthlyDetail('this_month', 'total')">
            <span class="comparison-label">Toplam Gelen Arama</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value"><?php echo number_format($thisMonthStats['total_calls'] ?? 0); ?></span>
                <span class="change-indicator <?php echo $thisVsLastCalls >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $thisVsLastCalls >= 0 ? '↗' : '↘'; ?> <?php echo abs($thisVsLastCalls); ?>%
                </span>
            </div>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('this_month', 'answered')">
            <span class="comparison-label">Cevaplanan</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value positive"><?php echo number_format($thisMonthStats['total_answered'] ?? 0); ?></span>
                <span class="change-indicator <?php echo $thisVsLastAnswered >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $thisVsLastAnswered >= 0 ? '↗' : '↘'; ?> <?php echo abs($thisVsLastAnswered); ?>%
                </span>
            </div>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('this_month', 'unanswered')">
            <span class="comparison-label">Cevaplanmayan</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value negative"><?php echo number_format($thisMonthStats['total_unanswered'] ?? 0); ?></span>
                <span class="change-indicator <?php echo $thisVsLastUnanswered >= 0 ? 'negative' : 'positive'; ?>">
                    <?php echo $thisVsLastUnanswered >= 0 ? '↗' : '↘'; ?> <?php echo abs($thisVsLastUnanswered); ?>%
                </span>
            </div>
        </div>
        <div class="comparison-item">
            <span class="comparison-label">Cevaplama Oranı</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value">%<?php echo number_format($thisMonthStats['avg_answer_rate'] ?? 0, 1); ?></span>
                <span class="change-indicator <?php echo $thisVsLastRate >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $thisVsLastRate >= 0 ? '↗' : '↘'; ?> <?php echo abs($thisVsLastRate); ?> puan
                </span>
            </div>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('this_month', 'talktime')">
            <span class="comparison-label">Toplam Konuşma</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value"><?php echo $thisMonthStats['total_talk_time'] ?? '00:00:00'; ?></span>
                <span class="change-indicator <?php echo $thisVsLastTalkTime >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $thisVsLastTalkTime >= 0 ? '↗' : '↘'; ?> <?php echo abs($thisVsLastTalkTime); ?>%
                </span>
            </div>
        </div>
    </div>

    <div class="comparison-card">
        <div class="comparison-header">📅 Geçen Ay (<?php
            echo $months[date('F', strtotime('-1 month'))] . ' ' . date('Y', strtotime('-1 month'));
        ?>)</div>

        <?php
        // Geçen ay vs 2 ay önce karşılaştırma oranları
        $lastVsTwoCalls = $twoMonthsAgoStats['total_calls'] > 0 ?
            round((($lastMonthStats['total_calls'] - $twoMonthsAgoStats['total_calls']) / $twoMonthsAgoStats['total_calls']) * 100, 1) : 0;
        $lastVsTwoAnswered = $twoMonthsAgoStats['total_answered'] > 0 ?
            round((($lastMonthStats['total_answered'] - $twoMonthsAgoStats['total_answered']) / $twoMonthsAgoStats['total_answered']) * 100, 1) : 0;
        $lastVsTwoUnanswered = $twoMonthsAgoStats['total_unanswered'] > 0 ?
            round((($lastMonthStats['total_unanswered'] - $twoMonthsAgoStats['total_unanswered']) / $twoMonthsAgoStats['total_unanswered']) * 100, 1) : 0;
        $lastVsTwoRate = $twoMonthsAgoStats['avg_answer_rate'] > 0 ?
            round($lastMonthStats['avg_answer_rate'] - $twoMonthsAgoStats['avg_answer_rate'], 1) : 0;

        // Toplam konuşma süresi karşılaştırması (Geçen ay vs 2 ay önce)
        $lastMonthTalkSeconds2 = 0;
        $twoMonthsAgoTalkSeconds = 0;
        if (!empty($lastMonthStats['total_talk_time'])) {
            list($h, $m, $s) = explode(':', $lastMonthStats['total_talk_time']);
            $lastMonthTalkSeconds2 = ($h * 3600) + ($m * 60) + $s;
        }
        if (!empty($twoMonthsAgoStats['total_talk_time'])) {
            list($h, $m, $s) = explode(':', $twoMonthsAgoStats['total_talk_time']);
            $twoMonthsAgoTalkSeconds = ($h * 3600) + ($m * 60) + $s;
        }
        $lastVsTwoTalkTime = $twoMonthsAgoTalkSeconds > 0 ?
            round((($lastMonthTalkSeconds2 - $twoMonthsAgoTalkSeconds) / $twoMonthsAgoTalkSeconds) * 100, 1) : 0;
        ?>
        
        <div class="comparison-item" onclick="showMonthlyDetail('last_month', 'total')">
            <span class="comparison-label">Toplam Gelen Arama</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value"><?php echo number_format($lastMonthStats['total_calls'] ?? 0); ?></span>
                <span class="change-indicator <?php echo $lastVsTwoCalls >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $lastVsTwoCalls >= 0 ? '↗' : '↘'; ?> <?php echo abs($lastVsTwoCalls); ?>%
                </span>
            </div>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('last_month', 'answered')">
            <span class="comparison-label">Cevaplanan</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value positive"><?php echo number_format($lastMonthStats['total_answered'] ?? 0); ?></span>
                <span class="change-indicator <?php echo $lastVsTwoAnswered >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $lastVsTwoAnswered >= 0 ? '↗' : '↘'; ?> <?php echo abs($lastVsTwoAnswered); ?>%
                </span>
            </div>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('last_month', 'unanswered')">
            <span class="comparison-label">Cevaplanmayan</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value negative"><?php echo number_format($lastMonthStats['total_unanswered'] ?? 0); ?></span>
                <span class="change-indicator <?php echo $lastVsTwoUnanswered >= 0 ? 'negative' : 'positive'; ?>">
                    <?php echo $lastVsTwoUnanswered >= 0 ? '↗' : '↘'; ?> <?php echo abs($lastVsTwoUnanswered); ?>%
                </span>
            </div>
        </div>
        <div class="comparison-item">
            <span class="comparison-label">Cevaplama Oranı</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value">%<?php echo number_format($lastMonthStats['avg_answer_rate'] ?? 0, 1); ?></span>
                <span class="change-indicator <?php echo $lastVsTwoRate >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $lastVsTwoRate >= 0 ? '↗' : '↘'; ?> <?php echo abs($lastVsTwoRate); ?> puan
                </span>
            </div>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('last_month', 'talktime')">
            <span class="comparison-label">Toplam Konuşma</span>
            <div class="comparison-value-with-change">
                <span class="comparison-value"><?php echo $lastMonthStats['total_talk_time'] ?? '00:00:00'; ?></span>
                <span class="change-indicator <?php echo $lastVsTwoTalkTime >= 0 ? 'positive' : 'negative'; ?>">
                    <?php echo $lastVsTwoTalkTime >= 0 ? '↗' : '↘'; ?> <?php echo abs($lastVsTwoTalkTime); ?>%
                </span>
            </div>
        </div>
    </div>

    <div class="comparison-card">
        <div class="comparison-header">📅 2 Ay Önce (<?php
            echo $months[date('F', strtotime('-2 months'))] . ' ' . date('Y', strtotime('-2 months'));
        ?>)</div>
        <div class="comparison-item" onclick="showMonthlyDetail('two_months_ago', 'total')">
            <span class="comparison-label">Toplam Gelen Arama</span>
            <span class="comparison-value"><?php echo number_format($twoMonthsAgoStats['total_calls'] ?? 0); ?></span>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('two_months_ago', 'answered')">
            <span class="comparison-label">Cevaplanan</span>
            <span class="comparison-value positive"><?php echo number_format($twoMonthsAgoStats['total_answered'] ?? 0); ?></span>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('two_months_ago', 'unanswered')">
            <span class="comparison-label">Cevaplanmayan</span>
            <span class="comparison-value negative"><?php echo number_format($twoMonthsAgoStats['total_unanswered'] ?? 0); ?></span>
        </div>
        <div class="comparison-item">
            <span class="comparison-label">Cevaplama Oranı</span>
            <span class="comparison-value">%<?php echo number_format($twoMonthsAgoStats['avg_answer_rate'] ?? 0, 1); ?></span>
        </div>
        <div class="comparison-item" onclick="showMonthlyDetail('two_months_ago', 'talktime')">
            <span class="comparison-label">Toplam Konuşma</span>
            <span class="comparison-value"><?php echo $twoMonthsAgoStats['total_talk_time'] ?? '00:00:00'; ?></span>
        </div>
    </div>
</div>

<!-- Grafikler -->
<?php if (!empty($dailyTrends)): ?>
<div class="charts-section">
    <!-- Günlük Arama Trendi -->
    <div class="chart-container">
        <h3 class="chart-title">📈 Günlük Arama Trendi</h3>
        <div class="chart-wrapper">
            <canvas id="dailyCallsChart"></canvas>
        </div>
    </div>

    <!-- Günlük Konuşma Süresi -->
    <div class="chart-container">
        <h3 class="chart-title">⏱️ Günlük Konuşma Süresi</h3>
        <div class="chart-wrapper">
            <canvas id="dailyDurationChart"></canvas>
        </div>
    </div>
</div>

<div class="charts-section">
    <!-- Personel Bazında Arama Dağılımı -->
    <div class="chart-container">
        <h3 class="chart-title">👥 Personellerin Toplam Gelen Aramaları</h3>
        <div class="chart-wrapper">
            <canvas id="topPerformersChart"></canvas>
        </div>
    </div>

    <!-- Personel Bazında Konuşma Süresi -->
    <div class="chart-container">
        <h3 class="chart-title">🕐 Personel Konuşma Süreleri</h3>
        <div class="chart-wrapper">
            <canvas id="topDurationChart"></canvas>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Top Performers - 3 Bölüm -->
<div class="top-performers-grid">
    <!-- En İyi Cevaplama Oranları -->
    <?php if (!empty($topAnswerRate)): ?>
    <div class="top-performers">
        <div class="section-header">
            <h2 class="section-title">🏆 En İyi Cevaplama</h2>
        </div>
        <?php foreach ($topAnswerRate as $index => $performer): ?>
            <div class="performer-item">
                <div class="performer-rank"><?php echo $index + 1; ?></div>
                <div class="performer-info">
                    <div class="performer-name"><?php echo htmlspecialchars($performer['full_name']); ?></div>
                    <div class="performer-extension">Dahili: <?php echo htmlspecialchars($performer['extension']); ?></div>
                </div>
                <div class="performer-stats">
                    <div class="performer-value"><?php echo number_format($performer['total_answered']); ?>/<?php echo number_format($performer['total_calls']); ?></div>
                    <div class="performer-subtitle">%<?php echo number_format($performer['avg_answer_rate'], 1); ?></div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- En Çok Cevapsız -->
    <?php if (!empty($mostUnanswered)): ?>
    <div class="top-performers">
        <div class="section-header">
            <h2 class="section-title">📵 En Çok Cevapsız</h2>
        </div>
        <?php foreach ($mostUnanswered as $index => $performer): ?>
            <div class="performer-item">
                <div class="performer-rank" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);"><?php echo $index + 1; ?></div>
                <div class="performer-info">
                    <div class="performer-name"><?php echo htmlspecialchars($performer['full_name']); ?></div>
                    <div class="performer-extension">Dahili: <?php echo htmlspecialchars($performer['extension']); ?></div>
                </div>
                <div class="performer-stats">
                    <div class="performer-value"><?php echo number_format($performer['total_unanswered']); ?>/<?php echo number_format($performer['total_calls']); ?></div>
                    <div class="performer-subtitle" style="color: #e74c3c;">%<?php echo round(($performer['total_unanswered'] / $performer['total_calls']) * 100, 1); ?></div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <!-- En Uzun Konuşma -->
    <?php if (!empty($mostTalkTime)): ?>
    <div class="top-performers">
        <div class="section-header">
            <h2 class="section-title">⏱️ En Uzun Konuşma</h2>
        </div>
        <?php foreach ($mostTalkTime as $index => $performer): ?>
            <div class="performer-item">
                <div class="performer-rank" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);"><?php echo $index + 1; ?></div>
                <div class="performer-info">
                    <div class="performer-name"><?php echo htmlspecialchars($performer['full_name']); ?></div>
                    <div class="performer-extension">Dahili: <?php echo htmlspecialchars($performer['extension']); ?></div>
                </div>
                <div class="performer-stats">
                    <div class="performer-value"><?php echo $performer['total_talk_time']; ?></div>
                    <div class="performer-subtitle"><?php echo number_format($performer['answered_calls']); ?> arama</div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
</div>

<!-- Personel Bazında Detaylı İstatistikler -->
<div class="data-table-container">
    <div class="section-header">
        <h2 class="section-title">👥 Personel Bazında Detaylı Analiz</h2>
        <div class="click-hint">Satıra tıklayarak detayları görün</div>
    </div>
    <table>
        <thead>
            <tr>
                <th>Sıra</th>
                <th>Personel</th>
                <th>Dahili</th>
                <th>
                    <div class="performance-info">
                        Performans Skoru
                        <span class="info-icon">i</span>
                        <div class="info-tooltip">
                            <div class="tooltip-title">📊 Performans Skoru Hesaplama</div>
                            <div class="tooltip-item">🎯 <strong>Cevaplanan Arama:</strong> %40 ağırlık</div>
                            <div class="tooltip-item">⏱️ <strong>Toplam Konuşma Süresi:</strong> %30 ağırlık</div>
                            <div class="tooltip-item">📞 <strong>Cevaplama Oranı:</strong> %20 ağırlık</div>
                            <div class="tooltip-item">📈 <strong>Günlük Ortalama:</strong> %10 ağırlık</div>
                            <div style="margin-top: 10px; padding-top: 8px; border-top: 1px solid rgba(255,255,255,0.2); font-size: 11px; color: #bdc3c7;">
                                <strong>Kategoriler:</strong> Mükemmel (85+) | Çok İyi (70-84) | İyi (55-69) | Gelişmeli (&lt;55)
                            </div>
                        </div>
                    </div>
                </th>
                <th>Toplam Gelen Arama</th>
                <th>Cevaplanan</th>
                <th>Cevaplanmayan</th>
                <th>Cevaplama %</th>
                <th>Toplam Konuşma</th>
                <th>Ort. Konuşma</th>
                <th>Günlük Ort.</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($userStats as $index => $stat):
                $answerRate = $stat['avg_answer_rate'] ?? 0;
                $ratingClass = $answerRate >= 90 ? 'excellent' : ($answerRate >= 75 ? 'good' : ($answerRate >= 60 ? 'average' : 'poor'));
            ?>
            <tr onclick="showUserDetail(<?php echo $stat['id']; ?>)">
                <td><strong><?php echo $index + 1; ?></strong></td>
                <td><strong><?php echo htmlspecialchars($stat['full_name']); ?></strong></td>
                <td><?php echo htmlspecialchars($stat['extension'] ?? '-'); ?></td>
                <td>
                    <span class="badge <?php echo $stat['performance_class'] ?? 'poor'; ?>"><?php echo $stat['performance_score'] ?? 0; ?> puan</span>
                    <div style="font-size: 11px; color: #7f8c8d; margin-top: 10px;"><?php echo $stat['performance_category'] ?? 'Hesaplanmadı'; ?></div>
                </td>
                <td><strong><?php echo number_format($stat['total_calls'] ?? 0); ?></strong></td>
                <td style="color: #27ae60;"><strong><?php echo number_format($stat['total_answered'] ?? 0); ?></strong></td>
                <td style="color: #e74c3c;"><strong><?php echo number_format($stat['total_unanswered'] ?? 0); ?></strong></td>
                <td>
                    <span class="badge <?php echo $ratingClass; ?>">%<?php echo number_format($answerRate, 1); ?></span>
                    <div class="progress-bar">
                        <div class="progress-fill <?php echo $ratingClass; ?>" style="width: <?php echo $answerRate; ?>%"></div>
                    </div>
                </td>
                <td><?php echo $stat['total_talk_time'] ?? '00:00:00'; ?></td>
                <td><?php echo $stat['avg_call_duration'] ?? '00:00:00'; ?></td>
                <td><?php echo number_format($stat['daily_avg_calls'] ?? 0); ?> arama/gün</td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php endif; ?>

<!-- Modal - Toplam/Cevaplanan/Cevaplanmayan Detay -->
<div id="callsDetailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="callsModalTitle">Detay</h3>
            <button class="close-modal" onclick="closeModal('callsDetailModal')">&times;</button>
        </div>
        <div class="modal-body" id="callsModalBody">
            <!-- JavaScript ile doldurulacak -->
        </div>
    </div>
</div>

<!-- Modal - Personel Detay -->
<div id="userDetailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="userModalTitle">Personel Detayı</h3>
            <button class="close-modal" onclick="closeModal('userDetailModal')">&times;</button>
        </div>
        <div class="modal-body" id="userModalBody">
            <!-- JavaScript ile doldurulacak -->
        </div>
    </div>
</div>

<script>
// Veri hazırlama
const userDetailedStats = <?php echo json_encode($userDetailedStats); ?>;
const dailyDetails = <?php echo json_encode($dailyDetails); ?>;

// Aylık personel bazlı veriler
const thisMonthUserStats = <?php echo json_encode($thisMonthUserStats); ?>;
const lastMonthUserStats = <?php echo json_encode($lastMonthUserStats); ?>;
const twoMonthsAgoUserStats = <?php echo json_encode($twoMonthsAgoUserStats); ?>;

// Tarih formatlama fonksiyonu (YYYY-MM-DD -> DD.MM.YYYY)
function formatDate(dateString) {
    if (!dateString) return '';
    const parts = dateString.split('-');
    if (parts.length === 3) {
        return `${parts[2]}.${parts[1]}.${parts[0]}`;
    }
    return dateString;
}

// Saat formatına çevirme (8.09 -> "8 saat 5 dakika")
function formatHoursToDuration(hours) {
    const totalMinutes = Math.round(parseFloat(hours) * 60);
    const h = Math.floor(totalMinutes / 60);
    const m = totalMinutes % 60;

    if (h === 0) {
        return m + ' dakika';
    } else if (m === 0) {
        return h + ' saat';
    } else {
        return h + ' saat ' + m + ' dakika';
    }
}

// Modal gösterme fonksiyonları
function showCallsDetail(type) {
    const modal = document.getElementById('callsDetailModal');
    const title = document.getElementById('callsModalTitle');
    const body = document.getElementById('callsModalBody');

    let titleText = '';
    let sortedData = [...userDetailedStats];

    if (type === 'total') {
        titleText = 'Toplam Gelen Arama - Personel Bazında';
        sortedData.sort((a, b) => b.total_calls - a.total_calls);
    } else if (type === 'answered') {
        titleText = 'Cevaplanan Aramalar - Personel Bazında';
        sortedData.sort((a, b) => b.total_answered - a.total_answered);
    } else if (type === 'unanswered') {
        titleText = 'Cevaplanmayan Aramalar - Personel Bazında';
        sortedData.sort((a, b) => b.total_unanswered - a.total_unanswered);
    } else if (type === 'talktime') {
        titleText = 'Toplam Konuşma Süresi - Personel Bazında';
        sortedData.sort((a, b) => {
            const timeA = a.total_talk_time.split(':').reduce((acc, time) => (60 * acc) + +time, 0);
            const timeB = b.total_talk_time.split(':').reduce((acc, time) => (60 * acc) + +time, 0);
            return timeB - timeA;
        });
    }

    title.textContent = titleText;

    let tableHTML = '<table class="modal-table"><thead><tr>';
    tableHTML += '<th>Sıra</th><th>Personel</th><th>Dahili</th>';

    if (type === 'total') {
        tableHTML += '<th>Toplam Gelen Arama</th><th>Cevaplanan</th><th>Cevapsız</th><th>Konuşma Süresi</th>';
    } else if (type === 'answered') {
        tableHTML += '<th>Cevaplanan</th><th>Toplam Gelen Arama</th><th>Oran</th>';
    } else if (type === 'unanswered') {
        tableHTML += '<th>Cevaplanmayan</th><th>Toplam Gelen Arama</th>';
    } else if (type === 'talktime') {
        tableHTML += '<th>Toplam Konuşma</th><th>Ortalama Konuşma</th><th>Cevaplanan Arama</th>';
    }

    tableHTML += '</tr></thead><tbody>';

    sortedData.forEach((user, index) => {
        tableHTML += '<tr>';
        tableHTML += `<td>${index + 1}</td>`;
        tableHTML += `<td><strong>${user.full_name}</strong></td>`;
        tableHTML += `<td>${user.extension}</td>`;

        if (type === 'total') {
            tableHTML += `<td><strong>${parseInt(user.total_calls).toLocaleString()}</strong></td>`;
            tableHTML += `<td style="color: #27ae60;">${parseInt(user.total_answered).toLocaleString()}</td>`;
            tableHTML += `<td style="color: #e74c3c;">${parseInt(user.total_unanswered).toLocaleString()}</td>`;
            tableHTML += `<td style="color: #9b59b6;">${user.total_talk_time}</td>`;
        } else if (type === 'answered') {
            tableHTML += `<td style="color: #27ae60;"><strong>${parseInt(user.total_answered).toLocaleString()}</strong></td>`;
            tableHTML += `<td>${parseInt(user.total_calls).toLocaleString()}</td>`;
            tableHTML += `<td>${user.avg_answer_rate}%</td>`;
        } else if (type === 'unanswered') {
            tableHTML += `<td style="color: #e74c3c;"><strong>${parseInt(user.total_unanswered).toLocaleString()}</strong></td>`;
            tableHTML += `<td>${parseInt(user.total_calls).toLocaleString()}</td>`;
        } else if (type === 'talktime') {
            tableHTML += `<td style="color: #9b59b6;"><strong>${user.total_talk_time}</strong></td>`;
            tableHTML += `<td style="color: #3498db;">${user.avg_call_duration || '00:00:00'}</td>`;
            tableHTML += `<td>${parseInt(user.total_answered).toLocaleString()}</td>`;
        }

        tableHTML += '</tr>';
    });

    tableHTML += '</tbody></table>';
    body.innerHTML = tableHTML;
    modal.classList.add('active');
}

// Aylık karşılaştırma modalı
function showMonthlyDetail(month, type) {
    const modal = document.getElementById('callsDetailModal');
    const title = document.getElementById('callsModalTitle');
    const body = document.getElementById('callsModalBody');

    let monthData = [];
    let monthName = '';

    if (month === 'this_month') {
        monthData = [...thisMonthUserStats];
        monthName = '<?php
            $months = [
                'January' => 'Ocak', 'February' => 'Şubat', 'March' => 'Mart',
                'April' => 'Nisan', 'May' => 'Mayıs', 'June' => 'Haziran',
                'July' => 'Temmuz', 'August' => 'Ağustos', 'September' => 'Eylül',
                'October' => 'Ekim', 'November' => 'Kasım', 'December' => 'Aralık'
            ];
            echo $months[date('F')] . ' ' . date('Y');
        ?>';
    } else if (month === 'last_month') {
        monthData = [...lastMonthUserStats];
        monthName = '<?php echo $months[date('F', strtotime('-1 month'))] . ' ' . date('Y', strtotime('-1 month')); ?>';
    } else if (month === 'two_months_ago') {
        monthData = [...twoMonthsAgoUserStats];
        monthName = '<?php echo $months[date('F', strtotime('-2 months'))] . ' ' . date('Y', strtotime('-2 months')); ?>';
    }

    let titleText = '';

    if (type === 'total') {
        titleText = monthName + ' - Toplam Gelen Arama';
        monthData.sort((a, b) => b.total_calls - a.total_calls);
    } else if (type === 'answered') {
        titleText = monthName + ' - Cevaplanan';
        monthData.sort((a, b) => b.total_answered - a.total_answered);
    } else if (type === 'unanswered') {
        titleText = monthName + ' - Cevaplanmayan';
        monthData.sort((a, b) => b.total_unanswered - a.total_unanswered);
    } else if (type === 'talktime') {
        titleText = monthName + ' - Toplam Konuşma';
        monthData.sort((a, b) => {
            const timeA = a.total_talk_time.split(':').reduce((acc, time) => (60 * acc) + +time, 0);
            const timeB = b.total_talk_time.split(':').reduce((acc, time) => (60 * acc) + +time, 0);
            return timeB - timeA;
        });
    }

    title.textContent = titleText;

    let tableHTML = '<table class="modal-table"><thead><tr>';
    tableHTML += '<th>Sıra</th><th>Personel</th><th>Dahili</th>';

    if (type === 'total') {
        tableHTML += '<th>Toplam Gelen Arama</th><th>Cevaplanan</th><th>Cevapsız</th>';
    } else if (type === 'answered') {
        tableHTML += '<th>Cevaplanan</th><th>Toplam Gelen Arama</th><th>Oran</th>';
    } else if (type === 'unanswered') {
        tableHTML += '<th>Cevaplanmayan</th><th>Toplam Gelen Arama</th><th>Oran</th>';
    } else if (type === 'talktime') {
        tableHTML += '<th>Toplam Konuşma</th><th>Cevaplanan Arama</th>';
    }

    tableHTML += '</tr></thead><tbody>';

    monthData.forEach((user, index) => {
        tableHTML += '<tr>';
        tableHTML += `<td>${index + 1}</td>`;
        tableHTML += `<td><strong>${user.full_name}</strong></td>`;
        tableHTML += `<td>${user.extension}</td>`;

        if (type === 'total') {
            tableHTML += `<td><strong>${parseInt(user.total_calls).toLocaleString()}</strong></td>`;
            tableHTML += `<td style="color: #27ae60;">${parseInt(user.total_answered).toLocaleString()}</td>`;
            tableHTML += `<td style="color: #e74c3c;">${parseInt(user.total_unanswered).toLocaleString()}</td>`;
        } else if (type === 'answered') {
            tableHTML += `<td style="color: #27ae60;"><strong>${parseInt(user.total_answered).toLocaleString()}</strong></td>`;
            tableHTML += `<td>${parseInt(user.total_calls).toLocaleString()}</td>`;
            tableHTML += `<td>${user.avg_answer_rate}%</td>`;
        } else if (type === 'unanswered') {
            tableHTML += `<td style="color: #e74c3c;"><strong>${parseInt(user.total_unanswered).toLocaleString()}</strong></td>`;
            tableHTML += `<td>${parseInt(user.total_calls).toLocaleString()}</td>`;
            const unansweredRate = user.total_calls > 0 ? ((user.total_unanswered / user.total_calls) * 100).toFixed(1) : 0;
            tableHTML += `<td>${unansweredRate}%</td>`;
        } else if (type === 'talktime') {
            tableHTML += `<td style="color: #9b59b6;"><strong>${user.total_talk_time}</strong></td>`;
            tableHTML += `<td>${parseInt(user.total_answered).toLocaleString()}</td>`;
        }

        tableHTML += '</tr>';
    });

    tableHTML += '</tbody></table>';
    body.innerHTML = tableHTML;
    modal.classList.add('active');
}

function showUserDetail(userId) {
    const modal = document.getElementById('userDetailModal');
    const title = document.getElementById('userModalTitle');
    const body = document.getElementById('userModalBody');

    const userStat = userDetailedStats.find(u => u.id == userId);
    const daily = dailyDetails[userId] || [];

    if (!userStat) return;

    title.textContent = `${userStat.full_name} - Detaylı Analiz`;

    let html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 10px; margin-bottom: 20px;">
            <h4 style="margin-bottom: 15px; color: #2c3e50;">Özet İstatistikler</h4>
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
                <div>
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">Dahili Numarası</div>
                    <div style="font-size: 18px; font-weight: 700;">${userStat.extension}</div>
                </div>
                <div>
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">Toplam Gelen Arama</div>
                    <div style="font-size: 18px; font-weight: 700;">${parseInt(userStat.total_calls).toLocaleString()}</div>
                </div>
                <div>
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">Cevaplanan</div>
                    <div style="font-size: 18px; font-weight: 700; color: #27ae60;">${parseInt(userStat.total_answered).toLocaleString()}</div>
                </div>
                <div>
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">Cevaplanmayan</div>
                    <div style="font-size: 18px; font-weight: 700; color: #e74c3c;">${parseInt(userStat.total_unanswered).toLocaleString()}</div>
                </div>
                <div>
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">Cevaplama Oranı</div>
                    <div style="font-size: 18px; font-weight: 700;">%${userStat.avg_answer_rate}</div>
                </div>
                <div>
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">Toplam Konuşma</div>
                    <div style="font-size: 18px; font-weight: 700;">${userStat.total_talk_time}</div>
                </div>
            </div>
        </div>
    `;

    if (daily.length > 0) {
        html += '<h4 style="margin-bottom: 15px; color: #2c3e50;">Günlük Detaylar</h4>';
        html += '<table class="modal-table"><thead><tr>';
        html += '<th>Tarih</th><th>Arama</th><th>Cevaplanan</th><th>Cevapsız</th><th>Oran</th><th>Konuşma</th><th>Ort. Süre</th>';
        html += '</tr></thead><tbody>';

        daily.forEach(day => {
            html += '<tr>';
            html += `<td><strong>${formatDate(day.call_date)}</strong></td>`;
            html += `<td>${parseInt(day.call_count).toLocaleString()}</td>`;
            html += `<td style="color: #27ae60;">${parseInt(day.answered_count).toLocaleString()}</td>`;
            html += `<td style="color: #e74c3c;">${parseInt(day.unanswered_count).toLocaleString()}</td>`;
            html += `<td>%${day.answer_percentage}</td>`;
            html += `<td>${day.total_duration}</td>`;
            html += `<td>${day.avg_duration}</td>`;
            html += '</tr>';
        });

        html += '</tbody></table>';
    }

    body.innerHTML = html;
    modal.classList.add('active');
}

function closeModal(modalId) {
    document.getElementById(modalId).classList.remove('active');
}

// Modal dışına tıklayınca kapat
document.querySelectorAll('.modal').forEach(modal => {
    modal.addEventListener('click', function(e) {
        if (e.target === this) {
            this.classList.remove('active');
        }
    });
});

// ESC tuşu ile kapat
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal').forEach(modal => {
            modal.classList.remove('active');
        });
    }
});
</script>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

<script>
// Grafik verileri hazırlama
const dailyTrendsData = <?php echo json_encode($dailyTrends); ?>;
const topPerformersData = <?php echo json_encode($topPerformersChart); ?>;

// Grafik renkleri
const colors = {
    primary: 'rgba(102, 126, 234, 1)',
    primaryLight: 'rgba(102, 126, 234, 0.2)',
    success: 'rgba(39, 174, 96, 1)',
    successLight: 'rgba(39, 174, 96, 0.2)',
    danger: 'rgba(231, 76, 60, 1)',
    dangerLight: 'rgba(231, 76, 60, 0.2)',
    warning: 'rgba(243, 156, 18, 1)',
    warningLight: 'rgba(243, 156, 18, 0.2)',
    purple: 'rgba(155, 89, 182, 1)',
    purpleLight: 'rgba(155, 89, 182, 0.2)'
};

// 1. Günlük Arama Trendi Grafiği
const dailyCallsCtx = document.getElementById('dailyCallsChart');
if (dailyCallsCtx && dailyTrendsData.length > 0) {
    new Chart(dailyCallsCtx, {
        type: 'line',
        data: {
            labels: dailyTrendsData.map(d => formatDate(d.call_date)),
            datasets: [
                {
                    label: 'Toplam Gelen Arama',
                    data: dailyTrendsData.map(d => d.total_calls),
                    borderColor: colors.primary,
                    backgroundColor: colors.primaryLight,
                    borderWidth: 3,
                    fill: true,
                    tension: 0.4
                },
                {
                    label: 'Cevaplanan',
                    data: dailyTrendsData.map(d => d.total_answered),
                    borderColor: colors.success,
                    backgroundColor: colors.successLight,
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4
                },
                {
                    label: 'Cevaplanmayan',
                    data: dailyTrendsData.map(d => d.total_unanswered),
                    borderColor: colors.danger,
                    backgroundColor: colors.dangerLight,
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    mode: 'index',
                    intersect: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        precision: 0
                    }
                }
            }
        }
    });
}

// 2. Günlük Konuşma Süresi Grafiği (Efektli Line)
const dailyDurationCtx = document.getElementById('dailyDurationChart');
if (dailyDurationCtx && dailyTrendsData.length > 0) {
    // Gradient oluşturma
    const ctx = dailyDurationCtx.getContext('2d');
    const gradient = ctx.createLinearGradient(0, 0, 0, 300);
    gradient.addColorStop(0, 'rgba(155, 89, 182, 0.5)');
    gradient.addColorStop(0.5, 'rgba(155, 89, 182, 0.25)');
    gradient.addColorStop(1, 'rgba(155, 89, 182, 0.05)');

    new Chart(dailyDurationCtx, {
        type: 'line',
        data: {
            labels: dailyTrendsData.map(d => formatDate(d.call_date)),
            datasets: [{
                label: 'Konuşma Süresi',
                data: dailyTrendsData.map(d => parseFloat(d.total_duration_hours)),
                backgroundColor: gradient,
                borderColor: colors.purple,
                borderWidth: 4,
                fill: true,
                tension: 0.4,
                pointRadius: 6,
                pointHoverRadius: 8,
                pointBackgroundColor: '#fff',
                pointBorderColor: colors.purple,
                pointBorderWidth: 3,
                pointHoverBackgroundColor: colors.purple,
                pointHoverBorderColor: '#fff',
                pointHoverBorderWidth: 3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    titleFont: {
                        size: 14,
                        weight: 'bold'
                    },
                    bodyFont: {
                        size: 13
                    },
                    callbacks: {
                        label: function(context) {
                            return '⏱️ ' + formatHoursToDuration(context.parsed.y);
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)',
                        drawBorder: false
                    },
                    ticks: {
                        callback: function(value) {
                            return formatHoursToDuration(value);
                        },
                        font: {
                            size: 12
                        },
                        color: '#666'
                    }
                },
                x: {
                    grid: {
                        display: false,
                        drawBorder: false
                    },
                    ticks: {
                        font: {
                            size: 11
                        },
                        color: '#666'
                    }
                }
            }
        }
    });
}

// 3. En Çok Aranan Personeller (Stacked Bar Chart - 6 Personel)
const topPerformersCtx = document.getElementById('topPerformersChart');
if (topPerformersCtx && topPerformersData.length > 0) {
    new Chart(topPerformersCtx, {
        type: 'bar',
        data: {
            labels: topPerformersData.map(d => d.full_name),
            datasets: [
                {
                    label: 'Cevaplanan',
                    data: topPerformersData.map(d => d.total_answered),
                    backgroundColor: colors.success,
                    borderWidth: 0,
                    borderRadius: {
                        topLeft: 0,
                        topRight: 0,
                        bottomLeft: 8,
                        bottomRight: 8
                    }
                },
                {
                    label: 'Cevaplanmayan',
                    data: topPerformersData.map(d => d.total_unanswered),
                    backgroundColor: colors.danger,
                    borderWidth: 0,
                    borderRadius: {
                        topLeft: 8,
                        topRight: 8,
                        bottomLeft: 0,
                        bottomRight: 0
                    }
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'top',
                    labels: {
                        font: {
                            size: 13,
                            weight: 'bold'
                        },
                        padding: 15,
                        usePointStyle: true,
                        boxWidth: 12,
                        boxHeight: 12
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    padding: 12,
                    titleFont: {
                        size: 14,
                        weight: 'bold'
                    },
                    bodyFont: {
                        size: 13
                    },
                    callbacks: {
                        label: function(context) {
                            const personIndex = context.dataIndex;
                            const totalCalls = topPerformersData[personIndex].total_calls;
                            return ' ' + context.dataset.label + ': ' + context.parsed.y.toLocaleString() + ' / Toplam: ' + totalCalls.toLocaleString();
                        },
                        footer: function(tooltipItems) {
                            if (tooltipItems.length > 0) {
                                const personIndex = tooltipItems[0].dataIndex;
                                const totalCalls = topPerformersData[personIndex].total_calls;
                                return '━━━━━━━━━━━━━━━━\nToplam Gelen Arama: ' + totalCalls.toLocaleString();
                            }
                            return '';
                        }
                    }
                }
            },
            scales: {
                y: {
                    stacked: true,
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)',
                        drawBorder: false
                    },
                    ticks: {
                        precision: 0,
                        font: {
                            size: 12
                        },
                        color: '#666'
                    }
                },
                x: {
                    stacked: true,
                    grid: {
                        display: false,
                        drawBorder: false
                    },
                    ticks: {
                        font: {
                            size: 11,
                            weight: '600'
                        },
                        color: '#2c3e50'
                    }
                }
            }
        }
    });
}

// 4. En Çok Konuşan Personeller
const topDurationCtx = document.getElementById('topDurationChart');
if (topDurationCtx && topPerformersData.length > 0) {
    new Chart(topDurationCtx, {
        type: 'bar',
        data: {
            labels: topPerformersData.map(d => d.full_name),
            datasets: [{
                label: 'Konuşma Süresi',
                data: topPerformersData.map(d => parseFloat(d.total_duration_hours)),
                backgroundColor: colors.warning,
                borderColor: colors.warning,
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: 'y',
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return formatHoursToDuration(context.parsed.x);
                        }
                    }
                }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return formatHoursToDuration(value);
                        }
                    }
                }
            }
        }
    });
}
</script>

<?php include 'includes/footer.php'; ?>
