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

Auth::requireAdmin(); // Sadece yöneticiler erişebilir

$pageTitle = 'Yönetici Raporları';
include 'includes/header.php';

$db = new Database();

// bonus.php ile aynı mantık: kriterin tarihe göre değerini al
function getCriteriaValueForDate_reports($db, $criteriaCode, $date) {
    $historyValue = $db->fetchOne("
        SELECT point_value FROM criteria_history
        WHERE criteria_code = ?
          AND start_date <= ?
          AND (end_date IS NULL OR end_date >= ?)
        ORDER BY start_date DESC LIMIT 1
    ", [$criteriaCode, $date, $date]);
    if ($historyValue && isset($historyValue['point_value'])) {
        return $historyValue['point_value'];
    }
    $defaultValue = $db->fetchOne("SELECT point_value FROM criteria WHERE code = ?", [$criteriaCode]);
    return ($defaultValue && isset($defaultValue['point_value'])) ? $defaultValue['point_value'] : 0;
}

// Varsayılan tarih aralığı: Son verinin olduğu ay
$lastDataQuery = "SELECT MAX(call_date) as last_date FROM incoming_calls";
$lastData = $db->fetchOne($lastDataQuery);
$lastDate = $lastData['last_date'] ?? date('Y-m-d');

$currentMonth = date('Y-m', strtotime($lastDate));
$startDate = date('Y-m-01', strtotime($lastDate));
$endDate = date('Y-m-t', strtotime($lastDate));

// Eğer varsayılan olarak bu ay yüklendiyse ve ay henüz bitmemişse, bugünü kullan
$today = date('Y-m-d');
$currentMonthNow = date('Y-m');
if (date('Y-m', strtotime($endDate)) === $currentMonthNow && $endDate > $today) {
    $endDate = $today;
}

// Hızlı filtre kontrolü
$quickFilter = $_GET['quick_filter'] ?? '';
if ($quickFilter) {
    if (strpos($quickFilter, 'month_') === 0) {
        $monthOffset = (int)str_replace('month_', '', $quickFilter);
        $startDate = date('Y-m-01', strtotime("$monthOffset months"));
        $tempEndDate = date('Y-m-t', strtotime("$monthOffset months"));

        // Eğer bu ay seçiliyse (offset = 0) ve ay henüz bitmemişse, bugünü kullan
        if ($monthOffset === 0 && $tempEndDate > $today) {
            $endDate = $today;
        } else {
            $endDate = $tempEndDate;
        }
    } elseif ($quickFilter === 'last_3_months') {
        $startDate = date('Y-m-01', strtotime('-2 months'));
        $tempEndDate = date('Y-m-t');
        // Son 3 ay için de bugünü kontrol et
        if ($tempEndDate > $today) {
            $endDate = $today;
        } else {
            $endDate = $tempEndDate;
        }
    }
} elseif (isset($_GET['start_date']) && isset($_GET['end_date'])) {
    // Manuel tarih filtresi
    $startDate = $_GET['start_date'];
    $endDate = $_GET['end_date'];
}

// Çalışan filtresi
$selectedUserId = $_GET['user_id'] ?? '';

// Aktif kullanıcıları getir
$usersQuery = "SELECT id, full_name, extension FROM users WHERE is_active = 1 ORDER BY full_name";
$users = $db->fetchAll($usersQuery);

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

// Geçmiş 12 ayı getir (hızlı filtre için)
$months = [];
for ($i = 0; $i >= -11; $i--) {
    $monthDate = strtotime("$i months");
    $monthNum = (int)date('n', $monthDate); // 1-12
    $year = date('Y', $monthDate);
    $months[] = [
        'value' => "month_$i",
        'label' => $turkishMonths[$monthNum] . ' ' . $year,
        'start' => date('Y-m-01', $monthDate),
        'end' => date('Y-m-t', $monthDate)
    ];
}

// ============ VERİ SORGULARI ============

// 1. GENEL İSTATİSTİKLER (Stat Cards için)
$statsQuery = "
    SELECT
        COUNT(DISTINCT ic.user_id) as active_users,
        SUM(ic.answered_count) as total_incoming_calls,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_incoming_duration,
        AVG(ic.answer_percentage) as avg_answer_rate
    FROM incoming_calls ic
    WHERE ic.call_date BETWEEN :start_date AND :end_date
";
if ($selectedUserId) {
    $statsQuery .= " AND ic.user_id = :user_id";
}

$params = ['start_date' => $startDate, 'end_date' => $endDate];
if ($selectedUserId) {
    $params['user_id'] = $selectedUserId;
}
$stats = $db->fetchOne($statsQuery, $params);

// Giden çağrı istatistikleri
$outgoingStatsQuery = "
    SELECT
        SUM(call_count) as total_outgoing_calls,
        SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_outgoing_duration
    FROM outgoing_calls
    WHERE call_date BETWEEN :start_date AND :end_date
";
if ($selectedUserId) {
    $outgoingStatsQuery .= " AND user_id = :user_id";
}
$outgoingStats = $db->fetchOne($outgoingStatsQuery, $params);

// Eğitim tamamlama istatistikleri
$trainingStatsQuery = "
    SELECT COUNT(*) as total_trainings
    FROM training_completion
    WHERE training_completion_date BETWEEN :start_date AND :end_date
";
if ($selectedUserId) {
    $trainingStatsQuery .= " AND support_representative IN (SELECT full_name FROM users WHERE id = :user_id)";
}
$trainingStats = $db->fetchOne($trainingStatsQuery, $params);

// 2. ÇALIŞAN BAZINDA PERFORMANS (Tablo ve Grafik için)
// Subquery kullanarak tarih filtresini doğru uygulayalım
$performanceQuery = "
    SELECT
        u.id,
        u.full_name,
        u.extension,
        u.role,
        COALESCE(ic_sum.total_answered, 0) as total_answered,
        COALESCE(ic_sum.total_unanswered, 0) as total_unanswered,
        COALESCE(ic_sum.avg_answer_rate, 0) as avg_answer_rate,
        COALESCE(ic_sum.total_incoming_duration, '00:00:00') as total_incoming_duration,
        COALESCE(oc_sum.total_outgoing, 0) as total_outgoing,
        COALESCE(oc_sum.total_outgoing_duration, '00:00:00') as total_outgoing_duration
    FROM users u
    LEFT JOIN (
        SELECT
            user_id,
            SUM(answered_count) as total_answered,
            SUM(unanswered_count) as total_unanswered,
            AVG(answer_percentage) as avg_answer_rate,
            SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_incoming_duration
        FROM incoming_calls
        WHERE call_date BETWEEN :start_date AND :end_date
        GROUP BY user_id
    ) ic_sum ON u.id = ic_sum.user_id
    LEFT JOIN (
        SELECT
            user_id,
            SUM(call_count) as total_outgoing,
            SEC_TO_TIME(SUM(TIME_TO_SEC(total_duration))) as total_outgoing_duration
        FROM outgoing_calls
        WHERE call_date BETWEEN :start_date2 AND :end_date2
        GROUP BY user_id
    ) oc_sum ON u.id = oc_sum.user_id
    WHERE u.is_active = 1
";
if ($selectedUserId) {
    $performanceQuery .= " AND u.id = :user_id";
}
$performanceQuery .= " ORDER BY total_answered DESC";

$performanceParams = [
    'start_date' => $startDate,
    'end_date' => $endDate,
    'start_date2' => $startDate,
    'end_date2' => $endDate
];
if ($selectedUserId) {
    $performanceParams['user_id'] = $selectedUserId;
}
$performanceData = $db->fetchAll($performanceQuery, $performanceParams);

// Eğitim verilerini ekle
foreach ($performanceData as &$performance) {
    $trainingCountQuery = "
        SELECT COUNT(*) as training_count
        FROM training_completion
        WHERE support_representative = :full_name
        AND training_completion_date BETWEEN :start_date AND :end_date
    ";
    $trainingCount = $db->fetchOne($trainingCountQuery, [
        'full_name' => $performance['full_name'],
        'start_date' => $startDate,
        'end_date' => $endDate
    ]);
    $performance['training_count'] = $trainingCount['training_count'] ?? 0;
}
unset($performance);

// 3. AYLIK TREND VERİLERİ (Line Chart için)
// 6 ay öncesini PHP'de hesapla
$sixMonthsAgo = date('Y-m-01', strtotime('-6 months', strtotime($endDate)));

$trendQuery = "
    SELECT
        DATE_FORMAT(call_date, '%Y-%m') as month,
        SUM(answered_count) as total_calls,
        COUNT(DISTINCT user_id) as active_users
    FROM incoming_calls
    WHERE call_date >= :six_months_ago
    AND call_date <= :end_date
";
if ($selectedUserId) {
    $trendQuery .= " AND user_id = :user_id";
}
$trendQuery .= " GROUP BY DATE_FORMAT(call_date, '%Y-%m') ORDER BY month ASC";

$trendParams = [
    'six_months_ago' => $sixMonthsAgo,
    'end_date' => $endDate
];
if ($selectedUserId) {
    $trendParams['user_id'] = $selectedUserId;
}
$trendData = $db->fetchAll($trendQuery, $trendParams);

// 4. PAKET TÜRÜ DAĞILIMI (Eğitim verileri)
$packageQuery = "
    SELECT
        package_type,
        COUNT(*) as count
    FROM training_completion
    WHERE training_completion_date BETWEEN :start_date AND :end_date
";
if ($selectedUserId) {
    $packageQuery .= " AND support_representative IN (SELECT full_name FROM users WHERE id = :user_id)";
}
$packageQuery .= " GROUP BY package_type ORDER BY count DESC";
$packageData = $db->fetchAll($packageQuery, $params);

// 5. GÜNLÜK AKTİVİTE (Son 30 gün)
// 30 gün öncesini PHP'de hesapla
$thirtyDaysAgo = date('Y-m-d', strtotime('-30 days', strtotime($endDate)));

// Tüm tarihleri al (boş günler için)
$activityQuery = "
    SELECT
        d.date as call_date,
        COALESCE(ic.daily_incoming, 0) as daily_incoming,
        COALESCE(oc.daily_outgoing, 0) as daily_outgoing
    FROM (
        SELECT DISTINCT call_date as date
        FROM incoming_calls
        WHERE call_date >= :thirty_days_ago AND call_date <= :end_date
        UNION
        SELECT DISTINCT call_date as date
        FROM outgoing_calls
        WHERE call_date >= :thirty_days_ago2 AND call_date <= :end_date2
    ) d
    LEFT JOIN (
        SELECT call_date, SUM(answered_count) as daily_incoming
        FROM incoming_calls
        WHERE call_date >= :thirty_days_ago3 AND call_date <= :end_date3
        " . ($selectedUserId ? " AND user_id = :user_id_ic" : "") . "
        GROUP BY call_date
    ) ic ON d.date = ic.call_date
    LEFT JOIN (
        SELECT call_date, SUM(call_count) as daily_outgoing
        FROM outgoing_calls
        WHERE call_date >= :thirty_days_ago4 AND call_date <= :end_date4
        " . ($selectedUserId ? " AND user_id = :user_id_oc" : "") . "
        GROUP BY call_date
    ) oc ON d.date = oc.call_date
    ORDER BY d.date ASC
";

$activityParams = [
    'thirty_days_ago' => $thirtyDaysAgo,
    'end_date' => $endDate,
    'thirty_days_ago2' => $thirtyDaysAgo,
    'end_date2' => $endDate,
    'thirty_days_ago3' => $thirtyDaysAgo,
    'end_date3' => $endDate,
    'thirty_days_ago4' => $thirtyDaysAgo,
    'end_date4' => $endDate
];
if ($selectedUserId) {
    $activityParams['user_id_ic'] = $selectedUserId;
    $activityParams['user_id_oc'] = $selectedUserId;
}
$activityData = $db->fetchAll($activityQuery, $activityParams);

// Grafik verilerini JSON formatına çevir (integer'a dönüştür)
$performanceLabels = array_column($performanceData, 'full_name');
$performanceIncoming = array_map('intval', array_column($performanceData, 'total_answered'));
$performanceOutgoing = array_map('intval', array_column($performanceData, 'total_outgoing'));
$performanceTraining = array_map('intval', array_column($performanceData, 'training_count'));

// Süreleri dakikaya çevir (TIME formatından)
$performanceIncomingDuration = array_map(function($item) {
    if (empty($item['total_incoming_duration']) || $item['total_incoming_duration'] === '00:00:00') return 0;
    list($hours, $minutes, $seconds) = explode(':', $item['total_incoming_duration']);
    return round(($hours * 60) + $minutes + ($seconds / 60));
}, $performanceData);

$performanceOutgoingDuration = array_map(function($item) {
    if (empty($item['total_outgoing_duration']) || $item['total_outgoing_duration'] === '00:00:00') return 0;
    list($hours, $minutes, $seconds) = explode(':', $item['total_outgoing_duration']);
    return round(($hours * 60) + $minutes + ($seconds / 60));
}, $performanceData);

$trendLabels = array_column($trendData, 'month');
$trendValues = array_map('intval', array_column($trendData, 'total_calls'));

$packageLabels = array_column($packageData, 'package_type');
$packageValues = array_map('intval', array_column($packageData, 'count'));

$activityLabels = array_map(function($item) {
    return date('d/m', strtotime($item['call_date']));
}, $activityData);
$activityIncoming = array_map('intval', array_column($activityData, 'daily_incoming'));
$activityOutgoing = array_map('intval', array_column($activityData, 'daily_outgoing'));

// ============ INSIGHTS HESAPLAMALARI ============

// En iyi performans gösterenler
$topPerformer = !empty($performanceData) ? $performanceData[0] : null;
$topByDuration = null;
$maxDuration = 0;
$topAnswerRate = null;
$maxAnswerRate = 0;

foreach ($performanceData as $perf) {
    // En uzun konuşan
    if (!empty($perf['total_incoming_duration']) && $perf['total_incoming_duration'] !== '00:00:00') {
        list($h, $m, $s) = explode(':', $perf['total_incoming_duration']);
        $totalMin = ($h * 60) + $m;
        if ($totalMin > $maxDuration) {
            $maxDuration = $totalMin;
            $topByDuration = $perf;
        }
    }

    // En yüksek yanıt oranı
    if ($perf['avg_answer_rate'] > $maxAnswerRate && $perf['total_answered'] > 0) {
        $maxAnswerRate = $perf['avg_answer_rate'];
        $topAnswerRate = $perf;
    }
}

// Ortalama metrikler
$avgIncoming = !empty($performanceData) ? round(array_sum($performanceIncoming) / count($performanceData)) : 0;
$avgOutgoing = !empty($performanceData) ? round(array_sum($performanceOutgoing) / count($performanceData)) : 0;
$avgTraining = !empty($performanceData) ? round(array_sum($performanceTraining) / count($performanceData)) : 0;

// Bir önceki dönem karşılaştırması (trend)
// Bugünün tarihine göre karşılaştırma yap
$today = date('Y-m-d');
$currentMonthStart = date('Y-m-01', strtotime($endDate));
$currentMonthEnd = date('Y-m-t', strtotime($endDate));

// Eğer seçilen dönem mevcut ayı içeriyorsa veya mevcut aya kadarsa, gün bazlı karşılaştır
if ($endDate >= $currentMonthStart && $endDate <= $today) {
    // Bugünün ayın kaçıncı günü olduğunu bul
    $dayOfMonth = (int)date('d', strtotime($endDate));

    // Önceki ay için aynı gün aralığını kullan
    $prevMonthStart = date('Y-m-01', strtotime('-1 month', strtotime($endDate)));
    $prevMonthSameDay = date('Y-m-d', strtotime($prevMonthStart . ' +' . ($dayOfMonth - 1) . ' days'));

    $prevStartDate = $prevMonthStart;
    $prevEndDate = $prevMonthSameDay;
} else {
    // Normal karşılaştırma (ay tamamlanmışsa)
    $prevStartDate = date('Y-m-01', strtotime('-1 month', strtotime($startDate)));
    $prevEndDate = date('Y-m-t', strtotime('-1 month', strtotime($endDate)));
}

$prevStatsQuery = "
    SELECT SUM(answered_count) as total_calls
    FROM incoming_calls
    WHERE call_date BETWEEN :start_date AND :end_date
";
$prevStats = $db->fetchOne($prevStatsQuery, ['start_date' => $prevStartDate, 'end_date' => $prevEndDate]);
$prevTotalCalls = $prevStats['total_calls'] ?? 0;
$currentTotalCalls = $stats['total_incoming_calls'] ?? 0;

$callsTrend = 0;
if ($prevTotalCalls > 0) {
    $callsTrend = round((($currentTotalCalls - $prevTotalCalls) / $prevTotalCalls) * 100, 1);
}

// ============ YILLIK PERSONEL PERFORMANS RAPORU ============

// Yıl seçimi (varsayılan: bu yıl)
$selectedYearForReport = $_GET['report_year'] ?? date('Y');

// Son 3 yılı listele
$availableYears = [];
for ($y = (int)date('Y'); $y >= (int)date('Y') - 2; $y--) {
    $availableYears[] = $y;
}

// Helper fonksiyonlar
function packageMatches_report($packageName, $searchName) {
    $pkg = strtolower($packageName);
    $search = strtolower($searchName);
    return (stripos($pkg, $search) !== false || stripos($search, $pkg) !== false);
}

// Oransal ve bonus paket tanımları
$proportionalPackages_report = [
    'Profesyonel Paket' => 1.0,
    'Gelişmiş Paket' => 1.0,
    'Uzman Paket' => 1.0,
    'Ideasoft Mini 2' => 1.0,
    'Ideasoft Mini 3' => 1.0,
    'Ideasoft Maksi' => 1.0,
    'Ideasoft ERP' => 0.5
];

$bonusPackages_report = [
    'Sopyo Logo' => 1.0,
    'Sopyo Nebim' => 1.0,
    'Sopyo Nebim v3' => 1.0,
    'Lisans Yenileme' => 0.25,
    'Google Yorum' => 1.0
];

// 12 ay için her personelin toplam puanını hesapla
$yearlyScores = [];
$personnelYearlyTotals = [];

// Aktif personel listesi (sadece personel - yöneticiler hariç)
$activePersonnel = $db->fetchAll("
    SELECT id, full_name, role
    FROM users
    WHERE is_active = 1 AND role = 'personel'
    ORDER BY full_name ASC
");

// Her personel için toplam puanları sıfırla
foreach ($activePersonnel as $person) {
    $personnelYearlyTotals[$person['full_name']] = 0;
}

// 12 ay için döngü
for ($month = 1; $month <= 12; $month++) {
    $monthStartDate = sprintf('%04d-%02d-01', $selectedYearForReport, $month);
    $monthEndDate = date('Y-m-t', strtotime($monthStartDate));

    // Gelecek ayları hesaplama
    if (strtotime($monthStartDate) > time()) {
        continue;
    }

    // Snapshot'tan kriterleri çek
    $monthlyCriteria = $db->fetchAll("
        SELECT criteria_code as code, point_value
        FROM criteria_snapshots
        WHERE year = ? AND month = ?
    ", [$selectedYearForReport, $month]);

    // Eğer snapshot yoksa varsayılan kriterleri kullan
    if (empty($monthlyCriteria)) {
        $monthlyCriteria = $db->fetchAll("
            SELECT code, point_value
            FROM criteria
            WHERE is_active = 1
        ");
    }

    // Kriterleri array'e çevir
    $criteriaPoints_report = [];
    foreach ($monthlyCriteria as $crit) {
        $criteriaPoints_report[$crit['code']] = $crit['point_value'];
    }

    // Her personel için aylık veri topla
    $monthlyData = [];
    $monthlyTotals = [
        'incoming_calls' => 0,
        'incoming_duration' => 0,
        'outgoing_calls' => 0,
        'outgoing_duration' => 0,
        'support_messages' => 0
    ];
    $monthlyProportionalWeighted = 0;

    foreach ($activePersonnel as $person) {
        $userId = $person['id'];
        $fullName = $person['full_name'];

        // Gelen aramalar
        $incomingPerf = $db->fetchOne("
            SELECT
                COALESCE(SUM(answered_count), 0) as total_answered,
                COALESCE(SUM(TIME_TO_SEC(total_duration)), 0) as total_duration_seconds
            FROM incoming_calls
            WHERE user_id = ? AND call_date BETWEEN ? AND ?
        ", [$userId, $monthStartDate, $monthEndDate]);

        $incomingCalls = (int)($incomingPerf['total_answered'] ?? 0);
        $incomingDuration = (int)($incomingPerf['total_duration_seconds'] ?? 0);

        // Giden aramalar
        $outgoingPerf = $db->fetchOne("
            SELECT
                COALESCE(SUM(answered_count), 0) as total_answered,
                COALESCE(SUM(TIME_TO_SEC(total_duration)), 0) as total_duration_seconds
            FROM outgoing_calls
            WHERE user_id = ? AND call_date BETWEEN ? AND ?
        ", [$userId, $monthStartDate, $monthEndDate]);

        $outgoingCalls = (int)($outgoingPerf['total_answered'] ?? 0);
        $outgoingDuration = (int)($outgoingPerf['total_duration_seconds'] ?? 0);

        // Paket bazlı eğitim sayıları
        $trainingStats = $db->fetchAll("
            SELECT package_type, COUNT(*) as count
            FROM training_completion
            WHERE support_representative = ?
            AND training_completion_date BETWEEN ? AND ?
            GROUP BY package_type
        ", [$fullName, $monthStartDate, $monthEndDate]);

        $packageCounts = [];
        foreach ($trainingStats as $training) {
            $packageCounts[$training['package_type']] = (int)$training['count'];
        }

        // Destek mesajları
        $supportMsgData = $db->fetchOne("
            SELECT COALESCE(SUM(message_count), 0) as total_messages
            FROM support_messages
            WHERE user_id = ? AND message_date BETWEEN ? AND ?
        ", [$userId, $monthStartDate, $monthEndDate]);
        $supportMessages = (int)($supportMsgData['total_messages'] ?? 0);

        $monthlyData[$fullName] = [
            'incoming_calls' => $incomingCalls,
            'incoming_duration' => $incomingDuration,
            'outgoing_calls' => $outgoingCalls,
            'outgoing_duration' => $outgoingDuration,
            'package_counts' => $packageCounts,
            'support_messages' => $supportMessages
        ];

        // Toplamları hesapla (yöneticiler zaten sorgudan çıkarıldı)
        $monthlyTotals['incoming_calls'] += $incomingCalls;
        $monthlyTotals['incoming_duration'] += $incomingDuration;
        $monthlyTotals['outgoing_calls'] += $outgoingCalls;
        $monthlyTotals['outgoing_duration'] += $outgoingDuration;
        $monthlyTotals['support_messages'] += $supportMessages;

        // Oransal paketlerin ağırlıklı toplamı
        foreach ($packageCounts as $pkgName => $count) {
            foreach ($proportionalPackages_report as $propPkgName => $weight) {
                if (packageMatches_report($pkgName, $propPkgName)) {
                    $monthlyProportionalWeighted += $count * $weight;
                    break;
                }
            }
        }
    }

    // Her personel için puanları hesapla
    foreach ($activePersonnel as $person) {
        $fullName = $person['full_name'];
        $data = $monthlyData[$fullName];

        // Gelen arama sayısı puanı
            $scoreIncomingCalls = $monthlyTotals['incoming_calls'] > 0
                ? ($data['incoming_calls'] / $monthlyTotals['incoming_calls']) * ($criteriaPoints_report['gelen_arama_sayisi'] ?? 0)
                : 0;

            // Gelen konuşma süresi puanı
            $scoreIncomingDuration = $monthlyTotals['incoming_duration'] > 0
                ? ($data['incoming_duration'] / $monthlyTotals['incoming_duration']) * ($criteriaPoints_report['gelen_arama_suresi'] ?? 0)
                : 0;

            // Giden arama sayısı puanı
            $scoreOutgoingCalls = $monthlyTotals['outgoing_calls'] > 0
                ? ($data['outgoing_calls'] / $monthlyTotals['outgoing_calls']) * ($criteriaPoints_report['giden_arama_sayisi'] ?? 0)
                : 0;

            // Giden konuşma süresi puanı
            $scoreOutgoingDuration = $monthlyTotals['outgoing_duration'] > 0
                ? ($data['outgoing_duration'] / $monthlyTotals['outgoing_duration']) * ($criteriaPoints_report['giden_arama_suresi'] ?? 0)
                : 0;

            // Oransal paketler puanı
            $personelProportionalWeighted = 0;
            foreach ($data['package_counts'] as $pkgName => $count) {
                foreach ($proportionalPackages_report as $propPkgName => $weight) {
                    if (packageMatches_report($pkgName, $propPkgName)) {
                        $personelProportionalWeighted += $count * $weight;
                        break;
                    }
                }
            }

            $scoreProportionalPackages = $monthlyProportionalWeighted > 0
                ? ($personelProportionalWeighted / $monthlyProportionalWeighted) * ($criteriaPoints_report['egitim_orani'] ?? 0)
                : 0;

            // Bonus paketler puanı
            $scoreBonusPackages = 0;
            foreach ($data['package_counts'] as $pkgName => $count) {
                foreach ($bonusPackages_report as $bonusPkgName => $bonusPoint) {
                    if (packageMatches_report($pkgName, $bonusPkgName)) {
                        $scoreBonusPackages += $count * $bonusPoint;
                        break;
                    }
                }
            }

        // Destek mesajı puanı
        $scoreDestek = $monthlyTotals['support_messages'] > 0
            ? ($data['support_messages'] / $monthlyTotals['support_messages']) * ($criteriaPoints_report['destek_mesaj_sayisi'] ?? 0)
            : 0;

        // Toplam puan
        $totalScore = $scoreIncomingCalls + $scoreIncomingDuration +
                     $scoreOutgoingCalls + $scoreOutgoingDuration +
                     $scoreProportionalPackages + $scoreBonusPackages + $scoreDestek;

        // Aylık puanı ve paket verilerini kaydet
        if (!isset($yearlyScores[$fullName])) {
            $yearlyScores[$fullName] = [];
        }
        $yearlyScores[$fullName][$month] = [
            'total_score' => round($totalScore, 2),
            'package_counts' => $data['package_counts'],
            'score_bonus_packages' => $scoreBonusPackages
        ];

        // Yıllık toplama ekle
        $personnelYearlyTotals[$fullName] += $totalScore;
    }
}

// Yıllık toplamları büyükten küçüğe sırala (en iyi performanslar)
arsort($personnelYearlyTotals);

// En iyi 3 personel
$topPerformers = array_slice($personnelYearlyTotals, 0, 3, true);

// Grafik için veri hazırlama
$monthlyLabels = [];
for ($m = 1; $m <= 12; $m++) {
    $monthlyLabels[] = $turkishMonths[$m];
}

// Her personel için 12 aylık veri dizisi
$personnelMonthlyData = [];
$personnelColors = [
    'rgba(102, 126, 234, 0.8)',
    'rgba(240, 147, 251, 0.8)',
    'rgba(67, 233, 123, 0.8)',
    'rgba(79, 172, 254, 0.8)',
    'rgba(250, 112, 154, 0.8)',
    'rgba(254, 202, 87, 0.8)',
    'rgba(99, 179, 237, 0.8)',
    'rgba(255, 159, 64, 0.8)'
];

$colorIndex = 0;
foreach ($yearlyScores as $personName => $monthlyScores) {
    $monthlyValues = [];
    for ($m = 1; $m <= 12; $m++) {
        // Artık monthlyScores bir array, total_score'u al
        $monthlyValues[] = isset($monthlyScores[$m])
            ? (is_array($monthlyScores[$m]) ? $monthlyScores[$m]['total_score'] : $monthlyScores[$m])
            : 0;
    }

    $personnelMonthlyData[] = [
        'name' => $personName,
        'data' => $monthlyValues,
        'color' => $personnelColors[$colorIndex % count($personnelColors)],
        'yearlyTotal' => $personnelYearlyTotals[$personName]
    ];

    $colorIndex++;
}

// Personel verilerini yıllık toplam puana göre büyükten küçüğe sırala
usort($personnelMonthlyData, function($a, $b) {
    return $b['yearlyTotal'] <=> $a['yearlyTotal'];
});

// En yüksek puanı bul (yüzde hesaplaması için)
$maxYearlyScore = !empty($personnelMonthlyData) ? $personnelMonthlyData[0]['yearlyTotal'] : 0;

// Her personel için yüzdeyi hesapla
foreach ($personnelMonthlyData as &$pData) {
    $pData['percentageOfMax'] = $maxYearlyScore > 0 ? ($pData['yearlyTotal'] / $maxYearlyScore) * 100 : 0;
}
unset($pData);

// ============ AYLIK PRİM HESAPLAMALARI ============

// Personel maaşlarını al
$personnelSalaries = [];
foreach ($activePersonnel as $person) {
    $salaryData = $db->fetchOne("SELECT salary FROM users WHERE id = ?", [$person['id']]);
    $personnelSalaries[$person['full_name']] = $salaryData['salary'] ?? 0;
}

// Her ay için prim hesapla (bonus.php ile aynı mantık)
$monthlyBonusData = [];

// 50 TL'ye yuvarlama fonksiyonu (bonus.php ile aynı)
if (!function_exists('roundToNearestFifty')) {
    function roundToNearestFifty($amount) {
        // Tam sayı kısmını al
        $intAmount = floor($amount);

        // 50'e bölümünden kalanı bul
        $remainder = $intAmount % 50;

        // Eğer tam 50'nin katıysa ve ondalık kısım yoksa olduğu gibi dön
        if ($remainder == 0 && $amount == $intAmount) {
            return $intAmount;
        }

        // Aksi halde HER ZAMAN bir sonraki 50'lik dilime yukarı yuvarla
        // Örnek: 1911₺ → 1950₺
        // Örnek: 1901₺ → 1950₺
        // Örnek: 1950₺ → 1950₺ (tam 50'nin katı)
        return $intAmount + (50 - $remainder);
    }
}

for ($month = 1; $month <= 12; $month++) {
    $monthStartDate = sprintf('%04d-%02d-01', $selectedYearForReport, $month);
    $monthEndDate = date('Y-m-t', strtotime($monthStartDate));

    // Gelecek ayları hesaplama
    if (strtotime($monthStartDate) > time()) {
        continue;
    }

    // O ay için prim tutarını al (bonus.php ile aynı: criteria_history'ye bak, yoksa criteria tablosu)
    $monthRefDate = sprintf('%04d-%02d-15', $selectedYearForReport, $month);
    $primTutari = getCriteriaValueForDate_reports($db, 'prim_tutari', $monthRefDate);

    // O ay için maksimum teorik puanı hesapla (criteria toplamı)
    $criteriaRows = $db->fetchAll("
        SELECT point_value FROM criteria_snapshots
        WHERE year = ? AND month = ? AND criteria_code IN ('gelen_arama_sayisi', 'gelen_arama_suresi', 'giden_arama_sayisi', 'giden_arama_suresi', 'egitim_orani')
    ", [$selectedYearForReport, $month]);

    if (empty($criteriaRows)) {
        $criteriaRows = $db->fetchAll("
            SELECT point_value FROM criteria
            WHERE code IN ('gelen_arama_sayisi', 'gelen_arama_suresi', 'giden_arama_sayisi', 'giden_arama_suresi', 'egitim_orani') AND is_active = 1
        ");
    }

    $maxTheoreticalScore = 0;
    foreach ($criteriaRows as $row) {
        $maxTheoreticalScore += $row['point_value'];
    }

    if ($maxTheoreticalScore == 0) {
        $maxTheoreticalScore = 100; // Fallback
    }

    // O ay için personel puanlarını al
    $monthScoresForBonus = [];
    foreach ($personnelMonthlyData as $pData) {
        $monthScoresForBonus[$pData['name']] = $pData['data'][$month - 1];
    }

    // Sıralama yap (büyükten küçüğe)
    arsort($monthScoresForBonus);
    $sortedPersonnel = array_keys($monthScoresForBonus);

    // En az 4 personel varsa prim hesapla
    if (count($sortedPersonnel) >= 4 && $primTutari > 0) {
        // Top 3 ve en düşük kişiyi belirle
        $topThree = array_slice($sortedPersonnel, 0, 3);
        $lowestPerson = $sortedPersonnel[count($sortedPersonnel) - 1];
        $highestPerson = $sortedPersonnel[0];

        $lowestScore = $monthScoresForBonus[$lowestPerson];

        // 4 kişinin toplam puanını hesapla (TÜM personellerin puanları)
        $totalScoreOfFour = 0;
        foreach ($monthScoresForBonus as $score) {
            $totalScoreOfFour += $score;
        }

        // Achievement rate hesapla
        $achievementRate = $maxTheoreticalScore > 0 ? ($totalScoreOfFour / $maxTheoreticalScore) * 100 : 0;

        // Eksik kalan yüzde
        $missingPercentage = 100 - $achievementRate;

        // 4. kişinin yüzdesi
        $lowestPersonPercentage = $maxTheoreticalScore > 0 ? ($lowestScore / $maxTheoreticalScore) * 100 : 0;

        // En yüksek kişiye eklenecek ekstra bonus yüzdesi
        $extraBonusPercentage = $missingPercentage + $lowestPersonPercentage;

        // Her personel için prim hesapla
        foreach ($sortedPersonnel as $personName) {
            $personScore = $monthScoresForBonus[$personName];

            if (!isset($monthlyBonusData[$personName])) {
                $monthlyBonusData[$personName] = [];
            }

            $isLowest = ($personName === $lowestPerson);
            $isHighest = ($personName === $highestPerson);

            if ($isLowest) {
                // En düşük puanlı kişi prim almaz
                $monthlyBonusData[$personName][$month] = 0;
            } else {
                // Kendi yüzdesi
                $ownPercentage = $maxTheoreticalScore > 0 ? ($personScore / $maxTheoreticalScore) * 100 : 0;

                if ($isHighest) {
                    // En yüksek: kendi yüzdesi + ekstra bonus
                    $bonusPercentage = $ownPercentage + $extraBonusPercentage;
                } else {
                    // Diğerleri sadece kendi yüzdesi
                    $bonusPercentage = $ownPercentage;
                }

                // Prim tutarını hesapla
                $rawAmount = ($bonusPercentage / 100) * $primTutari;

                // 50 TL'lik dilimlere yuvarla
                $bonusAmount = roundToNearestFifty($rawAmount);

                $monthlyBonusData[$personName][$month] = $bonusAmount;
            }
        }
    } else {
        // 4 kişiden az varsa kimse prim almaz
        foreach ($sortedPersonnel as $personName) {
            if (!isset($monthlyBonusData[$personName])) {
                $monthlyBonusData[$personName] = [];
            }
            $monthlyBonusData[$personName][$month] = 0;
        }
    }
}

// Yıllık toplam prim ve gelir hesapla
$yearlyBonusTotals = [];
$yearlyIncomeTotals = [];

foreach ($personnelMonthlyData as $pData) {
    $personName = $pData['name'];
    $yearlySalary = ($personnelSalaries[$personName] ?? 0) * 12; // Yıllık maaş
    $yearlyBonus = 0;

    if (isset($monthlyBonusData[$personName])) {
        $yearlyBonus = array_sum($monthlyBonusData[$personName]);
    }

    $yearlyBonusTotals[$personName] = $yearlyBonus;
    $yearlyIncomeTotals[$personName] = $yearlySalary + $yearlyBonus;
}

// ============ YILLIK ŞAMPIYONLAR (EN'LER) ============

// Yılın en'lerini hesapla
$yearlyChampions = [];

// 1. En çok gelen arama karşılayan
$incomingCallsQuery = "
    SELECT
        u.full_name,
        SUM(ic.answered_count) as total_answered,
        ROUND(SUM(ic.answered_count) / 12, 2) as monthly_avg
    FROM incoming_calls ic
    JOIN users u ON ic.user_id = u.id
    WHERE YEAR(ic.call_date) = :year
    AND u.role = 'personel'
    GROUP BY u.full_name
    ORDER BY total_answered DESC
    LIMIT 1
";
$topIncomingCalls = $db->fetchOne($incomingCallsQuery, ['year' => $selectedYearForReport]);
$yearlyChampions['incoming_calls'] = $topIncomingCalls;

// 2. En çok gelen aramalarda konuşan (süre)
$incomingDurationQuery = "
    SELECT
        u.full_name,
        SEC_TO_TIME(SUM(TIME_TO_SEC(ic.total_duration))) as total_duration,
        ROUND(SUM(TIME_TO_SEC(ic.total_duration)) / 3600, 1) as total_hours,
        ROUND(SUM(TIME_TO_SEC(ic.total_duration)) / 12 / 60, 1) as monthly_avg_minutes
    FROM incoming_calls ic
    JOIN users u ON ic.user_id = u.id
    WHERE YEAR(ic.call_date) = :year
    AND u.role = 'personel'
    GROUP BY u.full_name
    ORDER BY SUM(TIME_TO_SEC(ic.total_duration)) DESC
    LIMIT 1
";
$topIncomingDuration = $db->fetchOne($incomingDurationQuery, ['year' => $selectedYearForReport]);
$yearlyChampions['incoming_duration'] = $topIncomingDuration;

// 3. En çok giden arama yapan
$outgoingCallsQuery = "
    SELECT
        u.full_name,
        SUM(oc.call_count) as total_outgoing,
        ROUND(SUM(oc.call_count) / 12, 2) as monthly_avg
    FROM outgoing_calls oc
    JOIN users u ON oc.user_id = u.id
    WHERE YEAR(oc.call_date) = :year
    AND u.role = 'personel'
    GROUP BY u.full_name
    ORDER BY total_outgoing DESC
    LIMIT 1
";
$topOutgoingCalls = $db->fetchOne($outgoingCallsQuery, ['year' => $selectedYearForReport]);
$yearlyChampions['outgoing_calls'] = $topOutgoingCalls;

// 4. En çok giden aramalarda konuşan (süre)
$outgoingDurationQuery = "
    SELECT
        u.full_name,
        SEC_TO_TIME(SUM(TIME_TO_SEC(oc.total_duration))) as total_duration,
        ROUND(SUM(TIME_TO_SEC(oc.total_duration)) / 3600, 1) as total_hours,
        ROUND(SUM(TIME_TO_SEC(oc.total_duration)) / 12 / 60, 1) as monthly_avg_minutes
    FROM outgoing_calls oc
    JOIN users u ON oc.user_id = u.id
    WHERE YEAR(oc.call_date) = :year
    AND u.role = 'personel'
    GROUP BY u.full_name
    ORDER BY SUM(TIME_TO_SEC(oc.total_duration)) DESC
    LIMIT 1
";
$topOutgoingDuration = $db->fetchOne($outgoingDurationQuery, ['year' => $selectedYearForReport]);
$yearlyChampions['outgoing_duration'] = $topOutgoingDuration;

// 5. En çok eğitim veren (Google Yorum ve Lisans Yenileme hariç)
$trainingQuery = "
    SELECT
        support_representative as full_name,
        COUNT(*) as total_training,
        ROUND(COUNT(*) / 12, 2) as monthly_avg
    FROM training_completion
    WHERE YEAR(training_completion_date) = :year
    AND LOWER(package_type) NOT LIKE '%google yorum%'
    AND LOWER(package_type) NOT LIKE '%lisans yenileme%'
    GROUP BY support_representative
    ORDER BY total_training DESC
    LIMIT 1
";
$topTraining = $db->fetchOne($trainingQuery, ['year' => $selectedYearForReport]);
$yearlyChampions['training'] = $topTraining;

// 6. En çok lisans yenileme yapan
$licenseRenewalQuery = "
    SELECT
        support_representative as full_name,
        COUNT(*) as total_renewals,
        ROUND(COUNT(*) / 12, 2) as monthly_avg
    FROM training_completion
    WHERE YEAR(training_completion_date) = :year
    AND LOWER(package_type) LIKE '%lisans yenileme%'
    GROUP BY support_representative
    ORDER BY total_renewals DESC
    LIMIT 1
";
$topLicenseRenewal = $db->fetchOne($licenseRenewalQuery, ['year' => $selectedYearForReport]);
$yearlyChampions['license_renewal'] = $topLicenseRenewal;

// 7. En çok Google yorum alan
$googleReviewQuery = "
    SELECT
        support_representative as full_name,
        COUNT(*) as total_reviews,
        ROUND(COUNT(*) / 12, 2) as monthly_avg
    FROM training_completion
    WHERE YEAR(training_completion_date) = :year
    AND LOWER(package_type) LIKE '%google yorum%'
    GROUP BY support_representative
    ORDER BY total_reviews DESC
    LIMIT 1
";
$topGoogleReview = $db->fetchOne($googleReviewQuery, ['year' => $selectedYearForReport]);
$yearlyChampions['google_review'] = $topGoogleReview;

// ============ YENİ SATIŞ ANALİZİ (Google Yorum ve Lisans Yenileme Hariç) ============

// Her personel için yeni satış eğitim sayıları
$newSalesQuery = "
    SELECT
        support_representative as full_name,
        COUNT(*) as total_trainings,
        ROUND(COUNT(*) / 12, 2) as monthly_avg
    FROM training_completion
    WHERE YEAR(training_completion_date) = :year
    AND sales_type = 'Yeni Satış'
    AND LOWER(package_type) NOT LIKE '%google yorum%'
    AND LOWER(package_type) NOT LIKE '%lisans yenileme%'
    AND support_representative IS NOT NULL
    AND support_representative != ''
    GROUP BY support_representative
    ORDER BY total_trainings DESC
";
$newSalesData = $db->fetchAll($newSalesQuery, ['year' => $selectedYearForReport]);

// ============ TREND ÖZETLERİ VE ÖNERİLER HESAPLAMALARI ============

// Önce önceki dönem personel verilerini alalım (karşılaştırma için)
// Yöneticileri hariç tut (sadece personel)
// NOT: $prevStartDate ve $prevEndDate yukarıda hesaplandı, gün bazlı karşılaştırma yapıldı
$prevPerformanceQuery = "
    SELECT
        u.id,
        u.full_name,
        COALESCE(ic_sum.total_answered, 0) as total_answered,
        COALESCE(ic_sum.avg_answer_rate, 0) as avg_answer_rate
    FROM users u
    LEFT JOIN (
        SELECT
            user_id,
            SUM(answered_count) as total_answered,
            AVG(answer_percentage) as avg_answer_rate
        FROM incoming_calls
        WHERE call_date BETWEEN :start_date AND :end_date
        GROUP BY user_id
    ) ic_sum ON u.id = ic_sum.user_id
    WHERE u.is_active = 1 AND u.role = 'personel'
";

$prevPerformanceParams = [
    'start_date' => $prevStartDate,
    'end_date' => $prevEndDate
];
$prevPerformanceData = $db->fetchAll($prevPerformanceQuery, $prevPerformanceParams);

// Önceki dönem verilerini ID ile indeksle (kolay erişim için)
$prevPerformanceByUser = [];
foreach ($prevPerformanceData as $prev) {
    $prevPerformanceByUser[$prev['id']] = $prev;
}

// Personel bazlı karşılaştırmalar (sadece personel - yöneticileri hariç tut)
$userComparisons = [];
foreach ($performanceData as $current) {
    // Yöneticileri atla
    if ($current['role'] === 'admin') {
        continue;
    }

    $userId = $current['id'];
    $prev = $prevPerformanceByUser[$userId] ?? null;

    if ($prev && $prev['total_answered'] > 0) {
        $callChange = $current['total_answered'] - $prev['total_answered'];
        $callChangePercent = round(($callChange / $prev['total_answered']) * 100, 1);
        $answerRateChange = $current['avg_answer_rate'] - $prev['avg_answer_rate'];

        $userComparisons[] = [
            'id' => $userId,
            'name' => $current['full_name'],
            'current_calls' => $current['total_answered'],
            'prev_calls' => $prev['total_answered'],
            'call_change' => $callChange,
            'call_change_percent' => $callChangePercent,
            'current_answer_rate' => $current['avg_answer_rate'],
            'prev_answer_rate' => $prev['avg_answer_rate'],
            'answer_rate_change' => $answerRateChange,
            'training_count' => $current['training_count']
        ];
    }
}

// En çok gelişenler ve geriliyenler
usort($userComparisons, function($a, $b) {
    return $b['call_change_percent'] <=> $a['call_change_percent'];
});

$topImprovers = array_slice($userComparisons, 0, 3); // En çok gelişenler
$topDecliners = array_slice(array_reverse($userComparisons), 0, 3); // En çok gerileyenler

// Personel bazlı ortalamalar (yöneticiler hariç)
$personnelOnly = array_filter($performanceData, function($p) { return $p['role'] !== 'admin'; });
$personnelIncoming = array_map('intval', array_column($personnelOnly, 'total_answered'));
$personnelOutgoing = array_map('intval', array_column($personnelOnly, 'total_outgoing'));
$avgIncomingPersonnel = !empty($personnelIncoming) ? round(array_sum($personnelIncoming) / count($personnelIncoming)) : 0;
$avgOutgoingPersonnel = !empty($personnelOutgoing) ? round(array_sum($personnelOutgoing) / count($personnelOutgoing)) : 0;

$recommendations = [];

// 1. Çağrı Trendi Analizi
if ($callsTrend > 10) {
    $recommendations[] = [
        'type' => 'success',
        'icon' => '📈',
        'title' => 'Artan Çağrı Trendi',
        'description' => 'Gelen çağrı sayısı bir önceki döneme göre %' . abs($callsTrend) . ' arttı. Ekip kapasitesini gözden geçirin.',
        'action' => 'Yoğun dönemlerde ek personel desteği planlanabilir.'
    ];
} elseif ($callsTrend < -10) {
    $recommendations[] = [
        'type' => 'warning',
        'icon' => '📉',
        'title' => 'Azalan Çağrı Trendi',
        'description' => 'Gelen çağrı sayısı bir önceki döneme göre %' . abs($callsTrend) . ' azaldı. Nedenleri araştırın.',
        'action' => 'Müşteri memnuniyeti veya hizmet kalitesi analizi yapılabilir.'
    ];
}

// 2. Düşük Yanıt Oranı Analizi (sadece personel)
$lowAnswerRateCount = 0;
$lowAnswerRateUsers = [];
foreach ($personnelOnly as $perf) {
    if ($perf['total_answered'] > 0 && $perf['avg_answer_rate'] < 70) {
        $lowAnswerRateCount++;
        $lowAnswerRateUsers[] = $perf['full_name'];
    }
}
if ($lowAnswerRateCount > 0) {
    $recommendations[] = [
        'type' => 'alert',
        'icon' => '⚠️',
        'title' => 'Düşük Yanıt Oranı',
        'description' => $lowAnswerRateCount . ' personelin yanıt oranı %70\'in altında.',
        'action' => 'Bu personeller için ek eğitim veya destek planlanabilir: ' . implode(', ', array_slice($lowAnswerRateUsers, 0, 3)) . (count($lowAnswerRateUsers) > 3 ? '...' : '')
    ];
}

// 3. Eğitim Analizi (sadece personel)
$totalTrainingCount = array_sum($performanceTraining);
$zeroTrainingCount = 0;
foreach ($personnelOnly as $perf) {
    if ($perf['training_count'] == 0) {
        $zeroTrainingCount++;
    }
}
if ($zeroTrainingCount > 0 && $totalTrainingCount > 0) {
    $recommendations[] = [
        'type' => 'info',
        'icon' => '🎓',
        'title' => 'Eğitim Fırsatı',
        'description' => $zeroTrainingCount . ' personel bu dönemde eğitim tamamlamadı.',
        'action' => 'Tüm personelin düzenli eğitim alması için planlama yapılabilir.'
    ];
}

// 4. Performans Dengesizliği (sadece personel)
$personnelTopPerformer = !empty($personnelOnly) ? reset($personnelOnly) : null;
if (count($personnelOnly) > 1 && $personnelTopPerformer) {
    $topCalls = $personnelTopPerformer['total_answered'];

    if ($topCalls > ($avgIncomingPersonnel * 2)) {
        $recommendations[] = [
            'type' => 'info',
            'icon' => '⚖️',
            'title' => 'İş Yükü Dengesizliği',
            'description' => $personnelTopPerformer['full_name'] . ' ekip ortalamasının 2 katından fazla çağrı alıyor.',
            'action' => 'Çağrı dağılımını optimize etmek için yönlendirme ayarları gözden geçirilebilir.'
        ];
    }
}

// 5. Genel Performans Değerlendirmesi
$avgAnswerRate = $stats['avg_answer_rate'] ?? 0;
if ($avgAnswerRate >= 85) {
    $recommendations[] = [
        'type' => 'success',
        'icon' => '🌟',
        'title' => 'Mükemmel Performans',
        'description' => 'Ekip ortalama yanıt oranı %' . number_format($avgAnswerRate, 1) . ' - Hedefin üzerinde!',
        'action' => 'Bu başarı seviyesini korumak için mevcut stratejilere devam edilebilir.'
    ];
} elseif ($avgAnswerRate < 70) {
    $recommendations[] = [
        'type' => 'alert',
        'icon' => '🎯',
        'title' => 'İyileştirme Gerekli',
        'description' => 'Ekip ortalama yanıt oranı %' . number_format($avgAnswerRate, 1) . ' - Hedefin altında.',
        'action' => 'Yanıt oranını artırmak için operasyonel iyileştirmeler yapılabilir.'
    ];
}

// ============ PERSONEL BAZLI ANALİZLER ============

// 1. En Çok Gelişen Personel
if (!empty($topImprovers)) {
    $topImprover = $topImprovers[0];
    if ($topImprover['call_change_percent'] > 15) {
        $recommendations[] = [
            'type' => 'success',
            'icon' => '🚀',
            'title' => 'Yükselen Yıldız: ' . $topImprover['name'],
            'description' => 'Bir önceki döneme göre %' . abs($topImprover['call_change_percent']) . ' artışla ' .
                           number_format($topImprover['current_calls']) . ' çağrı yanıtladı (Önceki: ' .
                           number_format($topImprover['prev_calls']) . ')',
            'action' => 'Bu başarı takdir edilebilir ve diğer personele örnek gösterilebilir.'
        ];
    }
}

// 2. Dikkat Gerektiren Performans Düşüşü
if (!empty($topDecliners)) {
    foreach (array_slice($topDecliners, 0, 2) as $decliner) {
        if ($decliner['call_change_percent'] < -20 && $decliner['current_calls'] < 100) {
            $recommendations[] = [
                'type' => 'alert',
                'icon' => '📉',
                'title' => 'Performans Düşüşü: ' . $decliner['name'],
                'description' => 'Bir önceki döneme göre %' . abs($decliner['call_change_percent']) . ' düşüşle ' .
                               number_format($decliner['current_calls']) . ' çağrı yanıtladı (Önceki: ' .
                               number_format($decliner['prev_calls']) . ')',
                'action' => 'Performans düşüşünün nedenleri araştırılmalı, gerekirse birebir görüşme yapılabilir.'
            ];
        }
    }
}

// 3. Eğitim Etkisi Analizi
$trainingImpact = [];
foreach ($userComparisons as $comp) {
    if ($comp['training_count'] > 0 && $comp['call_change_percent'] > 10) {
        $trainingImpact[] = $comp;
    }
}
if (!empty($trainingImpact)) {
    $trainingImpactNames = array_slice(array_column($trainingImpact, 'name'), 0, 3);
    $recommendations[] = [
        'type' => 'success',
        'icon' => '🎓',
        'title' => 'Eğitim Başarı Etkisi',
        'description' => count($trainingImpact) . ' personel eğitim aldıktan sonra performans artışı gösterdi.',
        'action' => 'Eğitim programlarına devam edilmesi önerilir. Örnek: ' . implode(', ', $trainingImpactNames)
    ];
}

// 4. Yanıt Oranı İyileşmesi
$answerRateImprovers = [];
foreach ($userComparisons as $comp) {
    if ($comp['answer_rate_change'] > 5 && $comp['current_answer_rate'] > 75) {
        $answerRateImprovers[] = $comp;
    }
}
if (!empty($answerRateImprovers)) {
    $bestImprover = $answerRateImprovers[0];
    $recommendations[] = [
        'type' => 'success',
        'icon' => '📈',
        'title' => 'Yanıt Oranı İyileşmesi: ' . $bestImprover['name'],
        'description' => 'Yanıt oranı %' . number_format($bestImprover['prev_answer_rate'], 1) .
                       '\'den %' . number_format($bestImprover['current_answer_rate'], 1) . '\'e yükseldi.',
        'action' => 'Bu gelişim olumlu, motivasyon için takdir edilebilir.'
    ];
}

// 5. Sürekli Yüksek Performans
$consistentPerformers = [];
foreach ($userComparisons as $comp) {
    if ($comp['current_answer_rate'] >= 85 && $comp['prev_answer_rate'] >= 85 &&
        $comp['current_calls'] > $avgIncomingPersonnel && $comp['prev_calls'] > 0) {
        $consistentPerformers[] = $comp;
    }
}
if (!empty($consistentPerformers)) {
    $performerNames = array_slice(array_column($consistentPerformers, 'name'), 0, 3);
    $recommendations[] = [
        'type' => 'success',
        'icon' => '⭐',
        'title' => 'Sürekli Yüksek Performans',
        'description' => count($consistentPerformers) . ' personel hem bu dönem hem önceki dönemde %85 üzeri yanıt oranı koruyor.',
        'action' => 'Bu personeller mentor olarak görevlendirilebilir: ' . implode(', ', $performerNames)
    ];
}

// 6. Düşük Yanıt Oranında Kötüleşme
$worseningAnswerRate = [];
foreach ($userComparisons as $comp) {
    if ($comp['answer_rate_change'] < -5 && $comp['current_answer_rate'] < 70) {
        $worseningAnswerRate[] = $comp;
    }
}
if (!empty($worseningAnswerRate)) {
    $worstCase = $worseningAnswerRate[0];
    $recommendations[] = [
        'type' => 'alert',
        'icon' => '⚠️',
        'title' => 'Yanıt Oranında Kötüleşme: ' . $worstCase['name'],
        'description' => 'Yanıt oranı %' . number_format($worstCase['prev_answer_rate'], 1) .
                       '\'den %' . number_format($worstCase['current_answer_rate'], 1) . '\'e düştü.',
        'action' => 'Acil müdahale gerekebilir. Nedenler araştırılmalı ve destek sağlanmalı.'
    ];
}

// 7. Yeni Yüksek Performans Gösterenler (önceki dönem ortalama, bu dönem üstün)
$emergingStars = [];
foreach ($userComparisons as $comp) {
    if ($comp['prev_calls'] > 0 && $comp['current_calls'] > ($avgIncomingPersonnel * 1.3) &&
        $comp['prev_calls'] <= $avgIncomingPersonnel && $comp['call_change_percent'] > 30) {
        $emergingStars[] = $comp;
    }
}
if (!empty($emergingStars)) {
    $starNames = array_column($emergingStars, 'name');
    $recommendations[] = [
        'type' => 'success',
        'icon' => '💫',
        'title' => 'Yeni Yüksek Performans',
        'description' => count($emergingStars) . ' personel ortalama seviyeden üst seviyeye yükseldi.',
        'action' => 'Bu gelişim desteklenmeli: ' . implode(', ', $starNames)
    ];
}

// Öneri yoksa genel mesaj ekle
if (empty($recommendations)) {
    $recommendations[] = [
        'type' => 'info',
        'icon' => '✅',
        'title' => 'Dengeli Performans',
        'description' => 'Ekip dengeli bir performans sergiliyor. Önemli trend değişikliği tespit edilmedi.',
        'action' => 'Mevcut performansı korumak için rutin takip yapılabilir.'
    ];
}

?>


<style>
    .admin-reports-container {
        padding: 20px;
    }

    /* Filtre Bölümü */
    .filters-section {
        background: white;
        border-radius: 12px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .filter-row {
        display: flex;
        gap: 15px;
        align-items: flex-end;
        flex-wrap: wrap;
        margin-bottom: 15px;
    }

    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 5px;
    }

    .filter-group label {
        font-size: 13px;
        font-weight: 600;
        color: #2c3e50;
    }

    .filter-group input[type="date"],
    .filter-group select {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 6px;
        font-size: 14px;
        min-width: 150px;
    }

    .filter-group input[type="date"]:focus,
    .filter-group select:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .filter-btn {
        padding: 8px 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 600;
        transition: transform 0.2s;
    }

    .filter-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    /* Hızlı Filtreler */
    .quick-filters {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .quick-filter-btn {
        padding: 8px 16px;
        background: #f8f9fa;
        border: 2px solid #e9ecef;
        border-radius: 20px;
        text-decoration: none;
        color: #495057;
        font-size: 13px;
        font-weight: 500;
        transition: all 0.2s;
    }

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

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

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

    .stat-card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        border-left: 4px solid var(--card-color, #667eea);
        transition: transform 0.2s;
    }

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

    .stat-card-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .stat-info {
        flex: 1;
    }

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

    .stat-label {
        font-size: 14px;
        color: #7f8c8d;
        margin-bottom: 5px;
    }

    .stat-change {
        font-size: 12px;
        padding: 4px 8px;
        border-radius: 12px;
        display: inline-block;
        background: #e8f5e9;
        color: #2e7d32;
        font-weight: 600;
    }

    .stat-icon {
        font-size: 48px;
        opacity: 0.2;
    }

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

    .card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

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

    /* Chart Container */
    .chart-container {
        position: relative;
        height: 300px;
        margin-bottom: 20px;
    }

    /* Performance Table */
    .data-table-container {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        margin-top: 20px;
    }

    .table-scroll-wrapper {
        overflow-x: auto;
    }

    .performance-table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
    }

    .performance-table thead {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .performance-table th {
        padding: 12px;
        text-align: left;
        font-weight: 600;
        position: sticky;
        top: 0;
    }

    .performance-table td {
        padding: 12px;
        border-bottom: 1px solid #f0f0f0;
    }

    .performance-table tbody tr:hover {
        background: #f8f9fa;
    }

    .performance-table tbody tr:nth-child(even) {
        background: #fafafa;
    }

    .performance-table tbody tr:nth-child(even):hover {
        background: #f0f0f0;
    }

    /* Chart Filters */
    .chart-filters {
        margin-bottom: 20px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 8px;
    }

    .chart-filter-label {
        display: block;
        font-size: 14px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 10px;
    }

    .chart-filter-buttons {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .chart-filter-btn {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 16px;
        background: white;
        border: 2px solid #e0e0e0;
        border-radius: 20px;
        cursor: pointer;
        font-size: 13px;
        font-weight: 500;
        color: #666;
        transition: all 0.2s;
    }

    .chart-filter-btn:hover {
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

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

    .chart-filter-btn:not(.active) {
        opacity: 0.5;
    }

    .filter-color {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
        border: 2px solid rgba(255,255,255,0.5);
    }

    /* Insights Section */
    .insights-wrapper {
        background: white;
        border-radius: 12px;
        padding: 25px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        margin-top: 20px;
    }

    .insights-section {
    }

    .insights-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
    }

    .insight-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 12px;
        padding: 20px;
        color: white;
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        transition: transform 0.2s;
    }

    .insight-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }

    .insight-card.green {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        box-shadow: 0 4px 12px rgba(67, 233, 123, 0.3);
    }

    .insight-card.green:hover {
        box-shadow: 0 6px 20px rgba(67, 233, 123, 0.4);
    }

    .insight-card.orange {
        background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        box-shadow: 0 4px 12px rgba(250, 112, 154, 0.3);
    }

    .insight-card.orange:hover {
        box-shadow: 0 6px 20px rgba(250, 112, 154, 0.4);
    }

    .insight-card.blue {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        box-shadow: 0 4px 12px rgba(79, 172, 254, 0.3);
    }

    .insight-card.blue:hover {
        box-shadow: 0 6px 20px rgba(79, 172, 254, 0.4);
    }

    .insight-card.purple {
        background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
        box-shadow: 0 4px 12px rgba(168, 237, 234, 0.3);
    }

    .insight-card.purple:hover {
        box-shadow: 0 6px 20px rgba(168, 237, 234, 0.4);
    }

    .insight-card.pink {
        background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
        box-shadow: 0 4px 12px rgba(255, 154, 158, 0.3);
    }

    .insight-card.pink:hover {
        box-shadow: 0 6px 20px rgba(255, 154, 158, 0.4);
    }

    .insight-card.teal {
        background: linear-gradient(135deg, #0ba360 0%, #3cba92 100%);
        box-shadow: 0 4px 12px rgba(11, 163, 96, 0.3);
    }

    .insight-card.teal:hover {
        box-shadow: 0 6px 20px rgba(11, 163, 96, 0.4);
    }

    .insight-card.indigo {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
    }

    .insight-card.indigo:hover {
        box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
    }

    .insight-header {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 15px;
        font-size: 14px;
        opacity: 0.9;
        font-weight: 600;
    }

    .insight-icon {
        font-size: 24px;
    }

    .insight-value {
        font-size: 32px;
        font-weight: 700;
        margin-bottom: 5px;
    }

    .insight-label {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 10px;
    }

    .insight-detail {
        font-size: 13px;
        opacity: 0.9;
        display: flex;
        align-items: center;
        gap: 5px;
    }

    .trend-badge {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 8px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 12px;
        font-size: 12px;
        font-weight: 600;
        margin-top: 8px;
    }

    .trend-badge.up {
        background: rgba(76, 175, 80, 0.3);
    }

    .trend-badge.down {
        background: rgba(244, 67, 54, 0.3);
    }

    /* Notification */
    .notification {
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 20px;
        font-size: 14px;
        line-height: 1.5;
    }

    .notification.warning {
        background: #fff3cd;
        border-left: 4px solid #ffc107;
        color: #856404;
    }

    .notification.info {
        background: #cfe2ff;
        border-left: 4px solid #0d6efd;
        color: #084298;
    }

    /* Recommendations Section */
    .recommendations-wrapper {
        background: white;
        border-radius: 12px;
        padding: 25px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        margin-top: 20px;
    }

    .recommendations-section {
    }

    .recommendations-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
        gap: 20px;
    }

    .recommendation-card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        border-left: 4px solid #667eea;
        transition: transform 0.2s, box-shadow 0.2s;
    }

    .recommendation-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 16px rgba(0,0,0,0.15);
    }

    .recommendation-card.success {
        border-left-color: #4CAF50;
        background: linear-gradient(to right, rgba(76, 175, 80, 0.05) 0%, white 10%);
    }

    .recommendation-card.warning {
        border-left-color: #FF9800;
        background: linear-gradient(to right, rgba(255, 152, 0, 0.05) 0%, white 10%);
    }

    .recommendation-card.alert {
        border-left-color: #F44336;
        background: linear-gradient(to right, rgba(244, 67, 54, 0.05) 0%, white 10%);
    }

    .recommendation-card.info {
        border-left-color: #2196F3;
        background: linear-gradient(to right, rgba(33, 150, 243, 0.05) 0%, white 10%);
    }

    .recommendation-header {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 15px;
    }

    .recommendation-icon {
        font-size: 32px;
        line-height: 1;
    }

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

    .recommendation-description {
        font-size: 14px;
        color: #555;
        line-height: 1.6;
        margin-bottom: 12px;
        padding-left: 44px;
    }

    .recommendation-action {
        font-size: 13px;
        color: #667eea;
        background: rgba(102, 126, 234, 0.1);
        padding: 10px 15px;
        border-radius: 8px;
        margin-left: 44px;
        line-height: 1.5;
        font-weight: 500;
    }

    .recommendation-card.success .recommendation-action {
        color: #2e7d32;
        background: rgba(76, 175, 80, 0.1);
    }

    .recommendation-card.warning .recommendation-action {
        color: #e65100;
        background: rgba(255, 152, 0, 0.1);
    }

    .recommendation-card.alert .recommendation-action {
        color: #c62828;
        background: rgba(244, 67, 54, 0.1);
    }

    .recommendation-card.info .recommendation-action {
        color: #1565c0;
        background: rgba(33, 150, 243, 0.1);
    }

    /* Responsive */
    @media (max-width: 768px) {
        .content-grid {
            grid-template-columns: 1fr;
        }

        .filter-row {
            flex-direction: column;
            align-items: stretch;
        }

        .filter-group input[type="date"],
        .filter-group select {
            min-width: 100%;
        }
    }
</style>

<div class="admin-reports-container">
    <!-- Filtreler -->
    <div class="filters-section">
        <h3 style="margin-bottom: 15px; color: #2c3e50;">📊 Filtreler</h3>

        <!-- Hızlı Filtreler -->
        <div class="quick-filters" style="margin-bottom: 20px;">
            <a href="?quick_filter=month_0"
               class="quick-filter-btn <?php echo ($quickFilter === 'month_0' || (!$quickFilter && !isset($_GET['start_date']))) ? 'active' : ''; ?>">
                Bu Ay
            </a>
            <a href="?quick_filter=month_-1"
               class="quick-filter-btn <?php echo ($quickFilter === 'month_-1') ? 'active' : ''; ?>">
                Geçen Ay
            </a>
            <a href="?quick_filter=last_3_months"
               class="quick-filter-btn <?php echo ($quickFilter === 'last_3_months') ? 'active' : ''; ?>">
                Son 3 Ay
            </a>
            <?php foreach ($months as $month): ?>
                <?php if ($month['value'] !== 'month_0' && $month['value'] !== 'month_-1'): ?>
                <a href="?quick_filter=<?php echo $month['value']; ?>"
                   class="quick-filter-btn <?php echo ($quickFilter === $month['value']) ? 'active' : ''; ?>">
                    <?php echo $month['label']; ?>
                </a>
                <?php endif; ?>
            <?php endforeach; ?>
        </div>

        <!-- Manuel Filtreler -->
        <form method="GET" class="filter-row">
            <div class="filter-group">
                <label>Başlangıç Tarihi:</label>
                <input type="date" name="start_date" value="<?php echo htmlspecialchars($startDate); ?>" required>
            </div>

            <div class="filter-group">
                <label>Bitiş Tarihi:</label>
                <input type="date" name="end_date" value="<?php echo htmlspecialchars($endDate); ?>" required>
            </div>

            <div class="filter-group">
                <label>Çalışan:</label>
                <select name="user_id">
                    <option value="">Tüm Çalışanlar</option>
                    <?php foreach ($users as $user): ?>
                    <option value="<?php echo $user['id']; ?>"
                            <?php echo ($selectedUserId == $user['id']) ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($user['full_name']); ?>
                        <?php if ($user['extension']): ?>
                            (Dah. <?php echo htmlspecialchars($user['extension']); ?>)
                        <?php endif; ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <button type="submit" class="filter-btn">Filtrele</button>
        </form>
    </div>

    <!-- Genel İstatistikler -->
    <div class="stats-grid">
        <div class="stat-card" style="--card-color: #667eea;">
            <div class="stat-card-content">
                <div class="stat-info">
                    <div class="stat-value"><?php echo number_format($stats['total_incoming_calls'] ?? 0); ?></div>
                    <div class="stat-label">Toplam Gelen Çağrı</div>
                    <div class="stat-change">Yanıtlanan</div>
                </div>
                <div class="stat-icon">📞</div>
            </div>
        </div>

        <div class="stat-card" style="--card-color: #f093fb;">
            <div class="stat-card-content">
                <div class="stat-info">
                    <div class="stat-value"><?php echo number_format($outgoingStats['total_outgoing_calls'] ?? 0); ?></div>
                    <div class="stat-label">Toplam Giden Çağrı</div>
                    <div class="stat-change">Yapılan</div>
                </div>
                <div class="stat-icon">📱</div>
            </div>
        </div>

        <div class="stat-card" style="--card-color: #4facfe;">
            <div class="stat-card-content">
                <div class="stat-info">
                    <div class="stat-value"><?php echo $stats['total_incoming_duration'] ?? '00:00:00'; ?></div>
                    <div class="stat-label">Toplam Görüşme Süresi</div>
                    <div class="stat-change">Gelen Çağrılar</div>
                </div>
                <div class="stat-icon">⏱️</div>
            </div>
        </div>

        <div class="stat-card" style="--card-color: #ff6b9d;">
            <div class="stat-card-content">
                <div class="stat-info">
                    <div class="stat-value"><?php echo $outgoingStats['total_outgoing_duration'] ?? '00:00:00'; ?></div>
                    <div class="stat-label">Toplam Görüşme Süresi</div>
                    <div class="stat-change">Giden Çağrılar</div>
                </div>
                <div class="stat-icon">📞</div>
            </div>
        </div>

        <div class="stat-card" style="--card-color: #43e97b;">
            <div class="stat-card-content">
                <div class="stat-info">
                    <div class="stat-value"><?php echo number_format($trainingStats['total_trainings'] ?? 0); ?></div>
                    <div class="stat-label">Eğitim Tamamlama</div>
                    <div class="stat-change">Kurulum</div>
                </div>
                <div class="stat-icon">🎓</div>
            </div>
        </div>

        <div class="stat-card" style="--card-color: #feca57;">
            <div class="stat-card-content">
                <div class="stat-info">
                    <div class="stat-value">%<?php echo number_format($stats['avg_answer_rate'] ?? 0, 1); ?></div>
                    <div class="stat-label">Ortalama Yanıt Oranı</div>
                    <div class="stat-change">Başarı</div>
                </div>
                <div class="stat-icon">📈</div>
            </div>
        </div>
    </div>

    <!-- Grafikler -->
    <div class="content-grid">
        <!-- Çalışan Performans Karşılaştırması -->
        <div class="card" style="grid-column: 1 / -1;">
            <h3 class="card-title">Çalışan Bazında Performans Karşılaştırması</h3>
            <?php
            $totalTraining = array_sum($performanceTraining);
            if ($totalTraining == 0):
            ?>
            <div class="notification warning" style="margin-bottom: 15px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <div style="font-size: 24px;">ℹ️</div>
                    <div>
                        <strong>Eğitim verisi bulunamadı:</strong> Seçili tarih aralığında eğitim tamamlama kaydı yok.
                        Eğitim verilerini görmek için <strong>"Geçen Ay"</strong> veya farklı bir tarih aralığı seçin.
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Grafik Filtreleme Butonları -->
            <div class="chart-filters">
                <label class="chart-filter-label">Gösterilecek Veriler:</label>
                <div class="chart-filter-buttons">
                    <button class="chart-filter-btn active" data-dataset="0" onclick="toggleDataset(0)">
                        <span class="filter-color" style="background: rgba(102, 126, 234, 0.8);"></span>
                        Gelen Çağrı
                    </button>
                    <button class="chart-filter-btn active" data-dataset="1" onclick="toggleDataset(1)">
                        <span class="filter-color" style="background: rgba(240, 147, 251, 0.8);"></span>
                        Giden Çağrı
                    </button>
                    <button class="chart-filter-btn active" data-dataset="2" onclick="toggleDataset(2)">
                        <span class="filter-color" style="background: rgba(67, 233, 123, 0.8);"></span>
                        Eğitim
                    </button>
                    <button class="chart-filter-btn active" data-dataset="3" onclick="toggleDataset(3)">
                        <span class="filter-color" style="background: rgba(79, 172, 254, 0.8);"></span>
                        Gelen Süre (dk)
                    </button>
                    <button class="chart-filter-btn active" data-dataset="4" onclick="toggleDataset(4)">
                        <span class="filter-color" style="background: rgba(250, 112, 154, 0.8);"></span>
                        Giden Süre (dk)
                    </button>
                </div>
            </div>

            <div class="chart-container">
                <canvas id="performanceChart"></canvas>
            </div>
        </div>

        <!-- Aylık Trend -->
        <div class="card">
            <h3 class="card-title">Aylık Çağrı Trendi (Son 6 Ay)</h3>
            <div class="chart-container">
                <canvas id="trendChart"></canvas>
            </div>
        </div>

        <!-- Paket Dağılımı -->
        <div class="card">
            <h3 class="card-title">Paket Türü Dağılımı</h3>
            <div class="chart-container">
                <canvas id="packageChart"></canvas>
            </div>
        </div>

        <!-- Günlük Aktivite -->
        <div class="card" style="grid-column: 1 / -1;">
            <h3 class="card-title">Günlük Aktivite (Son 30 Gün)</h3>

            <!-- Aktivite Filtreleme Butonları -->
            <div class="chart-filters">
                <label class="chart-filter-label">Gösterilecek Veriler:</label>
                <div class="chart-filter-buttons">
                    <button class="chart-filter-btn active" data-activity-dataset="0" onclick="toggleActivityDataset(0)">
                        <span class="filter-color" style="background: rgba(79, 172, 254, 0.8);"></span>
                        Gelen Çağrı
                    </button>
                    <button class="chart-filter-btn" data-activity-dataset="1" onclick="toggleActivityDataset(1)">
                        <span class="filter-color" style="background: rgba(250, 112, 154, 0.8);"></span>
                        Giden Çağrı
                    </button>
                </div>
            </div>

            <div class="chart-container">
                <canvas id="activityChart"></canvas>
            </div>
        </div>
    </div>

    <!-- Yıllık Personel Performans Raporu -->
    <div class="data-table-container" style="margin-bottom: 30px;">
        <div class="section-header">
            <h2 class="section-title">📊 Yıllık Personel Performans Raporu</h2>
        </div>

        <!-- Yıl Seçici -->
        <div class="filters-section" style="margin-bottom: 20px;">
            <form method="GET" style="display: flex; gap: 15px; align-items: center;">
                <div class="filter-group">
                    <label>Rapor Yılı:</label>
                    <select name="report_year" onchange="this.form.submit()">
                        <?php foreach ($availableYears as $year): ?>
                        <option value="<?php echo $year; ?>" <?php echo ($selectedYearForReport == $year) ? 'selected' : ''; ?>>
                            <?php echo $year; ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </form>
        </div>

        <!-- En İyi Performanslar -->
        <div class="insights-wrapper" style="margin-bottom: 30px;">
            <div class="insights-section">
                <h3 style="margin-bottom: 20px; color: #2c3e50;">🏆 <?php echo $selectedYearForReport; ?> Yılı En İyi Performanslar</h3>
                <div class="insights-grid">
                    <?php
                    $medals = ['🥇', '🥈', '🥉'];
                    $cardClasses = ['green', 'blue', 'orange'];
                    $index = 0;
                    foreach ($topPerformers as $performerName => $yearlyTotal):
                    ?>
                    <div class="insight-card <?php echo $cardClasses[$index]; ?>">
                        <div class="insight-header">
                            <span class="insight-icon"><?php echo $medals[$index]; ?></span>
                            <span><?php echo ($index + 1); ?>. SIRADA</span>
                        </div>
                        <div class="insight-value"><?php echo htmlspecialchars($performerName); ?></div>
                        <div class="insight-label">Toplam Puan: <?php echo number_format($yearlyTotal, 2); ?></div>
                        <div class="insight-detail">
                            <?php echo $selectedYearForReport; ?> yılı boyunca elde edilen toplam puan
                        </div>
                    </div>
                    <?php
                    $index++;
                    endforeach;
                    ?>
                </div>
            </div>
        </div>

        <!-- Aylık Performans Grafiği -->
        <div class="card">
            <h3 class="card-title">Aylık Toplam Puan Dağılımı - <?php echo $selectedYearForReport; ?></h3>

            <!-- Personel Filtre Butonları -->
            <div class="chart-filters">
                <label class="chart-filter-label">Gösterilecek Personeller:</label>
                <div class="chart-filter-buttons">
                    <button class="chart-filter-btn active" onclick="toggleAllPersonnel()">
                        Tümünü Seç/Kaldır
                    </button>
                    <?php foreach ($personnelMonthlyData as $index => $pData): ?>
                    <button class="chart-filter-btn active" data-personnel-dataset="<?php echo $index; ?>" onclick="togglePersonnelDataset(<?php echo $index; ?>)">
                        <span class="filter-color" style="background: <?php echo $pData['color']; ?>;"></span>
                        <?php echo htmlspecialchars($pData['name']); ?>
                    </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="chart-container" style="height: 400px;">
                <canvas id="yearlyPerformanceChart"></canvas>
            </div>
        </div>

        <!-- Yatay Yığılmış Grafik (Rapor.jpg benzeri) -->
        <div class="card" style="margin-top: 30px;">
            <h3 class="card-title">Yıllık Performans Dağılımı (Aylık Yüzde) - <?php echo $selectedYearForReport; ?></h3>
            <div class="chart-container" style="height: <?php echo (count($personnelMonthlyData) * 60 + 100); ?>px;">
                <canvas id="stackedPerformanceChart"></canvas>
            </div>
        </div>

        <!-- Yıllık Toplam Puanlar Tablosu -->
        <div class="card" style="grid-column: 1 / -1; margin-top: 30px;">
            <h3 class="card-title">Detaylı Aylık Puan Tablosu - <?php echo $selectedYearForReport; ?></h3>
            <div class="table-scroll-wrapper">
                <table class="performance-table" style="border-collapse: collapse;">
                <thead>
                    <tr>
                        <th style="border: 2px solid #ddd; padding: 12px;">Personel</th>
                        <?php foreach ($monthlyLabels as $monthLabel): ?>
                        <th style="border: 2px solid #ddd; padding: 12px;"><?php echo $monthLabel; ?></th>
                        <?php endforeach; ?>
                        <th style="background: #667eea; border: 2px solid #ddd; padding: 12px;">Toplam</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    // Her ay için sıralama hesapla
                    $monthlyRankings = [];
                    for ($monthIndex = 0; $monthIndex < 12; $monthIndex++) {
                        $monthScores = [];
                        foreach ($personnelMonthlyData as $pData) {
                            $monthScores[] = [
                                'name' => $pData['name'],
                                'score' => $pData['data'][$monthIndex]
                            ];
                        }
                        // Büyükten küçüğe sırala
                        usort($monthScores, function($a, $b) {
                            return $b['score'] <=> $a['score'];
                        });

                        // Sıralamaları kaydet
                        $rankings = [];
                        $rank = 1;
                        foreach ($monthScores as $ms) {
                            $rankings[$ms['name']] = $rank;
                            $rank++;
                        }
                        $monthlyRankings[$monthIndex] = $rankings;
                    }

                    // Sıralamaya göre renk fonksiyonu
                    function getRankColor($rank, $totalPersonnel) {
                        if ($rank == 1) {
                            return 'background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%); color: white; font-weight: 700;'; // 1. - Koyu yeşil
                        } elseif ($rank == 2) {
                            return 'background: linear-gradient(135deg, #81C784 0%, #A5D6A7 100%); color: white; font-weight: 700;'; // 2. - Orta yeşil
                        } elseif ($rank == 3) {
                            return 'background: linear-gradient(135deg, #C8E6C9 0%, #DCEDC8 100%); color: #2c3e50; font-weight: 700;'; // 3. - Açık yeşil
                        } elseif ($rank == 4) {
                            return 'background: linear-gradient(135deg, #FFF9C4 0%, #FFF59D 100%); color: #2c3e50; font-weight: 600;'; // 4. - Sarı
                        } else {
                            return 'background: #fafafa; color: #666; font-weight: 500;'; // Diğerleri - Açık gri
                        }
                    }

                    $previousScore = null;
                    $rank = 0;
                    foreach ($personnelMonthlyData as $pData):
                        $rank++;
                        $scoreDiff = null;
                        $percentDiff = null;

                        if ($previousScore !== null) {
                            $scoreDiff = $previousScore - $pData['yearlyTotal'];
                            $percentDiff = $previousScore > 0 ? (($scoreDiff / $previousScore) * 100) : 0;
                        }
                    ?>
                    <tr>
                        <td style="border: 2px solid #ddd; padding: 12px;"><strong><?php echo htmlspecialchars($pData['name']); ?></strong></td>
                        <?php
                        foreach ($pData['data'] as $monthIndex => $monthValue):
                            $monthRank = $monthlyRankings[$monthIndex][$pData['name']];
                            $rankStyle = getRankColor($monthRank, count($personnelMonthlyData));
                        ?>
                        <td style="border: 2px solid #ddd; padding: 12px; <?php echo $rankStyle; ?>">
                            <div style="display: flex; flex-direction: column; align-items: center; gap: 4px;">
                                <div style="font-size: 14px; font-weight: 600;"><?php echo number_format($monthValue, 2); ?></div>
                                <div style="<?php
                                    if ($monthRank <= 3) echo 'font-size: 22px;';
                                    else echo 'font-size: 11px; background: #666; color: white; padding: 2px 6px; border-radius: 10px; font-weight: 600;';
                                ?>">
                                    <?php
                                    if ($monthRank == 1) echo '🥇';
                                    elseif ($monthRank == 2) echo '🥈';
                                    elseif ($monthRank == 3) echo '🥉';
                                    else echo $monthRank;
                                    ?>
                                </div>
                            </div>
                        </td>
                        <?php endforeach; ?>
                        <td style="background: rgba(102, 126, 234, 0.1); font-weight: 700; border: 2px solid #ddd; padding: 12px;">
                            <div style="display: flex; flex-direction: column; gap: 5px;">
                                <div style="font-size: 16px; color: #2c3e50;">
                                    <?php echo number_format($pData['yearlyTotal'], 2); ?> puan
                                </div>
                                <div style="font-size: 12px; color: #667eea; font-weight: 600;">
                                    Aylık Ort: <?php echo number_format($pData['yearlyTotal'] / 12, 2); ?> puan
                                </div>
                                <div style="font-size: 13px; color: <?php echo $pData['percentageOfMax'] >= 90 ? '#4CAF50' : ($pData['percentageOfMax'] >= 75 ? '#2196F3' : ($pData['percentageOfMax'] >= 60 ? '#FF9800' : '#F44336')); ?>; font-weight: 600;">
                                    %<?php echo number_format($pData['percentageOfMax'], 1); ?>
                                    <?php if ($pData['percentageOfMax'] >= 100): ?>
                                    🥇
                                    <?php elseif ($pData['percentageOfMax'] >= 90): ?>
                                    🥈
                                    <?php elseif ($pData['percentageOfMax'] >= 75): ?>
                                    🥉
                                    <?php endif; ?>
                                </div>
                                <?php if ($scoreDiff !== null && $scoreDiff > 0): ?>
                                <div style="font-size: 11px; color: #e91e63; background: rgba(233, 30, 99, 0.1); padding: 3px 6px; border-radius: 4px; display: inline-block;">
                                    ↓ <?php echo number_format($scoreDiff, 2); ?> puan
                                    (-%<?php echo number_format($percentDiff, 1); ?>)
                                </div>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php
                        $previousScore = $pData['yearlyTotal'];
                    endforeach;
                    ?>
                </tbody>
                </table>
            </div>

            <!-- Performans İçgörüleri -->
            <div style="margin-top: 30px; padding: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 12px;">
                <h4 style="color: white; margin: 0 0 20px 0; font-size: 18px; display: flex; align-items: center; gap: 10px;">
                    <span style="font-size: 24px;">🏆</span> Yıllık Sıralama İstatistikleri
                </h4>
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px;">
                    <?php
                    // Her personel için aylık sıralama istatistiklerini hesapla
                    $rankingStats = [];
                    foreach ($personnelMonthlyData as $pData) {
                        $rankingStats[$pData['name']] = [
                            1 => 0, 2 => 0, 3 => 0, 4 => 0, 'other' => 0
                        ];
                    }

                    // $monthlyRankings zaten yukarıda hesaplandı, her ay için sıralamaları say
                    for ($monthIndex = 0; $monthIndex < 12; $monthIndex++) {
                        if (isset($monthlyRankings[$monthIndex])) {
                            foreach ($monthlyRankings[$monthIndex] as $personName => $rank) {
                                if ($rank <= 4) {
                                    $rankingStats[$personName][$rank]++;
                                } else {
                                    $rankingStats[$personName]['other']++;
                                }
                            }
                        }
                    }

                    // Sıralamaları yıllık performansa göre göster
                    foreach ($personnelMonthlyData as $pData):
                        $stats = $rankingStats[$pData['name']];
                        $totalMonths = array_sum($stats);
                    ?>
                    <div style="background: white; border-radius: 10px; padding: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.1);">
                        <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 15px; padding-bottom: 12px; border-bottom: 2px solid #f0f0f0;">
                            <div style="width: 50px; height: 50px; border-radius: 50%; background: linear-gradient(135deg, <?php echo $pData['color']; ?> 0%, <?php echo $pData['color']; ?> 100%); display: flex; align-items: center; justify-content: center; color: white; font-weight: 700; font-size: 20px;">
                                <?php echo strtoupper(mb_substr($pData['name'], 0, 1)); ?>
                            </div>
                            <div style="flex: 1;">
                                <div style="font-weight: 700; color: #2c3e50; font-size: 16px;">
                                    <?php echo htmlspecialchars($pData['name']); ?>
                                </div>
                                <div style="font-size: 12px; color: #999;">
                                    <?php echo number_format($pData['yearlyTotal'], 2); ?> puan
                                </div>
                            </div>
                        </div>

                        <div style="display: flex; flex-direction: column; gap: 8px;">
                            <?php if ($stats[1] > 0): ?>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div style="font-size: 22px; width: 30px; text-align: center;">🥇</div>
                                <div style="flex: 1;">
                                    <div style="background: #4CAF50; height: 8px; border-radius: 4px; width: <?php echo ($stats[1] / $totalMonths) * 100; ?>%;"></div>
                                </div>
                                <div style="font-weight: 700; color: #4CAF50; min-width: 60px; text-align: right;">
                                    <?php echo $stats[1]; ?> ay (<?php echo round(($stats[1] / $totalMonths) * 100); ?>%)
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php if ($stats[2] > 0): ?>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div style="font-size: 22px; width: 30px; text-align: center;">🥈</div>
                                <div style="flex: 1;">
                                    <div style="background: #81C784; height: 8px; border-radius: 4px; width: <?php echo ($stats[2] / $totalMonths) * 100; ?>%;"></div>
                                </div>
                                <div style="font-weight: 700; color: #81C784; min-width: 60px; text-align: right;">
                                    <?php echo $stats[2]; ?> ay (<?php echo round(($stats[2] / $totalMonths) * 100); ?>%)
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php if ($stats[3] > 0): ?>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div style="font-size: 22px; width: 30px; text-align: center;">🥉</div>
                                <div style="flex: 1;">
                                    <div style="background: #C8E6C9; height: 8px; border-radius: 4px; width: <?php echo ($stats[3] / $totalMonths) * 100; ?>%;"></div>
                                </div>
                                <div style="font-weight: 700; color: #66BB6A; min-width: 60px; text-align: right;">
                                    <?php echo $stats[3]; ?> ay (<?php echo round(($stats[3] / $totalMonths) * 100); ?>%)
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php if ($stats[4] > 0): ?>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div style="font-size: 18px; width: 30px; text-align: center; color: #666;">4️⃣</div>
                                <div style="flex: 1;">
                                    <div style="background: #FFF9C4; height: 8px; border-radius: 4px; width: <?php echo ($stats[4] / $totalMonths) * 100; ?>%;"></div>
                                </div>
                                <div style="font-weight: 700; color: #FBC02D; min-width: 60px; text-align: right;">
                                    <?php echo $stats[4]; ?> ay (<?php echo round(($stats[4] / $totalMonths) * 100); ?>%)
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php if ($stats['other'] > 0): ?>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <div style="font-size: 18px; width: 30px; text-align: center; color: #999;">📊</div>
                                <div style="flex: 1;">
                                    <div style="background: #e0e0e0; height: 8px; border-radius: 4px; width: <?php echo ($stats['other'] / $totalMonths) * 100; ?>%;"></div>
                                </div>
                                <div style="font-weight: 700; color: #999; min-width: 60px; text-align: right;">
                                    <?php echo $stats['other']; ?> ay (<?php echo round(($stats['other'] / $totalMonths) * 100); ?>%)
                                </div>
                            </div>
                            <?php endif; ?>

                            <?php if ($totalMonths == 0): ?>
                            <div style="text-align: center; color: #999; padding: 20px;">
                                Henüz veri yok
                            </div>
                            <?php endif; ?>
                        </div>

                        <!-- En iyi performans ay -->
                        <?php
                        $bestMonth = null;
                        $bestScore = 0;
                        foreach ($pData['data'] as $idx => $score) {
                            if ($score > $bestScore) {
                                $bestScore = $score;
                                $bestMonth = $idx;
                            }
                        }
                        if ($bestMonth !== null):
                        ?>
                        <div style="margin-top: 15px; padding-top: 15px; border-top: 2px solid #f0f0f0; font-size: 12px; color: #666; text-align: center;">
                            <span style="font-weight: 600;">En İyi Ay:</span>
                            <?php echo $monthlyLabels[$bestMonth]; ?> (<?php echo number_format($bestScore, 2); ?> puan)
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>

        <!-- Aylık Prim Tutarları Tablosu -->
        <div class="card" style="grid-column: 1 / -1; margin-top: 30px;">
            <h3 class="card-title">Aylık Prim Tutarları ve Yıllık Gelir - <?php echo $selectedYearForReport; ?></h3>

            <!-- Gösterilecek Veriler Toggle -->
            <div style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                <label style="display: block; margin-bottom: 10px; font-weight: 600; color: #2c3e50;">
                    <i class="fas fa-chart-bar"></i> Tablo Görünümü:
                </label>
                <div style="display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px;">
                    <button class="toggle-bonus-data-btn active" data-view="monthly-bonus"
                        style="padding: 8px 16px; border: 2px solid #667eea; background: #667eea; color: white; border-radius: 6px; cursor: pointer; font-weight: 600; transition: all 0.3s;">
                        💰 Aylık Prim Tutarları
                    </button>
                    <button class="toggle-bonus-data-btn" data-view="yearly-income"
                        style="padding: 8px 16px; border: 2px solid #667eea; background: white; color: #667eea; border-radius: 6px; cursor: pointer; font-weight: 600; transition: all 0.3s;">
                        💵 Yıllık Gelir Dağılımı
                    </button>
                </div>

                <label style="display: block; margin-bottom: 10px; font-weight: 600; color: #2c3e50;">
                    <i class="fas fa-filter"></i> Gösterilecek Personeller:
                </label>
                <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                    <?php
                    $colors = ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40', '#FF6384', '#C9CBCF'];
                    $colorIndex = 0;
                    foreach ($personnelMonthlyData as $pData):
                        $color = $colors[$colorIndex % count($colors)];
                        $colorIndex++;
                    ?>
                    <button class="toggle-bonus-person-btn active" data-person="<?php echo htmlspecialchars($pData['name']); ?>"
                        style="padding: 6px 14px; border: 2px solid <?php echo $color; ?>; background: <?php echo $color; ?>; color: white; border-radius: 6px; cursor: pointer; font-size: 13px; font-weight: 600; transition: all 0.3s;">
                        <?php echo htmlspecialchars($pData['name']); ?>
                    </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Aylık Prim Tutarları Tablosu -->
            <div id="monthly-bonus-table" class="bonus-data-view" style="display: block;">
                <div class="table-scroll-wrapper">
                    <table class="performance-table" style="border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th style="border: 2px solid #ddd; padding: 12px;">Personel</th>
                            <?php foreach ($monthlyLabels as $monthLabel): ?>
                            <th style="border: 2px solid #ddd; padding: 12px;"><?php echo $monthLabel; ?></th>
                            <?php endforeach; ?>
                            <th style="background: #667eea; border: 2px solid #ddd; padding: 12px;">Yıllık Prim</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Personelleri yıllık prim toplamına göre sırala
                        $sortedBonusData = [];
                        foreach ($personnelMonthlyData as $pData) {
                            $personName = $pData['name'];
                            $sortedBonusData[] = [
                                'name' => $personName,
                                'yearlyBonus' => $yearlyBonusTotals[$personName] ?? 0,
                                'monthlyBonuses' => $monthlyBonusData[$personName] ?? array_fill(1, 12, 0)
                            ];
                        }
                        usort($sortedBonusData, function($a, $b) {
                            return $b['yearlyBonus'] <=> $a['yearlyBonus'];
                        });

                        $previousBonus = null;
                        $bonusRank = 0;
                        foreach ($sortedBonusData as $bonusData):
                            $bonusRank++;
                            $bonusDiff = null;
                            $bonusPercentDiff = null;

                            if ($previousBonus !== null && $previousBonus > 0) {
                                $bonusDiff = $previousBonus - $bonusData['yearlyBonus'];
                                $bonusPercentDiff = ($bonusDiff / $previousBonus) * 100;
                            }
                        ?>
                        <tr class="bonus-person-row" data-person="<?php echo htmlspecialchars($bonusData['name']); ?>">
                            <td style="border: 2px solid #ddd; padding: 12px;"><strong><?php echo htmlspecialchars($bonusData['name']); ?></strong></td>
                            <?php for ($month = 1; $month <= 12; $month++):
                                $monthBonus = $bonusData['monthlyBonuses'][$month] ?? 0;
                                // Renk kodlama: Prim alan = yeşil, almayan = gri
                                $cellStyle = $monthBonus > 0
                                    ? 'background: rgba(76, 175, 80, 0.1); color: #2c3e50;'
                                    : 'background: #fafafa; color: #999;';
                            ?>
                            <td style="border: 2px solid #ddd; padding: 12px; <?php echo $cellStyle; ?>">
                                <div style="text-align: center; font-weight: 600;">
                                    <?php echo $monthBonus > 0 ? number_format($monthBonus, 0) . ' ₺' : '-'; ?>
                                </div>
                            </td>
                            <?php endfor; ?>
                            <td style="background: rgba(102, 126, 234, 0.1); font-weight: 700; border: 2px solid #ddd; padding: 12px;">
                                <div style="display: flex; flex-direction: column; gap: 5px;">
                                    <div style="font-size: 16px; color: #2c3e50;">
                                        <?php echo number_format($bonusData['yearlyBonus'], 0); ?> ₺
                                    </div>
                                    <div style="font-size: 12px; color: #667eea; font-weight: 600;">
                                        Aylık Ort: <?php echo number_format($bonusData['yearlyBonus'] / 12, 0); ?> ₺
                                    </div>
                                    <?php if ($bonusDiff !== null && $bonusDiff > 0): ?>
                                    <div style="font-size: 11px; color: #e91e63; background: rgba(233, 30, 99, 0.1); padding: 3px 6px; border-radius: 4px; display: inline-block;">
                                        ↓ <?php echo number_format($bonusDiff, 0); ?> ₺
                                        (-%<?php echo number_format($bonusPercentDiff, 1); ?>)
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php
                            $previousBonus = $bonusData['yearlyBonus'];
                        endforeach;
                        ?>
                    </tbody>
                    </table>
                </div>
            </div>

            <!-- Yıllık Gelir Dağılımı Tablosu -->
            <div id="yearly-income-table" class="bonus-data-view" style="display: none;">
                <div class="table-scroll-wrapper">
                    <table class="performance-table" style="border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th style="border: 2px solid #ddd; padding: 12px;">Personel</th>
                            <th style="border: 2px solid #ddd; padding: 12px;">Aylık Maaş</th>
                            <th style="border: 2px solid #ddd; padding: 12px;">Yıllık Maaş (12 Ay)</th>
                            <th style="border: 2px solid #ddd; padding: 12px;">Yıllık Prim Toplamı</th>
                            <th style="background: #667eea; border: 2px solid #ddd; padding: 12px;">Toplam Yıllık Gelir</th>
                            <th style="background: #764ba2; border: 2px solid #ddd; padding: 12px; color: white;">Ortalama Aylık Gelir</th>
                            <th style="border: 2px solid #ddd; padding: 12px;">Prim Oranı</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Personelleri yıllık gelir toplamına göre sırala
                        $sortedIncomeData = [];
                        foreach ($personnelMonthlyData as $pData) {
                            $personName = $pData['name'];
                            $monthlySalary = $personnelSalaries[$personName] ?? 0;
                            $yearlySalary = $monthlySalary * 12;
                            $yearlyBonus = $yearlyBonusTotals[$personName] ?? 0;
                            $totalIncome = $yearlyIncomeTotals[$personName] ?? 0;

                            $sortedIncomeData[] = [
                                'name' => $personName,
                                'monthlySalary' => $monthlySalary,
                                'yearlySalary' => $yearlySalary,
                                'yearlyBonus' => $yearlyBonus,
                                'totalIncome' => $totalIncome
                            ];
                        }
                        usort($sortedIncomeData, function($a, $b) {
                            return $b['totalIncome'] <=> $a['totalIncome'];
                        });

                        $previousIncome = null;
                        $incomeRank = 0;
                        foreach ($sortedIncomeData as $incomeData):
                            $incomeRank++;
                            $incomeDiff = null;
                            $incomePercentDiff = null;

                            if ($previousIncome !== null && $previousIncome > 0) {
                                $incomeDiff = $previousIncome - $incomeData['totalIncome'];
                                $incomePercentDiff = ($incomeDiff / $previousIncome) * 100;
                            }

                            // Prim oranı hesapla (toplam gelirin yüzde kaçı prim?)
                            $bonusRate = $incomeData['totalIncome'] > 0
                                ? ($incomeData['yearlyBonus'] / $incomeData['totalIncome']) * 100
                                : 0;
                        ?>
                        <tr class="bonus-person-row" data-person="<?php echo htmlspecialchars($incomeData['name']); ?>">
                            <td style="border: 2px solid #ddd; padding: 12px;"><strong><?php echo htmlspecialchars($incomeData['name']); ?></strong></td>
                            <td style="border: 2px solid #ddd; padding: 12px; text-align: center;">
                                <?php echo number_format($incomeData['monthlySalary'], 0); ?> ₺
                            </td>
                            <td style="border: 2px solid #ddd; padding: 12px; text-align: center; background: rgba(33, 150, 243, 0.05);">
                                <?php echo number_format($incomeData['yearlySalary'], 0); ?> ₺
                            </td>
                            <td style="border: 2px solid #ddd; padding: 12px; text-align: center; background: rgba(76, 175, 80, 0.05);">
                                <?php echo number_format($incomeData['yearlyBonus'], 0); ?> ₺
                            </td>
                            <td style="background: rgba(102, 126, 234, 0.1); font-weight: 700; border: 2px solid #ddd; padding: 12px;">
                                <div style="display: flex; flex-direction: column; gap: 5px;">
                                    <div style="font-size: 16px; color: #2c3e50; text-align: center;">
                                        <?php echo number_format($incomeData['totalIncome'], 0); ?> ₺
                                    </div>
                                    <?php if ($incomeDiff !== null && $incomeDiff > 0): ?>
                                    <div style="font-size: 11px; color: #e91e63; background: rgba(233, 30, 99, 0.1); padding: 3px 6px; border-radius: 4px; display: inline-block; text-align: center;">
                                        ↓ <?php echo number_format($incomeDiff, 0); ?> ₺
                                        (-%<?php echo number_format($incomePercentDiff, 1); ?>)
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td style="background: rgba(118, 75, 162, 0.1); font-weight: 700; border: 2px solid #ddd; padding: 12px;">
                                <div style="display: flex; flex-direction: column; gap: 5px;">
                                    <div style="font-size: 16px; color: #2c3e50; text-align: center;">
                                        <?php
                                        $averageMonthlyIncome = $incomeData['totalIncome'] / 12;
                                        echo number_format($averageMonthlyIncome, 0);
                                        ?> ₺
                                    </div>
                                    <?php
                                    // Ortalama aylık gelir farkını hesapla
                                    if ($previousIncome !== null && $previousIncome > 0) {
                                        $previousAvgMonthly = $previousIncome / 12;
                                        $avgMonthlyDiff = $previousAvgMonthly - $averageMonthlyIncome;
                                        $avgMonthlyPercentDiff = ($avgMonthlyDiff / $previousAvgMonthly) * 100;

                                        if ($avgMonthlyDiff > 0):
                                    ?>
                                    <div style="font-size: 11px; color: #e91e63; background: rgba(233, 30, 99, 0.1); padding: 3px 6px; border-radius: 4px; display: inline-block; text-align: center;">
                                        ↓ <?php echo number_format($avgMonthlyDiff, 0); ?> ₺
                                        (-%<?php echo number_format($avgMonthlyPercentDiff, 1); ?>)
                                    </div>
                                    <?php
                                        endif;
                                    }
                                    ?>
                                </div>
                            </td>
                            <td style="border: 2px solid #ddd; padding: 12px; text-align: center;">
                                <div style="display: inline-block; padding: 5px 12px; border-radius: 20px; font-weight: 600;
                                    <?php
                                    if ($bonusRate >= 20) echo 'background: #4CAF50; color: white;';
                                    elseif ($bonusRate >= 15) echo 'background: #8BC34A; color: white;';
                                    elseif ($bonusRate >= 10) echo 'background: #FFC107; color: #333;';
                                    else echo 'background: #f5f5f5; color: #999;';
                                    ?>">
                                    %<?php echo number_format($bonusRate, 1); ?>
                                </div>
                            </td>
                        </tr>
                        <?php
                            $previousIncome = $incomeData['totalIncome'];
                        endforeach;
                        ?>
                    </tbody>
                    </table>
                </div>
            </div>
        </div>

        <script>
        // Tablo görünümü toggle butonları (Aylık Prim / Yıllık Gelir)
        document.querySelectorAll('.toggle-bonus-data-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const viewType = this.dataset.view;

                // Tüm butonları deaktif et
                document.querySelectorAll('.toggle-bonus-data-btn').forEach(b => {
                    b.classList.remove('active');
                    b.style.background = 'white';
                    b.style.color = '#667eea';
                });

                // Bu butonu aktif et
                this.classList.add('active');
                this.style.background = '#667eea';
                this.style.color = 'white';

                // Tüm tabloları gizle
                document.querySelectorAll('.bonus-data-view').forEach(view => {
                    view.style.display = 'none';
                });

                // Seçilen tabloyu göster
                if (viewType === 'monthly-bonus') {
                    document.getElementById('monthly-bonus-table').style.display = 'block';
                } else if (viewType === 'yearly-income') {
                    document.getElementById('yearly-income-table').style.display = 'block';
                }
            });
        });

        // Personel toggle butonları için event listener
        document.querySelectorAll('.toggle-bonus-person-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const personName = this.dataset.person;
                const isActive = this.classList.contains('active');

                if (isActive) {
                    // Devre dışı bırak - personeli gizle
                    this.classList.remove('active');
                    this.style.background = 'white';
                    this.style.borderColor = this.style.borderColor; // Kenarlık rengini koru
                    this.style.color = '#999';
                    this.style.opacity = '0.5';

                    // Bu personelin tüm satırlarını gizle (her iki tabloda da)
                    document.querySelectorAll(`.bonus-person-row[data-person="${personName}"]`).forEach(row => {
                        row.style.display = 'none';
                    });
                } else {
                    // Aktif et - personeli göster
                    this.classList.add('active');
                    const borderColor = this.style.borderColor;
                    this.style.background = borderColor;
                    this.style.color = 'white';
                    this.style.opacity = '1';

                    // Bu personelin tüm satırlarını göster (her iki tabloda da)
                    document.querySelectorAll(`.bonus-person-row[data-person="${personName}"]`).forEach(row => {
                        row.style.display = 'table-row';
                    });
                }
            });
        });
        </script>

        <!-- Bonus Kriterleri Etki Analizi -->
        <div class="card" style="grid-column: 1 / -1; margin-top: 30px;">
            <h3 class="card-title">🔍 Bonus Kriterleri Etki Analizi - <?php echo $selectedYearForReport; ?></h3>
            <p style="color: #666; margin-bottom: 20px; font-size: 14px;">
                Bonus kriterlerini devre dışı bırakarak, performans puanlarına etkilerini görebilirsiniz.
            </p>

            <!-- Bonus Kriterleri Seçimi -->
            <div style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px;">
                <label style="display: block; margin-bottom: 10px; font-weight: 600; color: #2c3e50;">
                    <i class="fas fa-filter"></i> Dahil Edilecek Bonus Kriterleri:
                </label>
                <div style="display: flex; flex-wrap: wrap; gap: 10px;">
                    <?php
                    $bonusCriteriaList = [
                        'sopyo_logo' => ['name' => 'Sopyo Logo', 'point' => 1.0],
                        'sopyo_nebim' => ['name' => 'Sopyo Nebim', 'point' => 1.0],
                        'sopyo_nebim_v3' => ['name' => 'Sopyo Nebim v3', 'point' => 1.0],
                        'lisans_yenileme' => ['name' => 'Lisans Yenileme', 'point' => 0.25],
                        'google_yorum' => ['name' => 'Google Yorum', 'point' => 1.0]
                    ];

                    foreach ($bonusCriteriaList as $criteriaKey => $criteriaInfo):
                    ?>
                    <button class="toggle-bonus-criteria-btn active" data-criteria="<?php echo $criteriaKey; ?>"
                        style="padding: 8px 16px; border: 2px solid #4CAF50; background: #4CAF50; color: white; border-radius: 6px; cursor: pointer; font-weight: 600; transition: all 0.3s; display: flex; align-items: center; gap: 8px;">
                        <span class="criteria-icon">✓</span>
                        <?php echo $criteriaInfo['name']; ?>
                        <span style="font-size: 11px; opacity: 0.8;">(<?php echo $criteriaInfo['point']; ?> puan)</span>
                    </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Etki Analizi Tablosu -->
            <div class="table-scroll-wrapper">
                <table class="performance-table" style="border-collapse: collapse;">
                    <thead>
                        <tr>
                            <th style="border: 2px solid #ddd; padding: 12px;">Personel</th>
                            <?php foreach ($monthlyLabels as $monthLabel): ?>
                            <th style="border: 2px solid #ddd; padding: 12px;"><?php echo $monthLabel; ?></th>
                            <?php endforeach; ?>
                            <th style="background: #667eea; border: 2px solid #ddd; padding: 12px;">Yıllık Toplam</th>
                            <th style="background: #f44336; border: 2px solid #ddd; padding: 12px;">Fark</th>
                        </tr>
                    </thead>
                    <tbody id="bonus-impact-table-body">
                        <?php foreach ($personnelMonthlyData as $pData): ?>
                        <tr class="impact-person-row" data-person="<?php echo htmlspecialchars($pData['name']); ?>">
                            <td style="border: 2px solid #ddd; padding: 12px;">
                                <strong><?php echo htmlspecialchars($pData['name']); ?></strong>
                            </td>
                            <?php foreach ($pData['data'] as $monthIndex => $monthValue): ?>
                            <td class="impact-month-cell"
                                data-person="<?php echo htmlspecialchars($pData['name']); ?>"
                                data-month="<?php echo $monthIndex; ?>"
                                data-original="<?php echo $monthValue; ?>"
                                style="border: 2px solid #ddd; padding: 12px; text-align: center;">
                                <div class="impact-value"><?php echo number_format($monthValue, 2); ?></div>
                                <div class="impact-diff" style="font-size: 11px; color: #f44336; display: none;"></div>
                            </td>
                            <?php endforeach; ?>
                            <td class="impact-yearly-total"
                                data-person="<?php echo htmlspecialchars($pData['name']); ?>"
                                data-original="<?php echo $pData['yearlyTotal']; ?>"
                                style="background: rgba(102, 126, 234, 0.1); font-weight: 700; border: 2px solid #ddd; padding: 12px; text-align: center;">
                                <div class="impact-total-value"><?php echo number_format($pData['yearlyTotal'], 2); ?></div>
                                <div class="impact-total-diff" style="font-size: 11px; color: #f44336; display: none;"></div>
                            </td>
                            <td class="impact-difference"
                                data-person="<?php echo htmlspecialchars($pData['name']); ?>"
                                style="background: rgba(244, 67, 54, 0.05); font-weight: 700; border: 2px solid #ddd; padding: 12px; text-align: center;">
                                <div style="font-size: 14px; color: #2c3e50;">0.00</div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <script>
            // Bonus kriterleri ve paket eşleşmeleri
            const bonusCriteriaData = <?php echo json_encode($bonusCriteriaList); ?>;

            // Her personel için her ayın paket sayılarını sakla
            const personnelPackageData = <?php
                $packageDataByPerson = [];
                foreach ($yearlyScores as $personName => $monthlyData) {
                    if (!isset($packageDataByPerson[$personName])) {
                        $packageDataByPerson[$personName] = [];
                    }
                    foreach ($monthlyData as $month => $data) {
                        if (is_array($data) && isset($data['package_counts'])) {
                            $packageDataByPerson[$personName][$month] = $data['package_counts'];
                        } else {
                            $packageDataByPerson[$personName][$month] = [];
                        }
                    }
                }
                echo json_encode($packageDataByPerson);
            ?>;

            // Aktif bonus kriterleri
            let activeBonusCriteria = new Set(Object.keys(bonusCriteriaData));

            // Toggle bonus criteria
            document.querySelectorAll('.toggle-bonus-criteria-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    const criteria = this.dataset.criteria;
                    const isActive = this.classList.contains('active');

                    if (isActive) {
                        // Devre dışı bırak
                        this.classList.remove('active');
                        this.style.background = 'white';
                        this.style.color = '#999';
                        this.querySelector('.criteria-icon').textContent = '✗';
                        activeBonusCriteria.delete(criteria);
                    } else {
                        // Aktif et
                        this.classList.add('active');
                        this.style.background = '#4CAF50';
                        this.style.color = 'white';
                        this.querySelector('.criteria-icon').textContent = '✓';
                        activeBonusCriteria.add(criteria);
                    }

                    // Puanları yeniden hesapla
                    recalculateImpactScores();
                });
            });

            function recalculateImpactScores() {
                // Her personel için hesapla
                document.querySelectorAll('.impact-person-row').forEach(row => {
                    const personName = row.dataset.person;
                    let yearlyTotal = 0;

                    // Her ay için hesapla
                    row.querySelectorAll('.impact-month-cell').forEach(cell => {
                        const month = parseInt(cell.dataset.month) + 1;
                        const originalScore = parseFloat(cell.dataset.original);

                        // Bu ay için paket verilerini al
                        const packageCounts = personnelPackageData[personName]?.[month] || {};

                        // Devre dışı bırakılan kriterlerin etkisini çıkar
                        let removedPoints = 0;

                        // Sopyo Logo
                        if (!activeBonusCriteria.has('sopyo_logo')) {
                            const logoCount = Object.entries(packageCounts).find(([pkg]) =>
                                pkg.toLowerCase().includes('sopyo logo'))?.[1] || 0;
                            removedPoints += logoCount * 1.0;
                        }

                        // Sopyo Nebim
                        if (!activeBonusCriteria.has('sopyo_nebim')) {
                            const nebimCount = Object.entries(packageCounts).find(([pkg]) =>
                                pkg.toLowerCase().includes('sopyo nebim') && !pkg.toLowerCase().includes('v3'))?.[1] || 0;
                            removedPoints += nebimCount * 1.0;
                        }

                        // Sopyo Nebim v3
                        if (!activeBonusCriteria.has('sopyo_nebim_v3')) {
                            const nebimV3Count = Object.entries(packageCounts).find(([pkg]) =>
                                pkg.toLowerCase().includes('sopyo nebim v3'))?.[1] || 0;
                            removedPoints += nebimV3Count * 1.0;
                        }

                        // Lisans Yenileme
                        if (!activeBonusCriteria.has('lisans_yenileme')) {
                            const lisansCount = Object.entries(packageCounts).find(([pkg]) =>
                                pkg.toLowerCase().includes('lisans yenileme'))?.[1] || 0;
                            removedPoints += lisansCount * 0.25;
                        }

                        // Google Yorum
                        if (!activeBonusCriteria.has('google_yorum')) {
                            const googleCount = Object.entries(packageCounts).find(([pkg]) =>
                                pkg.toLowerCase().includes('google yorum'))?.[1] || 0;
                            removedPoints += googleCount * 1.0;
                        }

                        const newScore = Math.max(0, originalScore - removedPoints);
                        const diff = originalScore - newScore;

                        yearlyTotal += newScore;

                        // Hücreyi güncelle
                        cell.querySelector('.impact-value').textContent = newScore.toFixed(2);
                        const diffEl = cell.querySelector('.impact-diff');
                        if (diff > 0) {
                            diffEl.textContent = '-' + diff.toFixed(2);
                            diffEl.style.display = 'block';
                        } else {
                            diffEl.style.display = 'none';
                        }
                    });

                    // Yıllık toplamı güncelle
                    const yearlyCell = row.querySelector('.impact-yearly-total');
                    const originalYearly = parseFloat(yearlyCell.dataset.original);
                    const yearlyDiff = originalYearly - yearlyTotal;

                    yearlyCell.querySelector('.impact-total-value').textContent = yearlyTotal.toFixed(2);
                    const totalDiffEl = yearlyCell.querySelector('.impact-total-diff');
                    if (yearlyDiff > 0) {
                        totalDiffEl.textContent = '-' + yearlyDiff.toFixed(2) + ' puan';
                        totalDiffEl.style.display = 'block';
                    } else {
                        totalDiffEl.style.display = 'none';
                    }

                    // Fark kolonunu güncelle
                    const diffCell = row.querySelector('.impact-difference div');
                    if (yearlyDiff > 0) {
                        diffCell.textContent = '-' + yearlyDiff.toFixed(2) + ' puan';
                        diffCell.style.color = '#f44336';
                    } else {
                        diffCell.textContent = '0.00';
                        diffCell.style.color = '#2c3e50';
                    }
                });
            }
            </script>
        </div>

        <!-- Yeni Satış Analizi -->
        <div class="card" style="grid-column: 1 / -1; margin-top: 30px;">
            <h3 class="card-title">💼 Eğitim Tamamlama Performansı - <?php echo $selectedYearForReport; ?></h3>
            <p style="color: #666; margin-bottom: 20px; font-size: 14px;">
                <strong>Satış Tipi:</strong> Yeni Satış | <strong>Hariç Tutulanlar:</strong> Google Yorum, Lisans Yenileme
            </p>

            <?php if (!empty($newSalesData)): ?>
            <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 20px;">
                <?php
                $colors = [
                    '#667eea', '#764ba2', '#f093fb', '#4facfe',
                    '#43e97b', '#fa709a', '#30cfd0', '#c471ed'
                ];
                $colorIndex = 0;
                foreach ($newSalesData as $salesData):
                    $color = $colors[$colorIndex % count($colors)];
                    $colorIndex++;
                ?>
                <div style="background: linear-gradient(135deg, <?php echo $color; ?>dd 0%, <?php echo $color; ?>99 100%);
                            padding: 20px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);
                            transition: all 0.3s; cursor: pointer; color: white;"
                     onmouseover="this.style.transform='translateY(-5px)'; this.style.boxShadow='0 8px 20px rgba(0,0,0,0.2)';"
                     onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 12px rgba(0,0,0,0.1)';">

                    <!-- Personel İsmi -->
                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 15px;">
                        <div style="width: 50px; height: 50px; background: rgba(255,255,255,0.3); border-radius: 50%;
                                    display: flex; align-items: center; justify-content: center; font-size: 24px; font-weight: 700;">
                            <?php echo strtoupper(substr($salesData['full_name'], 0, 1)); ?>
                        </div>
                        <div style="flex: 1;">
                            <div style="font-size: 18px; font-weight: 700;">
                                <?php echo htmlspecialchars($salesData['full_name']); ?>
                            </div>
                        </div>
                    </div>

                    <!-- İstatistikler -->
                    <div style="background: rgba(255,255,255,0.2); border-radius: 8px; padding: 15px; margin-bottom: 10px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <div style="font-size: 12px; opacity: 0.9; margin-bottom: 5px;">Tamamlanan Eğitim</div>
                                <div style="font-size: 32px; font-weight: 700;">
                                    <?php echo number_format($salesData['total_trainings']); ?>
                                </div>
                            </div>
                            <div style="font-size: 40px; opacity: 0.3;">🎓</div>
                        </div>
                    </div>

                    <!-- Aylık Ortalama -->
                    <div style="background: rgba(255,255,255,0.15); border-radius: 8px; padding: 12px; display: flex; align-items: center; gap: 10px;">
                        <div style="font-size: 20px;">📊</div>
                        <div style="flex: 1;">
                            <div style="font-size: 11px; opacity: 0.8;">Aylık Ortalama (12 Ay)</div>
                            <div style="font-size: 20px; font-weight: 600;">
                                <?php echo number_format($salesData['monthly_avg'], 2); ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php else: ?>
            <div style="text-align: center; padding: 40px; color: #999;">
                <div style="font-size: 48px; margin-bottom: 20px;">📭</div>
                <div style="font-size: 16px;">
                    <?php echo $selectedYearForReport; ?> yılında "Yeni Satış" kategorisinde veri bulunamadı.
                </div>
            </div>
            <?php endif; ?>
        </div>



    <!-- Detaylı Performans Tablosu -->
    <div class="data-table-container">
        <h3 class="card-title">Detaylı Performans Tablosu</h3>
        <div class="table-scroll-wrapper">
            <table class="performance-table">
                <thead>
                    <tr>
                        <th>Çalışan</th>
                        <th>Dahili</th>
                        <th>Gelen Çağrı (Yanıtlanan)</th>
                        <th>Yanıt Oranı</th>
                        <th>Gelen Süre</th>
                        <th>Giden Çağrı</th>
                        <th>Giden Süre</th>
                        <th>Eğitim</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($performanceData)): ?>
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 40px; color: #7f8c8d;">
                            Seçilen tarih aralığında veri bulunamadı.
                        </td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($performanceData as $row): ?>
                        <tr>
                            <td><strong><?php echo htmlspecialchars($row['full_name']); ?></strong></td>
                            <td><?php echo htmlspecialchars($row['extension'] ?? '-'); ?></td>
                            <td><?php echo number_format($row['total_answered']); ?></td>
                            <td>
                                <span style="color: <?php echo $row['avg_answer_rate'] >= 80 ? '#2e7d32' : ($row['avg_answer_rate'] >= 60 ? '#f57c00' : '#c62828'); ?>; font-weight: 600;">
                                    %<?php echo number_format($row['avg_answer_rate'], 1); ?>
                                </span>
                            </td>
                            <td><?php echo $row['total_incoming_duration']; ?></td>
                            <td><?php echo number_format($row['total_outgoing']); ?></td>
                            <td><?php echo $row['total_outgoing_duration']; ?></td>
                            <td>
                                <span style="background: #e3f2fd; color: #1565c0; padding: 4px 8px; border-radius: 12px; font-weight: 600;">
                                    <?php echo $row['training_count']; ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- İçgörüler / Insights -->
    <div class="insights-wrapper">
        <div class="insights-section">
            <h2 style="margin-bottom: 20px; color: #2c3e50;">💡 İçgörüler</h2>

            <?php if ($endDate >= $currentMonthStart && $endDate <= $today): ?>
            <div class="notification info" style="margin-bottom: 20px;">
                <div style="display: flex; align-items: center; gap: 10px;">
                    <div style="font-size: 20px;">📅</div>
                    <div>
                        <strong>Dönem Karşılaştırma Bilgisi:</strong>
                        Seçilen dönem: <strong><?php echo date('d/m/Y', strtotime($startDate)); ?> - <?php echo date('d/m/Y', strtotime($endDate)); ?></strong><br>
                        Karşılaştırılan dönem: <strong><?php echo date('d/m/Y', strtotime($prevStartDate)); ?> - <?php echo date('d/m/Y', strtotime($prevEndDate)); ?></strong>
                        <br><small style="opacity: 0.8;">Ay henüz tamamlanmadığı için gün bazlı karşılaştırma yapılmaktadır.</small>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="insights-grid">
            <!-- En İyi Performans -->
            <?php if ($topPerformer): ?>
            <div class="insight-card green">
                <div class="insight-header">
                    <span class="insight-icon">🏆</span>
                    <span>EN İYİ PERFORMANS</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($topPerformer['full_name']); ?></div>
                <div class="insight-label">En Fazla Çağrı</div>
                <div class="insight-detail">
                    📞 <?php echo number_format($topPerformer['total_answered']); ?> gelen çağrı yanıtladı
                </div>
                <div class="insight-detail">
                    📱 <?php echo number_format($topPerformer['total_outgoing']); ?> giden çağrı yaptı
                </div>
            </div>
            <?php endif; ?>

            <!-- En Uzun Görüşme -->
            <?php if ($topByDuration): ?>
            <div class="insight-card blue">
                <div class="insight-header">
                    <span class="insight-icon">⏱️</span>
                    <span>EN UZUN GÖRÜŞME</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($topByDuration['full_name']); ?></div>
                <div class="insight-label"><?php echo $topByDuration['total_incoming_duration']; ?> toplam süre</div>
                <div class="insight-detail">
                    Yaklaşık <?php echo round($maxDuration / 60, 1); ?> saat görüşme
                </div>
            </div>
            <?php endif; ?>

            <!-- En Yüksek Yanıt Oranı -->
            <?php if ($topAnswerRate): ?>
            <div class="insight-card orange">
                <div class="insight-header">
                    <span class="insight-icon">📈</span>
                    <span>EN YÜKSEK YANITLAMA</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($topAnswerRate['full_name']); ?></div>
                <div class="insight-label">%<?php echo number_format($topAnswerRate['avg_answer_rate'], 1); ?> yanıt oranı</div>
                <div class="insight-detail">
                    <?php echo number_format($topAnswerRate['total_answered']); ?> çağrıdan hesaplandı
                </div>
            </div>
            <?php endif; ?>

            <!-- Trend Analizi -->
            <div class="insight-card">
                <div class="insight-header">
                    <span class="insight-icon">📊</span>
                    <span>DÖNEM KARŞILAŞTIRMA</span>
                </div>
                <div class="insight-value">
                    <?php if ($callsTrend > 0): ?>
                        <span style="color: #4CAF50;">↑ %<?php echo abs($callsTrend); ?></span>
                    <?php elseif ($callsTrend < 0): ?>
                        <span style="color: #F44336;">↓ %<?php echo abs($callsTrend); ?></span>
                    <?php else: ?>
                        <span>- %0</span>
                    <?php endif; ?>
                </div>
                <div class="insight-label">Önceki Döneme Göre</div>
                <div class="insight-detail">
                    Bu dönem: <?php echo number_format($currentTotalCalls); ?> çağrı
                </div>
                <div class="insight-detail">
                    Önceki dönem: <?php echo number_format($prevTotalCalls); ?> çağrı
                </div>
            </div>

            <!-- Ortalama Metrikler -->
            <div class="insight-card">
                <div class="insight-header">
                    <span class="insight-icon">📐</span>
                    <span>KİŞİ BAŞI ORTALAMA</span>
                </div>
                <div class="insight-value"><?php echo number_format($avgIncoming); ?></div>
                <div class="insight-label">Ortalama Gelen Çağrı</div>
                <div class="insight-detail">
                    📱 Ortalama <?php echo number_format($avgOutgoing); ?> giden çağrı
                </div>
                <div class="insight-detail">
                    🎓 Ortalama <?php echo number_format($avgTraining); ?> eğitim
                </div>
            </div>
        </div>
        </div>
    </div>

    <!-- Yılın En'leri -->
    <div class="insights-wrapper" style="margin-top: 30px;">
        <div class="insights-section">
            <h2 style="margin-bottom: 20px; color: #2c3e50;">🌟 <?php echo $selectedYearForReport; ?> Yılının Enleri</h2>

            <div class="insights-grid">
            <!-- En Çok Gelen Arama Karşılayan -->
            <?php if (!empty($yearlyChampions['incoming_calls'])): ?>
            <div class="insight-card green">
                <div class="insight-header">
                    <span class="insight-icon">📞</span>
                    <span>EN ÇOK GELEN ARAMA</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($yearlyChampions['incoming_calls']['full_name']); ?></div>
                <div class="insight-label"><?php echo number_format($yearlyChampions['incoming_calls']['total_answered']); ?> çağrı yanıtladı</div>
                <div class="insight-detail">
                    📊 Aylık Ortalama: <?php echo number_format($yearlyChampions['incoming_calls']['monthly_avg'], 0); ?> çağrı
                </div>
            </div>
            <?php endif; ?>

            <!-- En Çok Gelen Aramalarda Konuşan -->
            <?php if (!empty($yearlyChampions['incoming_duration'])): ?>
            <div class="insight-card blue">
                <div class="insight-header">
                    <span class="insight-icon">⏱️</span>
                    <span>EN ÇOK GELEN SÜRE</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($yearlyChampions['incoming_duration']['full_name']); ?></div>
                <div class="insight-label"><?php echo $yearlyChampions['incoming_duration']['total_hours']; ?> saat konuştu</div>
                <div class="insight-detail">
                    📊 Aylık Ortalama: <?php echo number_format($yearlyChampions['incoming_duration']['monthly_avg_minutes'], 1); ?> dakika
                </div>
            </div>
            <?php endif; ?>

            <!-- En Çok Giden Arama Yapan -->
            <?php if (!empty($yearlyChampions['outgoing_calls'])): ?>
            <div class="insight-card orange">
                <div class="insight-header">
                    <span class="insight-icon">📱</span>
                    <span>EN ÇOK GİDEN ARAMA</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($yearlyChampions['outgoing_calls']['full_name']); ?></div>
                <div class="insight-label"><?php echo number_format($yearlyChampions['outgoing_calls']['total_outgoing']); ?> çağrı yaptı</div>
                <div class="insight-detail">
                    📊 Aylık Ortalama: <?php echo number_format($yearlyChampions['outgoing_calls']['monthly_avg'], 0); ?> çağrı
                </div>
            </div>
            <?php endif; ?>

            <!-- En Çok Giden Aramalarda Konuşan -->
            <?php if (!empty($yearlyChampions['outgoing_duration'])): ?>
            <div class="insight-card purple">
                <div class="insight-header">
                    <span class="insight-icon">⏰</span>
                    <span>EN ÇOK GİDEN SÜRE</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($yearlyChampions['outgoing_duration']['full_name']); ?></div>
                <div class="insight-label"><?php echo $yearlyChampions['outgoing_duration']['total_hours']; ?> saat konuştu</div>
                <div class="insight-detail">
                    📊 Aylık Ortalama: <?php echo number_format($yearlyChampions['outgoing_duration']['monthly_avg_minutes'], 1); ?> dakika
                </div>
            </div>
            <?php endif; ?>

            <!-- En Çok Eğitim Veren -->
            <?php if (!empty($yearlyChampions['training'])): ?>
            <div class="insight-card pink">
                <div class="insight-header">
                    <span class="insight-icon">🎓</span>
                    <span>EN ÇOK EĞİTİM</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($yearlyChampions['training']['full_name']); ?></div>
                <div class="insight-label"><?php echo number_format($yearlyChampions['training']['total_training']); ?> eğitim verdi</div>
                <div class="insight-detail">
                    📊 Aylık Ortalama: <?php echo number_format($yearlyChampions['training']['monthly_avg'], 1); ?> eğitim
                </div>
                <div class="insight-detail" style="font-size: 11px; opacity: 0.8;">
                    * Google Yorum ve Lisans Yenileme hariç
                </div>
            </div>
            <?php endif; ?>

            <!-- En Çok Lisans Yenileme -->
            <?php if (!empty($yearlyChampions['license_renewal'])): ?>
            <div class="insight-card teal">
                <div class="insight-header">
                    <span class="insight-icon">🔑</span>
                    <span>EN ÇOK LİSANS YENİLEME</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($yearlyChampions['license_renewal']['full_name']); ?></div>
                <div class="insight-label"><?php echo number_format($yearlyChampions['license_renewal']['total_renewals']); ?> lisans yeniledi</div>
                <div class="insight-detail">
                    📊 Aylık Ortalama: <?php echo number_format($yearlyChampions['license_renewal']['monthly_avg'], 1); ?> yenileme
                </div>
            </div>
            <?php endif; ?>

            <!-- En Çok Google Yorum -->
            <?php if (!empty($yearlyChampions['google_review'])): ?>
            <div class="insight-card indigo">
                <div class="insight-header">
                    <span class="insight-icon">⭐</span>
                    <span>EN ÇOK GOOGLE YORUM</span>
                </div>
                <div class="insight-value"><?php echo htmlspecialchars($yearlyChampions['google_review']['full_name']); ?></div>
                <div class="insight-label"><?php echo number_format($yearlyChampions['google_review']['total_reviews']); ?> yorum aldı</div>
                <div class="insight-detail">
                    📊 Aylık Ortalama: <?php echo number_format($yearlyChampions['google_review']['monthly_avg'], 1); ?> yorum
                </div>
            </div>
            <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Trend Özetleri ve Öneriler -->
    <div class="recommendations-wrapper">
        <div class="recommendations-section">
            <h2 style="margin-bottom: 20px; color: #2c3e50;">📋 Trend Özetleri ve Öneriler</h2>
            <div class="recommendations-grid">
            <?php foreach ($recommendations as $rec): ?>
            <div class="recommendation-card <?php echo $rec['type']; ?>">
                <div class="recommendation-header">
                    <span class="recommendation-icon"><?php echo $rec['icon']; ?></span>
                    <div class="recommendation-title"><?php echo htmlspecialchars($rec['title']); ?></div>
                </div>
                <div class="recommendation-description">
                    <?php echo htmlspecialchars($rec['description']); ?>
                </div>
                <div class="recommendation-action">
                    💡 <?php echo htmlspecialchars($rec['action']); ?>
                </div>
            </div>
            <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@2.2.0/dist/chartjs-plugin-datalabels.min.js"></script>
<script>
    // Çalışan Performans Karşılaştırması
    const performanceCtx = document.getElementById('performanceChart').getContext('2d');
    const performanceChart = new Chart(performanceCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($performanceLabels); ?>,
            datasets: [{
                label: 'Gelen Çağrı',
                data: <?php echo json_encode($performanceIncoming); ?>,
                backgroundColor: 'rgba(102, 126, 234, 0.8)',
                borderRadius: 6,
                yAxisID: 'y'
            }, {
                label: 'Giden Çağrı',
                data: <?php echo json_encode($performanceOutgoing); ?>,
                backgroundColor: 'rgba(240, 147, 251, 0.8)',
                borderRadius: 6,
                yAxisID: 'y'
            }, {
                label: 'Eğitim',
                data: <?php echo json_encode($performanceTraining); ?>,
                backgroundColor: 'rgba(67, 233, 123, 0.8)',
                borderRadius: 6,
                yAxisID: 'y'
            }, {
                label: 'Gelen Süre (dk)',
                data: <?php echo json_encode($performanceIncomingDuration); ?>,
                backgroundColor: 'rgba(79, 172, 254, 0.8)',
                borderRadius: 6,
                yAxisID: 'y'
            }, {
                label: 'Giden Süre (dk)',
                data: <?php echo json_encode($performanceOutgoingDuration); ?>,
                backgroundColor: 'rgba(250, 112, 154, 0.8)',
                borderRadius: 6,
                yAxisID: 'y'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false  // Legend'ı gizle, toggle butonlarını kullanıyoruz
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            let value = context.parsed.y;

                            // Süre dataset'leri için dakika göster
                            if (label.includes('Süre')) {
                                return label + ': ' + value.toLocaleString() + ' dakika';
                            }
                            return label + ': ' + value.toLocaleString();
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value.toLocaleString();
                        }
                    }
                }
            }
        }
    });

    // Toggle fonksiyonu
    function toggleDataset(index) {
        const meta = performanceChart.getDatasetMeta(index);
        meta.hidden = !meta.hidden;
        performanceChart.update();

        // Buton görünümünü güncelle
        const btn = document.querySelector(`[data-dataset="${index}"]`);
        if (meta.hidden) {
            btn.classList.remove('active');
        } else {
            btn.classList.add('active');
        }
    }

    // Aylık Trend
    const trendCtx = document.getElementById('trendChart').getContext('2d');
    const trendChart = new Chart(trendCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($trendLabels); ?>,
            datasets: [{
                label: 'Toplam Çağrı',
                data: <?php echo json_encode($trendValues); ?>,
                borderColor: 'rgb(102, 126, 234)',
                backgroundColor: 'rgba(102, 126, 234, 0.1)',
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value.toLocaleString();
                        }
                    }
                }
            }
        }
    });

    // Paket Dağılımı
    const packageCtx = document.getElementById('packageChart').getContext('2d');
    const packageChart = new Chart(packageCtx, {
        type: 'doughnut',
        data: {
            labels: <?php echo json_encode($packageLabels); ?>,
            datasets: [{
                data: <?php echo json_encode($packageValues); ?>,
                backgroundColor: [
                    'rgba(102, 126, 234, 0.8)',
                    'rgba(240, 147, 251, 0.8)',
                    'rgba(79, 172, 254, 0.8)',
                    'rgba(67, 233, 123, 0.8)',
                    'rgba(250, 112, 154, 0.8)',
                    'rgba(254, 202, 87, 0.8)'
                ]
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right'
                }
            }
        }
    });

    // Günlük Aktivite
    const activityCtx = document.getElementById('activityChart').getContext('2d');
    const activityChart = new Chart(activityCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($activityLabels); ?>,
            datasets: [{
                label: 'Gelen Çağrı',
                data: <?php echo json_encode($activityIncoming); ?>,
                backgroundColor: 'rgba(79, 172, 254, 0.8)',
                borderRadius: 4
            }, {
                label: 'Giden Çağrı',
                data: <?php echo json_encode($activityOutgoing); ?>,
                backgroundColor: 'rgba(250, 112, 154, 0.8)',
                borderRadius: 4,
                hidden: true  // Varsayılan olarak gizli
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            return context.dataset.label + ': ' + context.parsed.y.toLocaleString();
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value.toLocaleString();
                        }
                    }
                }
            }
        }
    });

    // Aktivite toggle fonksiyonu
    function toggleActivityDataset(index) {
        const meta = activityChart.getDatasetMeta(index);
        meta.hidden = !meta.hidden;
        activityChart.update();

        // Buton görünümünü güncelle
        const btn = document.querySelector(`[data-activity-dataset="${index}"]`);
        if (meta.hidden) {
            btn.classList.remove('active');
        } else {
            btn.classList.add('active');
        }
    }

    // Yıllık Performans Grafiği
    const yearlyPerformanceCtx = document.getElementById('yearlyPerformanceChart').getContext('2d');
    const yearlyPerformanceChart = new Chart(yearlyPerformanceCtx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($monthlyLabels); ?>,
            datasets: [
                <?php foreach ($personnelMonthlyData as $pData): ?>
                {
                    label: <?php echo json_encode($pData['name']); ?>,
                    data: <?php echo json_encode($pData['data']); ?>,
                    backgroundColor: '<?php echo $pData['color']; ?>',
                    borderRadius: 6
                },
                <?php endforeach; ?>
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false  // Legend'ı gizle, toggle butonlarını kullanıyoruz
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            let value = context.parsed.y;
                            return label + ': ' + value.toFixed(2) + ' puan';
                        }
                    }
                }
            },
            scales: {
                x: {
                    stacked: false
                },
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(value) {
                            return value.toFixed(0);
                        }
                    }
                }
            }
        }
    });

    // Personel dataset toggle fonksiyonu
    function togglePersonnelDataset(index) {
        const meta = yearlyPerformanceChart.getDatasetMeta(index);
        meta.hidden = !meta.hidden;
        yearlyPerformanceChart.update();

        // Buton görünümünü güncelle
        const btn = document.querySelector(`[data-personnel-dataset="${index}"]`);
        if (meta.hidden) {
            btn.classList.remove('active');
        } else {
            btn.classList.add('active');
        }
    }

    // Tüm personeli seç/kaldır
    let allPersonnelVisible = true;
    function toggleAllPersonnel() {
        allPersonnelVisible = !allPersonnelVisible;

        // Tüm dataset'leri göster/gizle
        for (let i = 0; i < yearlyPerformanceChart.data.datasets.length; i++) {
            const meta = yearlyPerformanceChart.getDatasetMeta(i);
            meta.hidden = !allPersonnelVisible;

            // Buton görünümünü güncelle
            const btn = document.querySelector(`[data-personnel-dataset="${i}"]`);
            if (meta.hidden) {
                btn.classList.remove('active');
            } else {
                btn.classList.add('active');
            }
        }

        yearlyPerformanceChart.update();
    }

    // Yatay Yığılmış Grafik (Rapor.jpg benzeri)
    const stackedPerformanceCtx = document.getElementById('stackedPerformanceChart').getContext('2d');

    // Aylar için renkler
    const monthColors = [
        'rgba(54, 162, 235, 0.8)',   // Ocak - Mavi
        'rgba(255, 159, 64, 0.8)',   // Şubat - Turuncu
        'rgba(75, 192, 192, 0.8)',   // Mart - Yeşil
        'rgba(79, 172, 254, 0.8)',   // Nisan - Açık Mavi
        'rgba(255, 99, 132, 0.8)',   // Mayıs - Pembe
        'rgba(153, 102, 255, 0.8)',  // Haziran - Mor
        'rgba(76, 175, 80, 0.8)',    // Temmuz - Açık Yeşil
        'rgba(255, 205, 86, 0.8)',   // Ağustos - Sarı
        'rgba(201, 203, 207, 0.8)',  // Eylül - Gri
        'rgba(255, 99, 71, 0.8)',    // Ekim - Kırmızı
        'rgba(100, 181, 246, 0.8)',  // Kasım - Mavi
        'rgba(255, 152, 0, 0.8)'     // Aralık - Koyu Turuncu
    ];

    // Personel isimleri (Y ekseni)
    const personnelNames = <?php echo json_encode(array_column($personnelMonthlyData, 'name')); ?>;

    // Tüm personel verilerini al
    const allPersonnelData = <?php echo json_encode($personnelMonthlyData); ?>;

    // Her ay için dataset oluştur (gerçek puan değerleri ile)
    const stackedDatasets = [];
    for (let monthIndex = 0; monthIndex < 12; monthIndex++) {
        const monthData = [];

        // Her personel için o ayın gerçek puanını al
        allPersonnelData.forEach(person => {
            const monthScore = person.data[monthIndex];
            monthData.push(monthScore);
        });

        stackedDatasets.push({
            label: <?php echo json_encode($monthlyLabels); ?>[monthIndex],
            data: monthData,
            backgroundColor: monthColors[monthIndex],
            borderWidth: 1,
            borderColor: 'rgba(255, 255, 255, 0.5)'
        });
    }

    // En yüksek toplam puanı bul (X ekseni için max değer)
    const maxYearlyTotal = Math.max(...allPersonnelData.map(p => p.yearlyTotal));

    const stackedPerformanceChart = new Chart(stackedPerformanceCtx, {
        type: 'bar',
        plugins: [ChartDataLabels], // Datalabels plugin'ini sadece bu grafik için aktif et
        data: {
            labels: personnelNames,
            datasets: stackedDatasets
        },
        options: {
            indexAxis: 'y', // Yatay bar chart
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: true,
                    position: 'bottom',
                    labels: {
                        boxWidth: 15,
                        padding: 10,
                        font: {
                            size: 11
                        }
                    }
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            const label = context.dataset.label || '';
                            const value = context.parsed.x;

                            // Yüzdeyi hesapla
                            const personIndex = context.dataIndex;
                            const yearlyTotal = allPersonnelData[personIndex].yearlyTotal;
                            const percentage = yearlyTotal > 0 ? (value / yearlyTotal) * 100 : 0;

                            return label + ': ' + value.toFixed(2) + ' puan (' + percentage.toFixed(2) + '%)';
                        }
                    }
                },
                datalabels: {
                    display: true,
                    color: '#fff',
                    font: {
                        weight: 'bold',
                        size: 10
                    },
                    formatter: function(value, context) {
                        // Her bar üzerinde gerçek puan değerini göster
                        // Çok küçük değerleri gösterme (5 puandan küçük)
                        if (value < 5) {
                            return '';
                        }

                        return value.toFixed(2);
                    },
                    anchor: 'center',
                    align: 'center',
                    textStrokeColor: 'rgba(0, 0, 0, 0.3)',
                    textStrokeWidth: 2
                }
            },
            scales: {
                x: {
                    stacked: true,
                    beginAtZero: true,
                    max: maxYearlyTotal * 1.05, // %5 boşluk bırak
                    ticks: {
                        callback: function(value) {
                            return value.toFixed(0);
                        }
                    },
                    grid: {
                        display: true,
                        color: 'rgba(0, 0, 0, 0.05)'
                    }
                },
                y: {
                    stacked: true,
                    grid: {
                        display: false
                    },
                    ticks: {
                        font: {
                            size: 12,
                            weight: 'bold'
                        }
                    }
                }
            }
        }
    });
</script>

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