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

Auth::requireLogin();

$pageTitle = 'Prim Hesaplama Sistemi';
include 'includes/header.php';

$db = new Database();

// Süre formatlama fonksiyonu (24 saat ve üzeri için)
function formatDuration($seconds) {
    $hours = floor($seconds / 3600);
    $minutes = floor(($seconds % 3600) / 60);
    $secs = $seconds % 60;
    return sprintf('%02d:%02d:%02d', $hours, $minutes, $secs);
}

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

// Tarih filtresi
if ($quickFilter) {
    // Ay seçimi
    if (strpos($quickFilter, 'month_') === 0) {
        $monthOffset = (int)str_replace('month_', '', $quickFilter);
        $startDate = date('Y-m-01', strtotime("$monthOffset months"));
        $endDate = date('Y-m-t', strtotime("$monthOffset months"));
    }
} else {
    // Manuel tarih seçimi veya varsayılan (Bu ay)
    if (isset($_GET['start_date']) && isset($_GET['end_date'])) {
        $startDate = $_GET['start_date'];
        $endDate = $_GET['end_date'];
    } else {
        // Varsayılan: Bu Ay
        $startDate = date('Y-m-01');
        $endDate = date('Y-m-d');
    }
}

// Prim katsayıları (Admin tarafından düzenlenebilir - şimdilik sabit)
$bonusSettings = [
    'performance_multiplier' => 100, // Performans puanı başına prim (TL)
    'training_per_unit' => 50, // Tamamlanan eğitim başına prim (TL)
    'package_multiplier' => 1.5, // Paket prim çarpanı
];

/**
 * Belirli bir tarih için kriterin değerini getirir
 * Önce criteria_history tablosuna bakar, yoksa criteria tablosundaki varsayılan değeri kullanır
 */
function getCriteriaValueForDate($db, $criteriaCode, $date) {
    // Önce history tablosunda bu tarih için kayıt var mı bak
    $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'];
    }

    // History'de yoksa criteria tablosundaki varsayılan değeri kullan
    $defaultValue = $db->fetchOne("
        SELECT point_value
        FROM criteria
        WHERE code = ?
    ", [$criteriaCode]);

    return ($defaultValue && isset($defaultValue['point_value'])) ? $defaultValue['point_value'] : 0;
}

// Seçilen ay için snapshot oluştur veya çek
$selectedYear = date('Y', strtotime($startDate));
$selectedMonth = date('n', strtotime($startDate));

// Snapshot var mı kontrol et
$snapshotExists = $db->fetchOne("
    SELECT COUNT(*) as count
    FROM criteria_snapshots
    WHERE year = ? AND month = ?
", [$selectedYear, $selectedMonth]);

// Snapshot yoksa oluştur
if ($snapshotExists['count'] == 0) {
    $currentCriteria = $db->fetchAll("
        SELECT code, name, category, point_value
        FROM criteria
        WHERE is_active = 1
    ");

    // Seçilen ay için ortadaki bir tarihi kullan (ayın 15'i)
    $referenceDate = sprintf('%04d-%02d-15', $selectedYear, $selectedMonth);

    foreach ($currentCriteria as $crit) {
        // Seçilen tarih için bu kriterin değerini al (history'den veya varsayılan)
        $pointValue = getCriteriaValueForDate($db, $crit['code'], $referenceDate);

        $db->query("
            INSERT INTO criteria_snapshots (year, month, criteria_code, criteria_name, category, point_value)
            VALUES (?, ?, ?, ?, ?, ?)
        ", [$selectedYear, $selectedMonth, $crit['code'], $crit['name'], $crit['category'], $pointValue]);
    }
}

// Snapshot'tan kriterleri çek
$criteria = $db->fetchAll("
    SELECT criteria_code as code, criteria_name as name, category, point_value
    FROM criteria_snapshots
    WHERE year = ? AND month = ?
    ORDER BY category ASC, criteria_name ASC
", [$selectedYear, $selectedMonth]);

// Eğer snapshot boşsa (eski ay) mevcut kriterleri kullan
if (empty($criteria)) {
    $criteria = $db->fetchAll("
        SELECT code, name, category, point_value
        FROM criteria
        WHERE is_active = 1
        ORDER BY category, display_order ASC, name ASC
    ");
}

// ÖNEMLİ: Tarihçe kontrolü - snapshot'ları override et
// Seçilen ay için referans tarih (ayın ortası)
$referenceDate = sprintf('%04d-%02d-15', $selectedYear, $selectedMonth);

foreach ($criteria as &$criterion) {
    // Bu kriter için tarihçede özel değer var mı kontrol et
    $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
    ", [$criterion['code'], $referenceDate, $referenceDate]);

    // Eğer tarihçede değer varsa, snapshot'taki değeri override et
    if ($historyValue && isset($historyValue['point_value'])) {
        $criterion['point_value'] = $historyValue['point_value'];
    }
}
unset($criterion); // Referansı temizle

// Kategorilere göre kriterleri grupla
$criteriaByCategory = [];
foreach ($criteria as $criterion) {
    $cat = $criterion['category'] ?? 'Genel';
    $criteriaByCategory[$cat][] = $criterion;
}

// Paket Kriterleri için özel sıralama
if (isset($criteriaByCategory['Paket Kriterleri'])) {
    $packageOrder = [
        'Profesyonel Paket' => 1,
        'Gelişmiş Paket' => 2,
        'Uzman Paket' => 3,
        'Ideasoft ERP' => 4,
        'Ideasoft Mini 2' => 5,
        'Ideasoft Mini 3' => 6,
        'Ideasoft Maksi' => 7,
        'Sopyo Logo' => 8,
        'Sopyo Nebim v3' => 9,
        'Sopyo Nebim V3' => 9, // Alternatif isim
        'Lisans Yenileme' => 10,
        'Google Yorum' => 11
    ];

    usort($criteriaByCategory['Paket Kriterleri'], function($a, $b) use ($packageOrder) {
        $orderA = $packageOrder[$a['name']] ?? 999;
        $orderB = $packageOrder[$b['name']] ?? 999;
        return $orderA <=> $orderB;
    });
}

// Paket türü renkleri (koyu tonlar)
function getPackageTypeColor($packageType) {
    if (empty($packageType)) return 'rgba(229, 231, 235, 0.4)';

    $pkg = strtolower($packageType);

    // SOPYO PAKETLERİ - Lacivert/Mavi Koyu Tonlar
    if (strpos($pkg, 'profesyonel') !== false && strpos($pkg, 'ideasoft') === false) {
        return '#5B7FC4'; // Koyu mavi
    } elseif (strpos($pkg, 'gelişmiş') !== false) {
        return '#4A6BA8'; // Daha koyu mavi
    } elseif (strpos($pkg, 'uzman') !== false) {
        return '#3A5891'; // Lacivert koyu
    }

    // IDEASOFT PAKETLERİ - Turkuaz/Yeşil-Mavi Koyu Tonları
    elseif (strpos($pkg, 'ideasoft erp') !== false) {
        return '#008B7E'; // Koyu turkuaz
    } elseif (strpos($pkg, 'ideasoft mini 2') !== false) {
        return '#15A393'; // Koyu açık turkuaz
    } elseif (strpos($pkg, 'ideasoft mini 3') !== false) {
        return '#2BB8A7'; // Orta turkuaz
    } elseif (strpos($pkg, 'ideasoft maksi') !== false || strpos($pkg, 'maksi') !== false) {
        return '#007A70'; // Çok koyu turkuaz
    } elseif (strpos($pkg, 'ideasoft') !== false) {
        return '#008B7E'; // Genel Ideasoft - Koyu turkuaz
    }

    // SOPYO ERP/MUHASEBE - Koyu Mor/Eflatun
    elseif (strpos($pkg, 'sopyo logo') !== false) {
        return '#836AA0'; // Koyu mor
    } elseif (strpos($pkg, 'nebim') !== false) {
        return '#9377B5'; // Koyu eflatun
    } elseif (strpos($pkg, 'sopyo') !== false) {
        return '#8A6FA9'; // Genel Sopyo ERP - Koyu
    }

    // LİSANS YENİLEME - Koyu Turuncu (Bonus)
    elseif (strpos($pkg, 'lisans') !== false || strpos($pkg, 'yenileme') !== false) {
        return '#D67A3D'; // Koyu turuncu-altın
    }

    return 'rgba(156, 131, 203, 0.8)'; // Lavanta koyu - Diğer
}

// Personel listesini al (Aktif kullanıcılar)
$personnelList = $db->fetchAll("
    SELECT id, username, full_name, extension
    FROM users
    WHERE is_active = 1
    ORDER BY full_name ASC
");

// Her personel için detaylı veri hazırla
$bonusData = [];

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

    // 1. GELEN ARAMALAR
    $incomingPerformance = $db->fetchOne("
        SELECT
            COALESCE(SUM(ic.answered_count), 0) as total_answered,
            COALESCE(SUM(TIME_TO_SEC(ic.total_duration)), 0) as total_duration_seconds
        FROM incoming_calls ic
        WHERE ic.user_id = ?
        AND ic.call_date BETWEEN ? AND ?
    ", [$userId, $startDate, $endDate]);

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

    // 2. GİDEN ARAMALAR
    $outgoingPerformance = $db->fetchOne("
        SELECT
            COALESCE(SUM(oc.answered_count), 0) as total_answered,
            COALESCE(SUM(TIME_TO_SEC(oc.total_duration)), 0) as total_duration_seconds
        FROM outgoing_calls oc
        WHERE oc.user_id = ?
        AND oc.call_date BETWEEN ? AND ?
    ", [$userId, $startDate, $endDate]);

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

    // 3. DESTEK MESAJLARI
    $supportMsgData = $db->fetchOne("
        SELECT COALESCE(SUM(message_count), 0) as total_messages
        FROM support_messages
        WHERE user_id = ?
        AND message_date BETWEEN ? AND ?
    ", [$userId, $startDate, $endDate]);

    $supportMessages = (int)($supportMsgData['total_messages'] ?? 0);

    // 4. PAKET BAZLI EĞİTİM SAYILARI
    $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, $startDate, $endDate]);

    // Her paket için sayıyı map'e al
    $packageCounts = [];
    $totalTrainings = 0;
    foreach ($trainingStats as $training) {
        $packageCounts[$training['package_type']] = (int)$training['count'];
        $totalTrainings += (int)$training['count'];
    }

    // 5. PRİM HESAPLAMA
    // Basit model: Arama sayısı + Eğitim + Paket primleri
    $totalCalls = $incomingCalls + $outgoingCalls;
    $callBonus = $totalCalls * 10; // Her arama için 10 TL (örnek katsayı)
    $trainingBonus = $totalTrainings * $bonusSettings['training_per_unit'];

    // Paket bazlı prim hesaplama
    $packageBonus = 0;
    foreach ($packageCounts as $pkgType => $count) {
        foreach ($criteriaByCategory['Paket Kriterleri'] ?? [] as $pkg) {
            if (stripos($pkgType, $pkg['name']) !== false || stripos($pkg['name'], $pkgType) !== false) {
                $packageBonus += $count * (float)$pkg['point_value'] * $bonusSettings['package_multiplier'];
                break;
            }
        }
    }

    $totalBonus = $callBonus + $trainingBonus + $packageBonus;

    // Tüm personeli ekle (veri olsun olmasın)
    $bonusData[] = [
        'user_id' => $userId,
        'representative' => $fullName,
        'incoming_calls' => $incomingCalls,
        'incoming_duration' => $incomingDuration,
        'outgoing_calls' => $outgoingCalls,
        'outgoing_duration' => $outgoingDuration,
        'support_messages' => $supportMessages,
        'total_calls' => $totalCalls,
        'package_counts' => $packageCounts,
        'total_trainings' => $totalTrainings,
        'call_bonus' => $callBonus,
        'training_bonus' => $trainingBonus,
        'package_bonus' => $packageBonus,
        'total_bonus' => $totalBonus
    ];
}

// İsme göre sırala (alfabetik) - Mustafa SÜLERYA'yı en alta koy
usort($bonusData, function($a, $b) {
    // Mustafa SÜLERYA'yı her zaman en alta koy
    if (stripos($a['representative'], 'Mustafa') !== false && stripos($a['representative'], 'SÜLERYA') !== false) {
        return 1;
    }
    if (stripos($b['representative'], 'Mustafa') !== false && stripos($b['representative'], 'SÜLERYA') !== false) {
        return -1;
    }
    // Diğerleri alfabetik
    return strcmp($a['representative'], $b['representative']);
});

// Performans Puanlama Hesaplaması (Mustafa SÜLERYA hariç)
$scoringData = [];

// Kriterlere göre point_value mapping oluştur
$criteriaPoints = [];
foreach ($criteria as $crit) {
    $criteriaPoints[$crit['code']] = $crit['point_value'];
}

// Snapshot'ta olmayan aktif kriterleri doğrudan criteria tablosundan tamamla
// (Snapshot oluşturulduktan sonra eklenen yeni kriterler için)
$activeCriteria = $db->fetchAll("SELECT code, point_value FROM criteria WHERE is_active = 1");
foreach ($activeCriteria as $ac) {
    if (!isset($criteriaPoints[$ac['code']])) {
        $criteriaPoints[$ac['code']] = getCriteriaValueForDate($db, $ac['code'], $referenceDate);
        // Eksik kriteri snapshot'a da ekle (bir sonraki yüklemede sorun yaşanmasın)
        $db->query("
            INSERT IGNORE INTO criteria_snapshots (year, month, criteria_code, criteria_name, category, point_value)
            SELECT ?, ?, c.code, c.name, c.category, ?
            FROM criteria c WHERE c.code = ?
        ", [$selectedYear, $selectedMonth, $criteriaPoints[$ac['code']], $ac['code']]);
    }
}

// Mustafa SÜLERYA hariç toplamları hesapla
$totals = [
    'incoming_calls' => 0,
    'incoming_duration' => 0,
    'outgoing_calls' => 0,
    'outgoing_duration' => 0,
    'support_messages' => 0,
    'total_trainings' => 0
];

// Paket kategorileri tanımla
$proportionalPackages = [
    '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 = [
    'Sopyo Logo' => 1.0,
    'Sopyo Nebim' => 1.0,
    'Sopyo Nebim v3' => 1.0,
    'Lisans Yenileme' => 0.25,
    'Google Yorum' => 1.0
];

// Helper function: Check if package name matches
function packageMatches($packageName, $searchName) {
    $pkg = strtolower($packageName);
    $search = strtolower($searchName);
    return (stripos($pkg, $search) !== false || stripos($search, $pkg) !== false);
}

// Helper function: Yukarı yuvarlama - 50₺'lik dilimlere HER ZAMAN YUKARI yuvarla
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);
}

// Oransal paket toplamını hesapla (Mustafa hariç, ağırlıklı)
$totalProportionalWeighted = 0;

foreach ($bonusData as $data) {
    // Mustafa SÜLERYA'yı atla
    if (stripos($data['representative'], 'Mustafa') !== false && stripos($data['representative'], 'SÜLERYA') !== false) {
        continue;
    }

    $totals['incoming_calls'] += $data['incoming_calls'];
    $totals['incoming_duration'] += $data['incoming_duration'];
    $totals['outgoing_calls'] += $data['outgoing_calls'];
    $totals['outgoing_duration'] += $data['outgoing_duration'];
    $totals['support_messages'] += $data['support_messages'];
    $totals['total_trainings'] += $data['total_trainings'];

    // Oransal paketlerin ağırlıklı toplamı
    foreach ($data['package_counts'] as $pkgName => $count) {
        foreach ($proportionalPackages as $propPkgName => $weight) {
            if (packageMatches($pkgName, $propPkgName)) {
                $totalProportionalWeighted += $count * $weight;
                break;
            }
        }
    }
}

// Her personel için puanları hesapla
foreach ($bonusData as &$data) {
    $isMustafa = (stripos($data['representative'], 'Mustafa') !== false && stripos($data['representative'], 'SÜLERYA') !== false);

    // Mustafa SÜLERYA için puanlar 0
    if ($isMustafa) {
        $data['score_incoming_calls'] = 0;
        $data['score_incoming_duration'] = 0;
        $data['score_outgoing_calls'] = 0;
        $data['score_outgoing_duration'] = 0;
        $data['score_support_messages'] = 0;
        $data['score_proportional_packages'] = 0;
        $data['score_bonus_packages'] = 0;
        $data['proportional_details'] = [];
        $data['bonus_details'] = [];
        $data['proportional_weighted_total'] = 0;
        $data['total_score'] = 0;
        continue;
    }

    // Gelen Arama Sayısı puanı
    $data['score_incoming_calls'] = $totals['incoming_calls'] > 0
        ? ($data['incoming_calls'] / $totals['incoming_calls']) * ($criteriaPoints['gelen_arama_sayisi'] ?? 0)
        : 0;

    // Gelen Konuşma Süresi puanı
    $data['score_incoming_duration'] = $totals['incoming_duration'] > 0
        ? ($data['incoming_duration'] / $totals['incoming_duration']) * ($criteriaPoints['gelen_arama_suresi'] ?? 0)
        : 0;

    // Giden Arama Sayısı puanı
    $data['score_outgoing_calls'] = $totals['outgoing_calls'] > 0
        ? ($data['outgoing_calls'] / $totals['outgoing_calls']) * ($criteriaPoints['giden_arama_sayisi'] ?? 0)
        : 0;

    // Giden Konuşma Süresi puanı
    $data['score_outgoing_duration'] = $totals['outgoing_duration'] > 0
        ? ($data['outgoing_duration'] / $totals['outgoing_duration']) * ($criteriaPoints['giden_arama_suresi'] ?? 0)
        : 0;

    // Destek Mesajı Sayısı puanı
    $data['score_support_messages'] = $totals['support_messages'] > 0
        ? ($data['support_messages'] / $totals['support_messages']) * ($criteriaPoints['destek_mesaj_sayisi'] ?? 0)
        : 0;

    // PAKET PUANLAMA SİSTEMİ

    // 1. Oransal Paketler (Formül ile hesaplanan)
    $personelProportionalWeighted = 0;
    $data['proportional_details'] = [];

    foreach ($data['package_counts'] as $pkgName => $count) {
        foreach ($proportionalPackages as $propPkgName => $weight) {
            if (packageMatches($pkgName, $propPkgName)) {
                $weighted = $count * $weight;
                $personelProportionalWeighted += $weighted;
                $data['proportional_details'][] = [
                    'name' => $pkgName,
                    'count' => $count,
                    'weight' => $weight,
                    'weighted' => $weighted
                ];
                break;
            }
        }
    }

    $data['proportional_weighted_total'] = $personelProportionalWeighted;

    // Oransal paket puanı = (personel_ağırlıklı / toplam_ağırlıklı) × eğitim_oranı_kriteri
    $data['score_proportional_packages'] = $totalProportionalWeighted > 0
        ? ($personelProportionalWeighted / $totalProportionalWeighted) * ($criteriaPoints['egitim_orani'] ?? 0)
        : 0;

    // 2. Bonus Paketler (Direkt puan)
    $data['score_bonus_packages'] = 0;
    $data['bonus_details'] = [];

    foreach ($data['package_counts'] as $pkgName => $count) {
        foreach ($bonusPackages as $bonusPkgName => $bonusPoint) {
            if (packageMatches($pkgName, $bonusPkgName)) {
                $bonusScore = $count * $bonusPoint;
                $data['score_bonus_packages'] += $bonusScore;
                $data['bonus_details'][] = [
                    'name' => $pkgName,
                    'count' => $count,
                    'point' => $bonusPoint,
                    'total' => $bonusScore
                ];
                break;
            }
        }
    }

    // Toplam puan
    $data['total_score'] =
        $data['score_incoming_calls'] +
        $data['score_incoming_duration'] +
        $data['score_outgoing_calls'] +
        $data['score_outgoing_duration'] +
        $data['score_support_messages'] +
        $data['score_proportional_packages'] +
        $data['score_bonus_packages'];
}
unset($data);

// Prim Tutarı Hesaplama
// criteria_history tablosunu kontrol et, yoksa criteria tablosundaki varsayılan değeri kullan
$primTutari = getCriteriaValueForDate($db, 'prim_tutari', $referenceDate);

// Mustafa hariç personelleri toplam puana göre sırala
$eligibleForBonus = array_filter($bonusData, function($person) {
    return !(stripos($person['representative'], 'Mustafa') !== false && stripos($person['representative'], 'SÜLERYA') !== false);
});

// Toplam puana göre sırala (büyükten küçüğe)
usort($eligibleForBonus, function($a, $b) {
    return $b['total_score'] <=> $a['total_score'];
});

// Prim hesaplama hazır

// Prim hesaplama - 4 personel veya daha fazla olmalı
if (count($eligibleForBonus) >= 4 && $primTutari > 0) {
    // En yüksek 3 kişiyi al (en düşük 1 kişi hariç - prim alacaklar)
    $topThree = array_slice($eligibleForBonus, 0, 3);
    $lowestPerson = $eligibleForBonus[count($eligibleForBonus) - 1]; // 4. kişi - prim almayacak

    // En yüksek puanlı kişi
    $highestPerson = $topThree[0];

    // 4 kişinin toplam puanını hesapla
    $totalScoreOfFour = 0;
    foreach ($eligibleForBonus as $person) {
        $totalScoreOfFour += $person['total_score'];
    }

    // Maksimum teorik puan (tüm kriterlerin toplamı - TEK KİŞİ İÇİN)
    $maxTheoreticalScore = ($criteriaPoints['gelen_arama_sayisi'] ?? 0) +
                           ($criteriaPoints['gelen_arama_suresi'] ?? 0) +
                           ($criteriaPoints['giden_arama_sayisi'] ?? 0) +
                           ($criteriaPoints['giden_arama_suresi'] ?? 0) +
                           ($criteriaPoints['egitim_orani'] ?? 0);

    // 4 kişinin TOPLAM puanını maksimuma göre değerlendir
    // Örnek: 86 puan varsa, maksimum 100'e göre %86 gerçekleşme var
    $achievementRate = $maxTheoreticalScore > 0 ? ($totalScoreOfFour / $maxTheoreticalScore) * 100 : 0;

    // Eksik kalan yüzde (100 - 86 = %14)
    $missingPercentage = 100 - $achievementRate;

    // 4. kişinin puanını da maksimum puana göre yüzdeye çevir
    $lowestPersonPercentage = $maxTheoreticalScore > 0 ? ($lowestPerson['total_score'] / $maxTheoreticalScore) * 100 : 0;

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

    // Her personel için prim miktarını hesapla ve $bonusData'ya ekle
    foreach ($bonusData as &$person) {
        $isMustafa = (stripos($person['representative'], 'Mustafa') !== false && stripos($person['representative'], 'SÜLERYA') !== false);

        if ($isMustafa) {
            $person['bonus_amount'] = 0;
            $person['bonus_percentage'] = 0;
            $person['gets_bonus'] = false;
            $person['extra_bonus_info'] = '';
        } else {
            // Bu kişi en düşük puanlı mı?
            $isLowest = ($person['user_id'] === $lowestPerson['user_id']);

            // Bu kişi en yüksek puanlı mı?
            $isHighest = ($person['user_id'] === $highestPerson['user_id']);

            if ($isLowest) {
                // En düşük puanlı kişi prim almaz
                $person['bonus_amount'] = 0;
                $person['bonus_percentage'] = 0;
                $person['gets_bonus'] = false;
                $person['extra_bonus_info'] = '';
            } else {
                // Top 3'te yer alıyor - prim alacak
                $person['gets_bonus'] = true;

                // Her personelin kendi puanını maksimum puana (100) göre yüzdeye çevir
                $ownPercentage = $maxTheoreticalScore > 0 ? ($person['total_score'] / $maxTheoreticalScore) * 100 : 0;

                if ($isHighest) {
                    // En yüksek puanlı: kendi yüzdesi + ekstra bonus
                    $person['bonus_percentage'] = $ownPercentage + $extraBonusPercentage;

                    // Daha anlaşılır açıklama oluştur
                    if ($missingPercentage > 0) {
                        // Toplam puan 100'ün altında - eksik var
                        $person['extra_bonus_info'] = sprintf(
                            "Kendi Payı: %.2f%% + 4.Kişi Payı: %.2f%% + Hedef Tamamlama: %.2f%% = %.2f%%",
                            $ownPercentage,
                            $lowestPersonPercentage,
                            $missingPercentage,
                            $person['bonus_percentage']
                        );
                    } else {
                        // Toplam puan 100'ü aştı - fazlalık var
                        $person['extra_bonus_info'] = sprintf(
                            "Kendi Payı: %.2f%% + 4.Kişi Payı: %.2f%% - Fazlalık Düşümü: %.2f%% = %.2f%%",
                            $ownPercentage,
                            $lowestPersonPercentage,
                            abs($missingPercentage),
                            $person['bonus_percentage']
                        );
                    }
                } else {
                    // Diğerleri sadece kendi yüzdelerini alır
                    $person['bonus_percentage'] = $ownPercentage;
                    $person['extra_bonus_info'] = '';
                }

                // Prim tutarını hesapla
                $rawAmount = ($person['bonus_percentage'] / 100) * $primTutari;

                // Akıllı yuvarlama: 50₺'lik dilimlere yuvarla
                $person['bonus_amount'] = roundToNearestFifty($rawAmount);
            }
        }
    }
    unset($person); // Referansı temizle
} else {
    // Yeterli personel yoksa veya prim tutarı 0 ise
    foreach ($bonusData as &$person) {
        $person['bonus_amount'] = 0;
        $person['bonus_percentage'] = 0;
        $person['gets_bonus'] = false;
        $person['extra_bonus_info'] = '';
    }
    unset($person); // Referansı temizle
}

// Türkçe ay isimleri
$turkishMonths = [
    '01' => 'Ocak', '02' => 'Şubat', '03' => 'Mart', '04' => 'Nisan',
    '05' => 'Mayıs', '06' => 'Haziran', '07' => 'Temmuz', '08' => 'Ağustos',
    '09' => 'Eylül', '10' => 'Ekim', '11' => 'Kasım', '12' => 'Aralık'
];

// Ay listesi (son 12 ay)
$months = [];
for ($i = 0; $i >= -11; $i--) {
    $monthDate = strtotime("$i months");
    $monthNum = date('m', $monthDate);
    $year = date('Y', $monthDate);
    $months[] = [
        'offset' => $i,
        'name' => $turkishMonths[$monthNum] . ' ' . $year,
        'short' => $turkishMonths[$monthNum]
    ];
}

// Genel istatistikler
$totalBonusPayout = array_sum(array_column($bonusData, 'total_bonus'));
$totalPersonnel = count($bonusData);
$avgBonus = $totalPersonnel > 0 ? $totalBonusPayout / $totalPersonnel : 0;

?>

<div class="page-header">
    <div class="header-content">
        <h1 class="page-title">💰 Prim Hesaplama Sistemi</h1>
        <?php if (Auth::isAdmin()): ?>
        <div class="header-actions">
            <button onclick="window.print()" class="btn btn-success">🖨️ Yazdır</button>
            <button onclick="exportToExcel()" class="btn btn-primary">📊 Excel'e Aktar</button>
        </div>
        <?php endif; ?>
    </div>
</div>

<!-- Hızlı Filtreler (Ay Bazlı) -->
<div class="filters-container">
    <div class="quick-filters">
        <?php foreach ($months as $month): ?>
            <?php
                $isActive = $quickFilter === "month_{$month['offset']}" || (!$quickFilter && $month['offset'] === 0);
            ?>
            <a href="?quick_filter=month_<?php echo $month['offset']; ?>"
               class="quick-filter-btn <?php echo $isActive ? 'active' : ''; ?>">
                <?php echo $month['name']; ?>
            </a>
        <?php endforeach; ?>
    </div>
</div>

<!-- Detaylı Prim Dağılımı -->
<div class="data-table-container">
    <div class="section-header">
        <h2 class="section-title">📋 Detaylı Prim Dağılımı - <?php echo $turkishMonths[date('m', strtotime($startDate))]; ?> <?php echo date('Y', strtotime($startDate)); ?></h2>
    </div>

    <div class="table-scroll-wrapper">
    <table class="performance-table">
        <thead>
            <tr>
                <th rowspan="2" class="sticky-col">Destek Temsilcisi</th>
                <th colspan="2" class="group-header incoming-group">Gelen Çağrı</th>
                <th colspan="2" class="group-header outgoing-group">Giden Çağrı</th>
                <th rowspan="2" class="group-header support-group">Destek<br>Mesajı</th>
                <?php foreach ($criteriaByCategory['Paket Kriterleri'] ?? [] as $pkg):
                    // Paket adını iki satıra böl
                    $packageName = $pkg['name'];
                    $packageNameFormatted = str_replace(' Paket', '<br>Paket', $packageName);
                    $packageNameFormatted = str_replace(' Mini ', '<br>Mini ', $packageNameFormatted);
                    $packageNameFormatted = str_replace(' ERP', '<br>ERP', $packageNameFormatted);
                    $packageNameFormatted = str_replace(' Maksi', '<br>Maksi', $packageNameFormatted);
                    $packageNameFormatted = str_replace(' Logo', '<br>Logo', $packageNameFormatted);
                    $packageNameFormatted = str_replace(' Nebim', '<br>Nebim', $packageNameFormatted);
                    $packageNameFormatted = str_replace('Lisans ', 'Lisans<br>', $packageNameFormatted);
                ?>
                    <th rowspan="2" class="package-col" style="background: <?php echo getPackageTypeColor($pkg['name']); ?>;">
                        <?php echo $packageNameFormatted; ?>
                    </th>
                <?php endforeach; ?>
            </tr>
            <tr>
                <th class="sub-header incoming-group">Sayı</th>
                <th class="sub-header incoming-group">Süre</th>
                <th class="sub-header outgoing-group">Sayı</th>
                <th class="sub-header outgoing-group">Süre</th>
            </tr>
        </thead>
        <tbody>
            <?php
            // Her paket kolonu için maksimum değerleri hesapla (dikey karşılaştırma için)
            $packageMaxValues = [];
            foreach ($criteriaByCategory['Paket Kriterleri'] ?? [] as $pkg) {
                $maxValue = 0;
                foreach ($bonusData as $data) {
                    foreach ($data['package_counts'] as $pkgName => $pkgCount) {
                        if (stripos($pkgName, $pkg['name']) !== false || stripos($pkg['name'], $pkgName) !== false) {
                            if ($pkgCount > $maxValue) {
                                $maxValue = $pkgCount;
                            }
                            break;
                        }
                    }
                }
                $packageMaxValues[$pkg['name']] = $maxValue;
            }

            // Toplam satırı için değerleri topla
            $totalIncomingCalls = 0;
            $totalIncomingDuration = 0;
            $totalOutgoingCalls = 0;
            $totalOutgoingDuration = 0;
            $totalSupportMessages = 0;
            $totalPackageCounts = [];

            foreach ($bonusData as $data):
                $totalIncomingCalls += $data['incoming_calls'];
                $totalIncomingDuration += $data['incoming_duration'];
                $totalOutgoingCalls += $data['outgoing_calls'];
                $totalOutgoingDuration += $data['outgoing_duration'];
                $totalSupportMessages += $data['support_messages'];

                foreach ($data['package_counts'] as $pkg => $count) {
                    if (!isset($totalPackageCounts[$pkg])) {
                        $totalPackageCounts[$pkg] = 0;
                    }
                    $totalPackageCounts[$pkg] += $count;
                }
            ?>
                <tr class="clickable-row" onclick="showBonusDetails('<?php echo htmlspecialchars($data['representative'], ENT_QUOTES); ?>', '<?php echo $startDate; ?>', '<?php echo $endDate; ?>')">
                    <td class="sticky-col personnel-name"><?php echo htmlspecialchars($data['representative']); ?></td>
                    <td class="incoming-cell"><?php echo $data['incoming_calls']; ?></td>
                    <td class="incoming-cell"><?php echo formatDuration($data['incoming_duration']); ?></td>
                    <td class="outgoing-cell"><?php echo $data['outgoing_calls']; ?></td>
                    <td class="outgoing-cell"><?php echo formatDuration($data['outgoing_duration']); ?></td>
                    <td class="support-cell"><?php echo $data['support_messages'] > 0 ? $data['support_messages'] : '-'; ?></td>
                    <?php foreach ($criteriaByCategory['Paket Kriterleri'] ?? [] as $pkg):
                        $count = 0;
                        foreach ($data['package_counts'] as $pkgName => $pkgCount) {
                            if (stripos($pkgName, $pkg['name']) !== false || stripos($pkg['name'], $pkgName) !== false) {
                                $count = $pkgCount;
                                break;
                            }
                        }

                        // Renk sınıfını belirle (dikey karşılaştırma - her kolon kendi içinde)
                        $cellClass = 'package-cell';
                        $maxForThisPackage = $packageMaxValues[$pkg['name']] ?? 0;

                        if ($count == 0) {
                            $cellClass .= ' package-zero';
                        } elseif ($maxForThisPackage > 0) {
                            // Yüzdelik dilim hesapla
                            $percentage = ($count / $maxForThisPackage) * 100;

                            if ($percentage >= 80) {
                                $cellClass .= ' package-high';      // %80-100: Koyu yeşil
                            } elseif ($percentage >= 50) {
                                $cellClass .= ' package-medium';    // %50-79: Yeşil
                            } else {
                                $cellClass .= ' package-low';       // %1-49: Sarı
                            }
                        } else {
                            $cellClass .= ' package-low';
                        }
                    ?>
                        <td class="<?php echo $cellClass; ?>"><?php echo $count > 0 ? $count : '-'; ?></td>
                    <?php endforeach; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr class="total-row">
                <td class="sticky-col"><strong>TOPLAM</strong></td>
                <td class="incoming-cell"><strong><?php echo $totalIncomingCalls; ?></strong></td>
                <td class="incoming-cell"><strong><?php echo formatDuration($totalIncomingDuration); ?></strong></td>
                <td class="outgoing-cell"><strong><?php echo $totalOutgoingCalls; ?></strong></td>
                <td class="outgoing-cell"><strong><?php echo formatDuration($totalOutgoingDuration); ?></strong></td>
                <td class="support-cell"><strong><?php echo $totalSupportMessages; ?></strong></td>
                <?php foreach ($criteriaByCategory['Paket Kriterleri'] ?? [] as $pkg):
                    $total = 0;
                    foreach ($totalPackageCounts as $pkgName => $count) {
                        if (stripos($pkgName, $pkg['name']) !== false || stripos($pkg['name'], $pkgName) !== false) {
                            $total = $count;
                            break;
                        }
                    }
                ?>
                    <td class="package-cell"><strong><?php echo $total; ?></strong></td>
                <?php endforeach; ?>
            </tr>
        </tfoot>
    </table>
    </div>
</div>

<!-- Performans Puanlama Tablosu -->
<div class="data-table-container">
    <div class="section-header">
        <h2 class="section-title">🎯 Performans Puanlama - <?php echo $turkishMonths[date('m', strtotime($startDate))]; ?> <?php echo date('Y', strtotime($startDate)); ?></h2>
        <div class="section-subtitle">
            Kriterlere göre puanlama sistemi (Yönetici hariç hesaplanır)
        </div>
    </div>

    <div class="table-scroll-wrapper">
    <table class="performance-table">
        <thead>
            <tr>
                <th rowspan="2" class="sticky-col">Destek Temsilcisi</th>
                <th colspan="2" class="group-header incoming-group">Gelen Çağrı Puanları</th>
                <th colspan="2" class="group-header outgoing-group">Giden Çağrı Puanları</th>
                <th colspan="1" class="group-header support-group">Destek Mesajı<br>Puanları</th>
                <th rowspan="2" class="package-score-header">Oransal<br>Paket Puanı<br><small>(<?php echo number_format($criteriaPoints['egitim_orani'] ?? 0, 2); ?> puan)</small></th>
                <th rowspan="2" class="bonus-score-header">Bonus<br>Puan<br><small>(Direkt)</small></th>
                <th rowspan="2" class="total-score-header">Toplam<br>Puan</th>
                <th rowspan="2" class="bonus-amount-header">💰 Prim<br>Tutarı<br><small>(₺<?php echo number_format($primTutari, 0); ?>)</small></th>
            </tr>
            <tr>
                <th class="sub-header incoming-group">
                    Arama<br>
                    <small>(<?php echo number_format($criteriaPoints['gelen_arama_sayisi'] ?? 0, 2); ?> puan)</small>
                </th>
                <th class="sub-header incoming-group">
                    Süre<br>
                    <small>(<?php echo number_format($criteriaPoints['gelen_arama_suresi'] ?? 0, 2); ?> puan)</small>
                </th>
                <th class="sub-header outgoing-group">
                    Arama<br>
                    <small>(<?php echo number_format($criteriaPoints['giden_arama_sayisi'] ?? 0, 2); ?> puan)</small>
                </th>
                <th class="sub-header outgoing-group">
                    Süre<br>
                    <small>(<?php echo number_format($criteriaPoints['giden_arama_suresi'] ?? 0, 2); ?> puan)</small>
                </th>
                <th class="sub-header support-group">
                    Sayı<br>
                    <small>(<?php echo number_format($criteriaPoints['destek_mesaj_sayisi'] ?? 0, 2); ?> puan)</small>
                </th>
            </tr>
        </thead>
        <tbody>
            <?php
            // Maksimum puanı bul (yüzdelik hesaplama için)
            $maxTotalScore = 0;
            foreach ($bonusData as $data) {
                if ($data['total_score'] > $maxTotalScore) {
                    $maxTotalScore = $data['total_score'];
                }
            }

            // Toplam puanları hesapla (footer için)
            $totalScoreIncoming = 0;
            $totalScoreIncomingDuration = 0;
            $totalScoreOutgoing = 0;
            $totalScoreOutgoingDuration = 0;
            $totalScoreSupport = 0;
            $totalScoreProportional = 0;
            $totalScoreBonus = 0;
            $grandTotalScore = 0;
            $totalBonusAmount = 0;

            foreach ($bonusData as $data):
                $isMustafa = (stripos($data['representative'], 'Mustafa') !== false && stripos($data['representative'], 'SÜLERYA') !== false);

                if (!$isMustafa) {
                    $totalScoreIncoming += $data['score_incoming_calls'];
                    $totalScoreIncomingDuration += $data['score_incoming_duration'];
                    $totalScoreOutgoing += $data['score_outgoing_calls'];
                    $totalScoreOutgoingDuration += $data['score_outgoing_duration'];
                    $totalScoreSupport += $data['score_support_messages'];
                    $totalScoreProportional += $data['score_proportional_packages'];
                    $totalScoreBonus += $data['score_bonus_packages'];
                    $grandTotalScore += $data['total_score'];
                    $totalBonusAmount += $data['bonus_amount'] ?? 0;
                }

                // Yüzdelik hesaplama
                $percentage = $maxTotalScore > 0 ? ($data['total_score'] / $maxTotalScore) * 100 : 0;

                // Sıra renk sınıfı
                $rowClass = '';
                if ($isMustafa) {
                    $rowClass = 'manager-row';
                } elseif ($percentage >= 85) {
                    $rowClass = 'score-excellent';
                } elseif ($percentage >= 70) {
                    $rowClass = 'score-good';
                } elseif ($percentage >= 55) {
                    $rowClass = 'score-average';
                } else {
                    $rowClass = 'score-low';
                }
            ?>
                <tr class="<?php echo $rowClass; ?>">
                    <td class="sticky-col personnel-name"><?php echo htmlspecialchars($data['representative']); ?></td>
                    <td class="incoming-cell score-cell">
                        <?php echo $isMustafa ? '-' : number_format($data['score_incoming_calls'], 2); ?>
                        <?php if (!$isMustafa && $data['score_incoming_calls'] > 0): ?>
                            <br><small class="percentage-display"><?php echo number_format(($data['score_incoming_calls'] / ($criteriaPoints['gelen_arama_sayisi'] ?? 1)) * 100, 1); ?>%</small>
                        <?php endif; ?>
                    </td>
                    <td class="incoming-cell score-cell">
                        <?php echo $isMustafa ? '-' : number_format($data['score_incoming_duration'], 2); ?>
                        <?php if (!$isMustafa && $data['score_incoming_duration'] > 0): ?>
                            <br><small class="percentage-display"><?php echo number_format(($data['score_incoming_duration'] / ($criteriaPoints['gelen_arama_suresi'] ?? 1)) * 100, 1); ?>%</small>
                        <?php endif; ?>
                    </td>
                    <td class="outgoing-cell score-cell">
                        <?php echo $isMustafa ? '-' : number_format($data['score_outgoing_calls'], 2); ?>
                        <?php if (!$isMustafa && $data['score_outgoing_calls'] > 0): ?>
                            <br><small class="percentage-display"><?php echo number_format(($data['score_outgoing_calls'] / ($criteriaPoints['giden_arama_sayisi'] ?? 1)) * 100, 1); ?>%</small>
                        <?php endif; ?>
                    </td>
                    <td class="outgoing-cell score-cell">
                        <?php echo $isMustafa ? '-' : number_format($data['score_outgoing_duration'], 2); ?>
                        <?php if (!$isMustafa && $data['score_outgoing_duration'] > 0): ?>
                            <br><small class="percentage-display"><?php echo number_format(($data['score_outgoing_duration'] / ($criteriaPoints['giden_arama_suresi'] ?? 1)) * 100, 1); ?>%</small>
                        <?php endif; ?>
                    </td>
                    <td class="support-cell score-cell">
                        <?php if ($isMustafa): ?>
                            -
                        <?php else: ?>
                            <?php echo number_format($data['score_support_messages'], 2); ?>
                            <?php if ($data['support_messages'] > 0): ?>
                                <br><small style="color:#888;"><?php echo $data['support_messages']; ?> msg</small>
                            <?php endif; ?>
                        <?php endif; ?>
                    </td>
                    <td class="package-score-cell score-cell has-tooltip">
                        <?php if (!$isMustafa): ?>
                            <span class="info-icon">ℹ️</span>
                            <?php echo number_format($data['score_proportional_packages'], 2); ?>
                            <?php if ($data['score_proportional_packages'] > 0): ?>
                                <br><small class="percentage-display"><?php echo number_format(($data['score_proportional_packages'] / ($criteriaPoints['egitim_orani'] ?? 1)) * 100, 1); ?>%</small>
                            <?php endif; ?>

                            <div class="score-tooltip">
                                <div class="tooltip-header">📦 Oransal Paket Detayı</div>
                                <?php if (!empty($data['proportional_details'])): ?>
                                    <table class="tooltip-table">
                                        <tr>
                                            <th>Paket</th>
                                            <th>Adet</th>
                                            <th>Ağırlık</th>
                                            <th>Toplam</th>
                                        </tr>
                                        <?php foreach ($data['proportional_details'] as $detail): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($detail['name']); ?></td>
                                                <td><?php echo $detail['count']; ?></td>
                                                <td><?php echo $detail['weight']; ?></td>
                                                <td><?php echo number_format($detail['weighted'], 2); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                        <tr class="tooltip-total">
                                            <td colspan="3"><strong>Ağırlıklı Toplam:</strong></td>
                                            <td><strong><?php echo number_format($data['proportional_weighted_total'], 2); ?></strong></td>
                                        </tr>
                                    </table>
                                    <div class="tooltip-formula">
                                        <strong>Hesaplama:</strong><br>
                                        (<?php echo number_format($data['proportional_weighted_total'], 2); ?> / <?php echo number_format($totalProportionalWeighted, 2); ?>) × <?php echo $criteriaPoints['egitim_orani'] ?? 0; ?> = <?php echo number_format($data['score_proportional_packages'], 2); ?> puan
                                    </div>
                                <?php else: ?>
                                    <p class="tooltip-empty">Bu personelin oransal paketi yok</p>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                    <td class="bonus-score-cell score-cell has-tooltip">
                        <?php if (!$isMustafa): ?>
                            <?php if ($data['score_bonus_packages'] > 0): ?>
                                <span class="info-icon">ℹ️</span>
                            <?php endif; ?>
                            <?php echo number_format($data['score_bonus_packages'], 2); ?>

                            <?php if (!empty($data['bonus_details'])): ?>
                                <div class="score-tooltip">
                                    <div class="tooltip-header">🎁 Bonus Paket Detayı</div>
                                    <table class="tooltip-table">
                                        <tr>
                                            <th>Paket</th>
                                            <th>Adet</th>
                                            <th>Puan/Adet</th>
                                            <th>Toplam</th>
                                        </tr>
                                        <?php foreach ($data['bonus_details'] as $detail): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($detail['name']); ?></td>
                                                <td><?php echo $detail['count']; ?></td>
                                                <td>+<?php echo number_format($detail['point'], 2); ?></td>
                                                <td>+<?php echo number_format($detail['total'], 2); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                        <tr class="tooltip-total">
                                            <td colspan="3"><strong>Toplam Bonus:</strong></td>
                                            <td><strong>+<?php echo number_format($data['score_bonus_packages'], 2); ?></strong></td>
                                        </tr>
                                    </table>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                    <td class="total-score-cell score-cell has-tooltip">
                        <?php if (!$isMustafa): ?>
                            <span class="info-icon">ℹ️</span>
                            <strong><?php echo number_format($data['total_score'], 2); ?></strong>
                            <?php if ($maxTotalScore > 0): ?>
                                <br><small class="percentage-display"><?php echo number_format($percentage, 1); ?>%</small>
                            <?php endif; ?>

                            <div class="score-tooltip">
                                <div class="tooltip-header">📊 Toplam Puan Detayı</div>
                                <table class="tooltip-table">
                                    <tr>
                                        <th>Kriter</th>
                                        <th>Puan</th>
                                    </tr>
                                    <tr>
                                        <td>📞 Gelen Arama Puanı</td>
                                        <td><?php echo number_format($data['score_incoming_calls'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>⏱️ Gelen Süre Puanı</td>
                                        <td><?php echo number_format($data['score_incoming_duration'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>📱 Giden Arama Puanı</td>
                                        <td><?php echo number_format($data['score_outgoing_calls'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>⏰ Giden Süre Puanı</td>
                                        <td><?php echo number_format($data['score_outgoing_duration'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>💬 Destek Mesajı Puanı</td>
                                        <td><?php echo number_format($data['score_support_messages'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>📦 Oransal Paket Puanı</td>
                                        <td><?php echo number_format($data['score_proportional_packages'], 2); ?></td>
                                    </tr>
                                    <tr>
                                        <td>🎁 Bonus Puan</td>
                                        <td>+<?php echo number_format($data['score_bonus_packages'], 2); ?></td>
                                    </tr>
                                    <tr class="tooltip-total">
                                        <td><strong>TOPLAM:</strong></td>
                                        <td><strong><?php echo number_format($data['total_score'], 2); ?></strong></td>
                                    </tr>
                                </table>
                            </div>
                        <?php else: ?>
                            <strong>-</strong>
                        <?php endif; ?>
                    </td>
                    <td class="bonus-amount-cell score-cell has-tooltip">
                        <?php if (!$isMustafa): ?>
                            <?php if ($data['gets_bonus']): ?>
                                <span class="info-icon">ℹ️</span>
                                <strong style="color: #27ae60;">₺<?php echo number_format($data['bonus_amount'], 0); ?></strong>
                                <br><small class="percentage-display"><?php echo number_format($data['bonus_percentage'], 1); ?>%</small>

                                <div class="score-tooltip">
                                    <div class="tooltip-header">💰 Prim Hesaplama Detayı</div>
                                    <div class="tooltip-formula" style="text-align: left; padding: 10px;">
                                        <strong>Personel Puanı:</strong> <?php echo number_format($data['total_score'], 2); ?><br>
                                        <?php
                                        // Puan yüzdesini göster
                                        if (isset($maxTheoreticalScore) && $maxTheoreticalScore > 0) {
                                            $ownPerc = ($data['total_score'] / $maxTheoreticalScore) * 100;
                                            echo '<strong>Puan Yüzdesi:</strong> ' . number_format($ownPerc, 2) . '% (' . number_format($data['total_score'], 2) . ' / 100)<br>';
                                        }

                                        // En yüksek puanlı mı kontrol et
                                        if (isset($highestPerson) && $data['user_id'] === $highestPerson['user_id'] && !empty($data['extra_bonus_info'])) {
                                            echo '<hr style="margin: 8px 0; border: none; border-top: 1px solid #ddd;">';
                                            echo '<strong style="color: #f39c12;">🏆 Ekstra Performans Bonusu:</strong><br>';
                                            echo '<small>' . htmlspecialchars($data['extra_bonus_info']) . '</small><br>';
                                        }
                                        ?>
                                        <hr style="margin: 8px 0; border: none; border-top: 1px solid #ddd;">
                                        <strong>Toplam Prim Payı:</strong> %<?php echo number_format($data['bonus_percentage'], 2); ?><br>
                                        <strong>Prim Tutarı (Yuvarlanmış):</strong> ₺<?php echo number_format($data['bonus_amount'], 0); ?>
                                    </div>
                                </div>
                            <?php else: ?>
                                <span style="color: #e74c3c;">-</span>
                                <br><small style="color: #e74c3c;">Prim Yok</small>
                            <?php endif; ?>
                        <?php else: ?>
                            <strong>-</strong>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
        <tfoot>
            <tr class="total-row">
                <td class="sticky-col"><strong>TOPLAM</strong></td>
                <td class="incoming-cell"><strong><?php echo number_format($totalScoreIncoming, 2); ?></strong></td>
                <td class="incoming-cell"><strong><?php echo number_format($totalScoreIncomingDuration, 2); ?></strong></td>
                <td class="outgoing-cell"><strong><?php echo number_format($totalScoreOutgoing, 2); ?></strong></td>
                <td class="outgoing-cell"><strong><?php echo number_format($totalScoreOutgoingDuration, 2); ?></strong></td>
                <td class="support-cell"><strong><?php echo number_format($totalScoreSupport, 2); ?></strong></td>
                <td class="package-score-cell"><strong><?php echo number_format($totalScoreProportional, 2); ?></strong></td>
                <td class="bonus-score-cell"><strong><?php echo number_format($totalScoreBonus, 2); ?></strong></td>
                <td class="total-score-cell"><strong><?php echo number_format($grandTotalScore, 2); ?></strong></td>
                <td class="bonus-amount-cell"><strong style="color: #27ae60;">₺<?php echo number_format($totalBonusAmount, 0); ?></strong></td>
            </tr>
        </tfoot>
    </table>
    </div>
</div>

<!-- Bonus Detay Modal -->
<div id="bonusModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="bonusModalTitle">Prim Detayları</h2>
            <span class="close" onclick="closeBonusModal()">×</span>
        </div>
        <div id="bonusModalContent" class="modal-body">
            <div class="loading">Yükleniyor...</div>
        </div>
    </div>
</div>

<script>
// Prim detaylarını göster
async function showBonusDetails(representative, startDate, endDate) {
    const modal = document.getElementById('bonusModal');
    const title = document.getElementById('bonusModalTitle');
    const content = document.getElementById('bonusModalContent');

    modal.style.display = 'flex';
    title.textContent = '💰 ' + representative + ' - Prim Detayları';
    content.innerHTML = '<div class="loading">Yükleniyor...</div>';

    try {
        const response = await fetch('get_bonus_details.php?representative=' + encodeURIComponent(representative) + '&start_date=' + startDate + '&end_date=' + endDate);
        const data = await response.json();

        if (data.success) {
            renderBonusDetails(data);
        } else {
            console.error('API Error:', data);
            let errorMsg = '<div class="error"><strong>Hata:</strong> ' + (data.message || 'Prim detayları yüklenemedi.') + '</div>';
            if (data.line) {
                errorMsg += '<div style="margin-top: 10px; font-size: 12px; color: #666;">Satır: ' + data.line + '</div>';
            }
            content.innerHTML = errorMsg;
        }
    } catch (error) {
        console.error('Fetch Error:', error);
        content.innerHTML = '<div class="error">Veriler yüklenirken bir hata oluştu: ' + error.message + '</div>';
    }
}

// Paket renklendirme fonksiyonu - Her paket türü için benzersiz renk
function getPackageColorJS(packageType) {
    const pkg = packageType.toLowerCase().trim();

    // Her paket türü için TAMAMEN FARKLI renkler
    if (pkg === 'profesyonel paket') return '#28B463';  // Yeşil
    if (pkg === 'gelişmiş paket') return '#17A2B8';      // Cyan/Turkuaz
    if (pkg === 'uzman paket') return '#8E44AD';         // Mor/Violet
    if (pkg === 'ideasoft maksi') return '#007BFF';      // Parlak Mavi
    if (pkg === 'ideasoft erp') return '#1A1A2E';        // Koyu Lacivert
    if (pkg === 'google yorum') return '#FF6B35';        // Turuncu-Kırmızı

    // Contains kontrolü (tam eşleşme bulunamazsa)
    if (pkg.includes('profesyonel')) return '#28B463';
    if (pkg.includes('gelişmiş') || pkg.includes('gelismis')) return '#17A2B8';
    if (pkg.includes('uzman')) return '#8E44AD';
    if (pkg.includes('ideasoft')) {
        if (pkg.includes('maksi')) return '#007BFF';
        if (pkg.includes('erp')) return '#1A1A2E';
        if (pkg.includes('mini')) return '#5DADE2';
        return '#3498DB';
    }
    if (pkg.includes('google')) return '#FF6B35';
    if (pkg.includes('sopyo')) {
        if (pkg.includes('logo')) return '#9B59B6';
        if (pkg.includes('nebim')) return '#7D3C98';
        return '#8A6FA9';
    }
    if (pkg.includes('lisans') || pkg.includes('yenileme')) return '#E67E22';

    return '#95A5A6'; // Gri - Diğer
}

// Satış tipi renklendirme
function getSalesTypeColor(salesType) {
    if (!salesType) return '#95a5a6';
    const type = salesType.toLowerCase();

    if (type.includes('yeni')) return '#27ae60'; // Yeşil - Yeni Satış
    if (type.includes('yenileme')) return '#e67e22'; // Turuncu - Yenileme
    if (type.includes('upgrade') || type.includes('yükseltme')) return '#3498db'; // Mavi - Upgrade
    if (type.includes('destek')) return '#9b59b6'; // Mor - Destek

    return '#95a5a6'; // Gri - Diğer
}

// Prim detaylarını render et
function renderBonusDetails(data) {
    const content = document.getElementById('bonusModalContent');
    const scores = data.scores;
    const rawData = data.raw_data;
    const packageDetails = data.package_details;
    const criteriaPoints = data.criteria_points;

    let html = '<div class="bonus-details">';

    // Performans Puanlama Özeti
    html += '<div class="bonus-stats-header">';
    html += '<div class="bonus-stats-main">';
    html += '<div class="bonus-stat-item"><span class="bonus-stat-label">Toplam Puan</span><strong class="bonus-stat-big">' + scores.total_score.toFixed(2) + '</strong></div>';
    html += '<div class="bonus-stat-item"><span class="bonus-stat-label">Puan Yüzdesi</span><strong class="bonus-stat-value">' + scores.score_percentage.toFixed(1) + '%</strong></div>';
    html += '<div class="bonus-stat-item"><span class="bonus-stat-label">Maks. Puan</span><strong class="bonus-stat-value">' + data.max_theoretical_score.toFixed(0) + '</strong></div>';
    html += '</div>';
    html += '</div>';

    // Sekmeler
    html += '<div class="bonus-tabs">';
    html += '<button class="bonus-tab active" onclick="switchBonusTab(\'scores\')">📊 Puan Detayı</button>';
    html += '<button class="bonus-tab" onclick="switchBonusTab(\'packages\')">📦 Paket Detayı</button>';
    html += '<button class="bonus-tab" onclick="switchBonusTab(\'trainings\')">🎓 Eğitimler (' + data.trainings.length + ')</button>';
    html += '</div>';

    // Puan Detayı Sekmesi
    html += '<div id="scoresTab" class="bonus-tab-content active">';
    html += '<h3 class="bonus-section-title">📊 Performans Puan Dökümü</h3>';
    html += '<table class="bonus-detail-table">';
    html += '<thead><tr><th>Kriter</th><th>Ham Veri</th><th>Puan</th><th>Maks. Puan</th><th>Oran</th></tr></thead>';
    html += '<tbody>';

    // Kriter puanlarını number'a çevir
    const gelenAramaSayisi = parseFloat(criteriaPoints.gelen_arama_sayisi) || 0;
    const gelenAramaSuresi = parseFloat(criteriaPoints.gelen_arama_suresi) || 0;
    const gidenAramaSayisi = parseFloat(criteriaPoints.giden_arama_sayisi) || 0;
    const gidenAramaSuresi = parseFloat(criteriaPoints.giden_arama_suresi) || 0;
    const egitimOrani = parseFloat(criteriaPoints.egitim_orani) || 0;

    html += '<tr>';
    html += '<td>📞 Gelen Arama Sayısı</td>';
    html += '<td>' + rawData.incoming_calls + ' arama</td>';
    html += '<td><strong>' + scores.incoming_calls.toFixed(2) + '</strong></td>';
    html += '<td>' + gelenAramaSayisi.toFixed(2) + '</td>';
    html += '<td>' + (gelenAramaSayisi > 0 ? ((scores.incoming_calls / gelenAramaSayisi) * 100).toFixed(1) : '0.0') + '%</td>';
    html += '</tr>';

    html += '<tr>';
    html += '<td>⏱️ Gelen Arama Süresi</td>';
    html += '<td>' + Math.floor(rawData.incoming_duration / 60) + ' dk</td>';
    html += '<td><strong>' + scores.incoming_duration.toFixed(2) + '</strong></td>';
    html += '<td>' + gelenAramaSuresi.toFixed(2) + '</td>';
    html += '<td>' + (gelenAramaSuresi > 0 ? ((scores.incoming_duration / gelenAramaSuresi) * 100).toFixed(1) : '0.0') + '%</td>';
    html += '</tr>';

    html += '<tr>';
    html += '<td>📱 Giden Arama Sayısı</td>';
    html += '<td>' + rawData.outgoing_calls + ' arama</td>';
    html += '<td><strong>' + scores.outgoing_calls.toFixed(2) + '</strong></td>';
    html += '<td>' + gidenAramaSayisi.toFixed(2) + '</td>';
    html += '<td>' + (gidenAramaSayisi > 0 ? ((scores.outgoing_calls / gidenAramaSayisi) * 100).toFixed(1) : '0.0') + '%</td>';
    html += '</tr>';

    html += '<tr>';
    html += '<td>⏰ Giden Arama Süresi</td>';
    html += '<td>' + Math.floor(rawData.outgoing_duration / 60) + ' dk</td>';
    html += '<td><strong>' + scores.outgoing_duration.toFixed(2) + '</strong></td>';
    html += '<td>' + gidenAramaSuresi.toFixed(2) + '</td>';
    html += '<td>' + (gidenAramaSuresi > 0 ? ((scores.outgoing_duration / gidenAramaSuresi) * 100).toFixed(1) : '0.0') + '%</td>';
    html += '</tr>';

    html += '<tr>';
    html += '<td>📦 Oransal Paket Puanı</td>';
    html += '<td>' + packageDetails.proportional_weighted_total.toFixed(2) + ' ağırlık</td>';
    html += '<td><strong>' + scores.proportional_packages.toFixed(2) + '</strong></td>';
    html += '<td>' + egitimOrani.toFixed(2) + '</td>';
    html += '<td>' + (egitimOrani > 0 ? ((scores.proportional_packages / egitimOrani) * 100).toFixed(1) : '0.0') + '%</td>';
    html += '</tr>';

    html += '<tr>';
    html += '<td>🎁 Bonus Puan</td>';
    html += '<td>-</td>';
    html += '<td><strong>+' + scores.bonus_packages.toFixed(2) + '</strong></td>';
    html += '<td>-</td>';
    html += '<td>-</td>';
    html += '</tr>';

    html += '<tr class="calc-total">';
    html += '<td><strong>TOPLAM</strong></td>';
    html += '<td></td>';
    html += '<td><strong>' + scores.total_score.toFixed(2) + '</strong></td>';
    html += '<td><strong>' + data.max_theoretical_score.toFixed(2) + '</strong></td>';
    html += '<td><strong>' + scores.score_percentage.toFixed(1) + '%</strong></td>';
    html += '</tr>';

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

    // Paket Detayı Sekmesi
    html += '<div id="packagesTab" class="bonus-tab-content">';
    html += '<h3 class="bonus-section-title">📦 Paket Detayı</h3>';

    if (packageDetails.proportional.length > 0 || packageDetails.bonus.length > 0) {
        // Oransal Paketler
        if (packageDetails.proportional.length > 0) {
            html += '<h4 style="margin-top: 20px;">📦 Oransal Paketler</h4>';
            html += '<table class="bonus-detail-table">';
            html += '<thead><tr><th>Paket</th><th>Adet</th><th>Ağırlık</th><th>Toplam</th></tr></thead>';
            html += '<tbody>';
            packageDetails.proportional.forEach(pkg => {
                html += '<tr>';
                html += '<td><strong>' + escapeHtml(pkg.name) + '</strong></td>';
                html += '<td>' + pkg.count + '</td>';
                html += '<td>' + pkg.weight + '</td>';
                html += '<td>' + pkg.weighted.toFixed(2) + '</td>';
                html += '</tr>';
            });
            html += '<tr class="calc-total">';
            html += '<td colspan="3"><strong>Bu Personelin Ağırlıklı Toplamı:</strong></td>';
            html += '<td><strong>' + packageDetails.proportional_weighted_total.toFixed(2) + '</strong></td>';
            html += '</tr>';
            html += '</tbody></table>';

            // Puan hesaplama formülü
            if (packageDetails.total_proportional_weighted > 0) {
                html += '<div style="margin-top: 15px; padding: 10px; background: #f5f7fa; border-radius: 8px;">';
                html += '<strong>Puan Hesaplama:</strong><br>';
                html += '(' + packageDetails.proportional_weighted_total.toFixed(2) + ' / ' + packageDetails.total_proportional_weighted.toFixed(2) + ') × ' + egitimOrani.toFixed(2) + ' = ';
                html += '<strong>' + scores.proportional_packages.toFixed(2) + ' puan</strong>';
                html += '</div>';
            }
        }

        // Bonus Paketler
        if (packageDetails.bonus.length > 0) {
            html += '<h4 style="margin-top: 20px;">🎁 Bonus Paketler</h4>';
            html += '<table class="bonus-detail-table">';
            html += '<thead><tr><th>Paket</th><th>Adet</th><th>Puan/Adet</th><th>Toplam</th></tr></thead>';
            html += '<tbody>';
            packageDetails.bonus.forEach(pkg => {
                html += '<tr>';
                html += '<td><strong>' + escapeHtml(pkg.name) + '</strong></td>';
                html += '<td>' + pkg.count + '</td>';
                html += '<td>+' + pkg.point.toFixed(2) + '</td>';
                html += '<td>+' + pkg.total.toFixed(2) + '</td>';
                html += '</tr>';
            });
            html += '<tr class="calc-total">';
            html += '<td colspan="3"><strong>Toplam Bonus:</strong></td>';
            html += '<td><strong>+' + scores.bonus_packages.toFixed(2) + '</strong></td>';
            html += '</tr>';
            html += '</tbody></table>';
        }
    } else {
        html += '<p class="no-data">Bu dönemde paket kaydı bulunamadı.</p>';
    }
    html += '</div>';

    // Eğitimler Sekmesi
    html += '<div id="trainingsTab" class="bonus-tab-content">';
    html += '<h3 class="bonus-section-title">🎓 Eğitim Tamamlama Kayıtları</h3>';
    if (data.trainings.length > 0) {
        // Mükerrer firma tespiti için firma sayılarını hesapla
        const companyCounts = {};
        data.trainings.forEach(training => {
            const companyName = training.company_name;
            companyCounts[companyName] = (companyCounts[companyName] || 0) + 1;
        });

        html += '<table class="bonus-detail-table">';
        html += '<thead><tr><th>Tarih</th><th>Firma</th><th>Paket Türü</th><th>Satış Tipi</th></tr></thead>';
        html += '<tbody>';
        data.trainings.forEach(training => {
            const isDuplicate = companyCounts[training.company_name] > 1;
            const rowClass = isDuplicate ? ' style="background-color: #fff3cd;"' : '';

            html += '<tr' + rowClass + '>';
            html += '<td>' + formatDate(training.training_completion_date) + '</td>';

            // Firma - mükerrer ise işaretle
            if (isDuplicate) {
                html += '<td><strong style="color: #856404;">🔁 ' + escapeHtml(training.company_name) + '</strong></td>';
            } else {
                html += '<td><strong>' + escapeHtml(training.company_name) + '</strong></td>';
            }

            // Paket Türü - renkli badge
            const packageColor = getPackageColorJS(training.package_type);
            html += '<td><span class="package-badge" style="background: ' + packageColor + ' !important; color: white; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600;">' + escapeHtml(training.package_type) + '</span></td>';

            // Satış Tipi - renkli badge
            const salesType = training.sales_type || '-';
            if (salesType !== '-') {
                const salesColor = getSalesTypeColor(salesType);
                html += '<td><span style="background: ' + salesColor + ' !important; color: white; padding: 4px 10px; border-radius: 12px; font-size: 11px; font-weight: 600;">' + escapeHtml(salesType) + '</span></td>';
            } else {
                html += '<td style="color: #95a5a6;">-</td>';
            }

            html += '</tr>';
        });
        html += '</tbody></table>';
    } else {
        html += '<p class="no-data">Bu dönemde eğitim kaydı bulunamadı.</p>';
    }
    html += '</div>';

    html += '</div>';
    content.innerHTML = html;
}

// Sekme değiştirme
function switchBonusTab(tabName) {
    // Tüm sekmeleri gizle
    document.querySelectorAll('.bonus-tab-content').forEach(tab => {
        tab.classList.remove('active');
    });

    // Tüm sekme butonlarını pasif yap
    document.querySelectorAll('.bonus-tab').forEach(btn => {
        btn.classList.remove('active');
    });

    // İlgili sekmeyi göster
    const tabMap = {
        'scores': 'scoresTab',
        'packages': 'packagesTab',
        'trainings': 'trainingsTab'
    };

    const tabId = tabMap[tabName];
    if (tabId) {
        document.getElementById(tabId).classList.add('active');
    }

    // İlgili butonu aktif yap
    event.target.classList.add('active');
}

function closeBonusModal() {
    document.getElementById('bonusModal').style.display = 'none';
}

function exportToExcel() {
    alert('Excel export özelliği yakında eklenecek!');
}

function formatDate(dateString) {
    if (!dateString) return '-';
    const date = new Date(dateString);
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return day + '.' + month + '.' + year;
}

function formatMoney(amount) {
    return parseFloat(amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
}

function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Modal dışına tıklayınca kapat
window.onclick = function(event) {
    const bonusModal = document.getElementById('bonusModal');
    if (event.target === bonusModal) {
        closeBonusModal();
    }
}

// Tooltip dinamik pozisyonlama
document.addEventListener('DOMContentLoaded', function() {
    const tooltipCells = document.querySelectorAll('.has-tooltip');

    tooltipCells.forEach(cell => {
        cell.addEventListener('mouseenter', function() {
            const tooltip = this.querySelector('.score-tooltip');
            if (!tooltip) return;

            const cellRect = this.getBoundingClientRect();
            const margin = 8;

            tooltip.style.display = 'block';
            tooltip.style.left = '0px';
            tooltip.style.transform = 'none';

            const tooltipWidth  = tooltip.offsetWidth;
            const tooltipHeight = tooltip.offsetHeight;

            // Yatay: önce hücre ortasına hizala, sonra viewport sınırını kontrol et
            let leftPos = cellRect.left + (cellRect.width / 2) - (tooltipWidth / 2);
            const maxLeft = window.innerWidth - tooltipWidth - margin;
            if (leftPos > maxLeft) leftPos = maxLeft;
            if (leftPos < margin) leftPos = margin;
            tooltip.style.left = leftPos + 'px';

            // Dikey: yukarı/aşağı karar ver
            const spaceAbove  = cellRect.top;
            const spaceBelow  = window.innerHeight - cellRect.bottom;
            const neededSpace = tooltipHeight + 20;

            if (spaceBelow >= neededSpace || spaceBelow > spaceAbove) {
                tooltip.classList.add('tooltip-bottom');
                tooltip.style.top    = (cellRect.bottom + 10) + 'px';
                tooltip.style.bottom = 'auto';
            } else {
                tooltip.classList.remove('tooltip-bottom');
                tooltip.style.bottom = (window.innerHeight - cellRect.top + 10) + 'px';
                tooltip.style.top    = 'auto';
            }
        });

        cell.addEventListener('mouseleave', function() {
            const tooltip = this.querySelector('.score-tooltip');
            if (tooltip) {
                tooltip.style.display = 'none';
            }
        });
    });
});
</script>

<style>
/* Page Header */
.page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 15px;
    padding: 30px;
    margin-bottom: 30px;
    box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
}

.page-title {
    color: white;
    font-size: 28px;
    font-weight: 700;
    margin: 0;
}

.header-actions {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
}

/* Buttons */
.btn {
    padding: 12px 24px;
    border: none;
    border-radius: 10px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    text-decoration: none;
    display: inline-block;
}

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

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

.btn-success {
    background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
    color: white;
    box-shadow: 0 4px 15px rgba(86, 171, 47, 0.3);
}

.btn-success:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(86, 171, 47, 0.4);
}

.btn-secondary {
    background: #95a5a6;
    color: white;
}

.btn-secondary:hover {
    background: #7f8c8d;
}

.btn-compact {
    padding: 10px 16px;
    min-width: 50px;
    font-size: 18px;
}

/* Quick Filters */
.quick-filters {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    justify-content: center;
}

.quick-filter-btn {
    padding: 8px 16px;
    border: 2px solid #e0e0e0;
    background: white;
    color: #2c3e50;
    text-decoration: none;
    border-radius: 25px;
    font-size: 13px;
    font-weight: 600;
    transition: all 0.3s;
    white-space: nowrap;
}

.quick-filter-btn:hover {
    border-color: #667eea;
    background: #f8f9fa;
    transform: translateY(-2px);
}

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

/* Filters */
.filters-container {
    background: #fff;
    border-radius: 12px;
    padding: 25px;
    margin-bottom: 30px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.filters-form {
    display: grid;
    grid-template-columns: 3fr auto;
    gap: 15px;
    align-items: end;
}

.filter-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 600;
    color: #2c3e50;
    font-size: 13px;
}

.form-control {
    width: 100%;
    padding: 10px 12px;
    border: 2px solid #e0e0e0;
    border-radius: 8px;
    font-size: 14px;
    transition: border-color 0.3s;
}

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

.date-range {
    display: flex;
    align-items: center;
    gap: 10px;
}

.date-range input {
    flex: 1;
}

.date-range span {
    color: #7f8c8d;
    font-weight: 600;
}

.filter-actions {
    display: flex;
    gap: 8px;
}

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

.stat-card {
    background: white;
    border-radius: 15px;
    padding: 25px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s, box-shadow 0.3s;
    border-left: 5px solid;
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    opacity: 0.1;
    transform: translate(30px, -30px);
}

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

.stat-card.blue {
    border-left-color: #3498db;
}

.stat-card.blue::before {
    background: #3498db;
}

.stat-card.green {
    border-left-color: #27ae60;
}

.stat-card.green::before {
    background: #27ae60;
}

.stat-card.orange {
    border-left-color: #e67e22;
}

.stat-card.orange::before {
    background: #e67e22;
}

.stat-card.purple {
    border-left-color: #9b59b6;
}

.stat-card.purple::before {
    background: #9b59b6;
}

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

.stat-value {
    font-size: 36px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 8px;
    line-height: 1;
}

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

.bonus-card {
    cursor: pointer;
}

.click-hint {
    margin-top: 10px;
    font-size: 11px;
    color: #7f8c8d;
    font-style: italic;
    text-align: center;
}

.bonus-card:hover .click-hint {
    color: #2c3e50;
}

/* Data Table */
.data-table-container {
    background: white;
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 30px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
    overflow: hidden;
}

.section-header {
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 2px solid #ecf0f1;
}

.section-title {
    font-size: 22px;
    font-weight: 700;
    color: #2c3e50;
    margin: 0 0 10px 0;
}

.section-subtitle {
    font-size: 14px;
    color: #7f8c8d;
    font-weight: 500;
}

.section-subtitle strong {
    color: #2c3e50;
    font-weight: 700;
}

/* Performance Table */
.table-scroll-wrapper {
    overflow-x: auto;
    margin: 0 -25px;
    padding: 0 25px;
    max-width: 100%;
}

.performance-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    font-size: 13px;
    white-space: nowrap;
    border-radius: 12px;
    overflow: hidden;
}

.performance-table thead th {
    padding: 10px 8px;
    text-align: center;
    font-weight: 600;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border: 1px solid #dee2e6;
    position: sticky;
    top: 0;
    z-index: 10;
}

.performance-table thead th:first-child {
    border-top-left-radius: 12px;
}

.performance-table thead tr:first-child th:last-child {
    border-top-right-radius: 12px;
}

.performance-table .group-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    font-size: 12px;
}

.performance-table .incoming-group {
    background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
    color: white;
}

.performance-table .outgoing-group {
    background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%);
    color: white;
}

.performance-table .support-group {
    background: linear-gradient(135deg, #16a085 0%, #1abc9c 100%);
    color: white;
}

.performance-table .sub-header {
    font-size: 11px;
    padding: 8px 6px;
}

.performance-table .package-col {
    /* Arka plan rengi inline olarak package type'a göre belirleniyor */
    color: white;
    min-width: 75px;
    max-width: 95px;
    font-weight: 600;
    font-size: 11px;
    line-height: 1.3;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
    padding: 8px 5px !important;
}

.performance-table .sticky-col {
    position: sticky;
    left: 0;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    z-index: 11;
    min-width: 130px;
    max-width: 160px;
    text-align: left !important;
}

.performance-table tbody tr {
    border-bottom: 1px solid #dee2e6;
    transition: all 0.2s;
}

.performance-table tbody tr:hover {
    background-color: #e3f2fd !important;
}

.performance-table tbody tr:hover td {
    background-color: #e3f2fd !important;
}

.performance-table tbody td {
    padding: 9px 7px;
    text-align: center;
    border: 1px solid #dee2e6;
}

.performance-table tbody tr:last-child td:first-child {
    border-bottom-left-radius: 12px;
}

.performance-table tbody tr:last-child td:last-child {
    border-bottom-right-radius: 12px;
}

.performance-table .personnel-name {
    font-weight: 600;
    background: white !important;
    color: #2c3e50 !important;
    text-align: left !important;
    padding-left: 15px !important;
    font-size: 13px;
}

.clickable-row {
    cursor: pointer;
}

/* Cell Colors */
.incoming-cell {
    background-color: rgba(52, 152, 219, 0.08);
    color: #2c3e50;
    max-width: 75px;
    font-size: 12px;
}

.outgoing-cell {
    background-color: rgba(155, 89, 182, 0.08);
    color: #2c3e50;
    max-width: 75px;
    font-size: 12px;
}

.support-cell {
    background-color: rgba(26, 188, 156, 0.08);
    color: #2c3e50;
    max-width: 75px;
    font-size: 12px;
    font-weight: 600;
}

.package-cell {
    font-weight: 600;
    font-size: 12px;
}

.package-zero {
    background-color: rgba(231, 76, 60, 0.15);
    color: #c0392b;
}

.package-low {
    background-color: rgba(241, 196, 15, 0.15);
    color: #d68910;
}

.package-medium {
    background-color: rgba(46, 204, 113, 0.15);
    color: #27ae60;
}

.package-high {
    background-color: rgba(46, 204, 113, 0.3);
    color: #1e8449;
    font-weight: 700;
}

/* Total Row */
.performance-table tfoot .total-row {
    background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
    color: white;
    font-weight: 700;
    font-size: 13px;
}

.performance-table tfoot td {
    padding: 10px 8px;
    text-align: center;
    border: 1px solid #1a252f;
    color: white !important;
}

.performance-table tfoot td strong {
    color: white !important;
}

.performance-table tfoot tr td:first-child {
    border-bottom-left-radius: 12px;
}

.performance-table tfoot tr td:last-child {
    border-bottom-right-radius: 12px;
}

.performance-table tfoot .sticky-col {
    background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
    z-index: 11;
}

/* Total row içindeki cell renkleri - override */
.performance-table tfoot .incoming-cell,
.performance-table tfoot .outgoing-cell,
.performance-table tfoot .support-cell,
.performance-table tfoot .package-cell {
    background-color: transparent !important;
    color: white !important;
}

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

.modal-content {
    background: white;
    border-radius: 15px;
    width: 98%;
    max-width: 1400px;
    max-height: 95vh;
    display: flex;
    flex-direction: column;
    box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
    animation: slideDown 0.3s ease;
    overflow: hidden;
}

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

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px;
    border-bottom: 2px solid #ecf0f1;
    flex-shrink: 0;
}

.modal-header h2 {
    margin: 0;
    color: #2c3e50;
    font-size: 22px;
}

.close {
    font-size: 32px;
    font-weight: bold;
    color: #95a5a6;
    cursor: pointer;
    transition: color 0.3s;
    line-height: 1;
}

.close:hover {
    color: #e74c3c;
}

.modal-body {
    padding: 25px 30px;
    overflow-y: auto;
    overflow-x: hidden;
    flex: 1;
    min-height: 0;
}

.modal-body::-webkit-scrollbar {
    width: 8px;
}

.modal-body::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

.modal-body::-webkit-scrollbar-thumb {
    background: #888;
    border-radius: 10px;
}

.modal-body::-webkit-scrollbar-thumb:hover {
    background: #555;
}

.loading {
    text-align: center;
    padding: 40px 20px;
    color: #7f8c8d;
    font-size: 16px;
}

.error {
    text-align: center;
    padding: 40px 20px;
    color: #e74c3c;
    font-size: 14px;
}

/* Bonus Details */
.bonus-details {
    padding: 0;
    width: 100%;
}

.bonus-stats-header {
    margin-bottom: 25px;
    padding: 20px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    border: 1px solid #dee2e6;
}

.bonus-stats-main {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
}

.bonus-stat-item {
    text-align: center;
}

.bonus-stat-label {
    display: block;
    font-size: 11px;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 8px;
    font-weight: 600;
}

.bonus-stat-big {
    display: block;
    font-size: 32px;
    color: #667eea;
    font-weight: 700;
    line-height: 1;
}

.bonus-stat-value {
    display: block;
    font-size: 24px;
    color: #2c3e50;
    font-weight: 600;
    line-height: 1;
}

/* Bonus Tabs */
.bonus-tabs {
    display: flex;
    gap: 10px;
    margin-bottom: 25px;
    border-bottom: 2px solid #ecf0f1;
}

.bonus-tab {
    padding: 12px 24px;
    background: transparent;
    border: none;
    border-bottom: 3px solid transparent;
    color: #7f8c8d;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s;
}

.bonus-tab:hover {
    color: #2c3e50;
    background: #f8f9fa;
}

.bonus-tab.active {
    color: #667eea;
    border-bottom-color: #667eea;
    background: #f8f9fa;
}

.bonus-tab-content {
    display: none;
}

.bonus-tab-content.active {
    display: block;
}

.bonus-section-title {
    font-size: 18px;
    font-weight: 700;
    color: #2c3e50;
    margin: 0 0 20px 0;
    padding-bottom: 12px;
    border-bottom: 2px solid #ecf0f1;
}

/* Bonus Detail Table */
.bonus-detail-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
    margin-bottom: 30px;
}

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

.bonus-detail-table thead th {
    padding: 12px;
    text-align: left;
    font-weight: 600;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.bonus-detail-table tbody tr {
    border-bottom: 1px solid #ecf0f1;
    transition: background-color 0.2s;
}

.bonus-detail-table tbody tr:hover {
    background-color: #f8f9fa;
}

.bonus-detail-table tbody td {
    padding: 12px;
    color: #2c3e50;
}

.criterion-badge {
    display: inline-block;
    padding: 4px 10px;
    background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
    color: white;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
    margin: 2px;
}

.package-badge {
    display: inline-block;
    padding: 6px 12px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 15px;
    font-size: 12px;
    font-weight: 600;
}

.badge-success {
    display: inline-block;
    padding: 4px 10px;
    background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
    color: white;
    border-radius: 12px;
    font-size: 11px;
    font-weight: 600;
}

.no-data {
    text-align: center;
    padding: 40px 20px;
    color: #95a5a6;
    font-size: 14px;
    font-style: italic;
}

/* Bonus Summary */
.bonus-summary {
    margin-top: 30px;
    padding: 25px;
    background: linear-gradient(135deg, #fff9e6 0%, #fff4d6 100%);
    border-radius: 12px;
    border: 2px solid #f39c12;
}

.bonus-calculation {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.calc-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
    background: white;
    border-radius: 8px;
    border-left: 4px solid #667eea;
}

.calc-row.calc-total {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-left: none;
    font-size: 18px;
    padding: 18px 15px;
    margin-top: 10px;
}

.calc-label {
    font-weight: 600;
    color: #2c3e50;
}

.calc-row.calc-total .calc-label {
    color: white;
}

.calc-value {
    font-size: 16px;
    color: #2c3e50;
}

.calc-row.calc-total .calc-value {
    color: white;
    font-size: 20px;
}

/* Performans Puanlama Tablosu Stilleri */
.package-score-header {
    background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%);
    color: white;
    font-weight: 700;
    font-size: 12px;
}

.bonus-score-header {
    background: linear-gradient(135deg, #16a085 0%, #1abc9c 100%);
    color: white;
    font-weight: 700;
    font-size: 12px;
}

.bonus-amount-header {
    background: linear-gradient(135deg, #27ae60 0%, #229954 100%);
    color: white;
    font-weight: 700;
    font-size: 12px;
}

.package-score-cell {
    background-color: rgba(155, 89, 182, 0.1);
    color: #2c3e50;
    font-weight: 600;
}

.bonus-score-cell {
    background-color: rgba(22, 160, 133, 0.1);
    color: #2c3e50;
    font-weight: 600;
}

.bonus-amount-cell {
    background-color: rgba(39, 174, 96, 0.1);
    color: #27ae60;
    font-weight: 700;
    font-size: 14px;
    position: relative;
}

.total-score-header {
    background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
    color: white;
    font-weight: 700;
    font-size: 12px;
}

.total-score-cell {
    background-color: rgba(243, 156, 18, 0.1);
    font-weight: 700;
    position: relative;
    color: #2c3e50;
    font-size: 14px;
}

.score-cell {
    text-align: center;
    vertical-align: middle;
}

.percentage-display {
    font-size: 10px;
    color: #7f8c8d;
    font-style: italic;
    font-weight: 500;
}

/* Performans Seviyesi Renkleri */
.score-excellent {
    background-color: rgba(39, 174, 96, 0.08) !important;
}

.score-excellent:hover {
    background-color: rgba(39, 174, 96, 0.15) !important;
}

.score-excellent td {
    background-color: rgba(39, 174, 96, 0.08) !important;
}

.score-excellent:hover td {
    background-color: rgba(39, 174, 96, 0.15) !important;
}

.score-good {
    background-color: rgba(52, 152, 219, 0.08) !important;
}

.score-good:hover {
    background-color: rgba(52, 152, 219, 0.15) !important;
}

.score-good td {
    background-color: rgba(52, 152, 219, 0.08) !important;
}

.score-good:hover td {
    background-color: rgba(52, 152, 219, 0.15) !important;
}

.score-average {
    background-color: rgba(241, 196, 15, 0.08) !important;
}

.score-average:hover {
    background-color: rgba(241, 196, 15, 0.15) !important;
}

.score-average td {
    background-color: rgba(241, 196, 15, 0.08) !important;
}

.score-average:hover td {
    background-color: rgba(241, 196, 15, 0.15) !important;
}

.score-low {
    background-color: rgba(231, 76, 60, 0.08) !important;
}

.score-low:hover {
    background-color: rgba(231, 76, 60, 0.15) !important;
}

.score-low td {
    background-color: rgba(231, 76, 60, 0.08) !important;
}

.score-low:hover td {
    background-color: rgba(231, 76, 60, 0.15) !important;
}

.manager-row {
    background-color: rgba(149, 165, 166, 0.15) !important;
    opacity: 0.7;
}

.manager-row:hover {
    background-color: rgba(149, 165, 166, 0.25) !important;
}

.manager-row td {
    background-color: rgba(149, 165, 166, 0.15) !important;
    color: #7f8c8d !important;
}

.manager-row:hover td {
    background-color: rgba(149, 165, 166, 0.25) !important;
}

/* Personel ismi sütunu her zaman beyaz kalmalı */
.manager-row .personnel-name {
    background: white !important;
    color: #7f8c8d !important;
}

.manager-row:hover .personnel-name {
    background: white !important;
}

/* Tooltip Styles for Package Details */
.has-tooltip {
    position: relative;
    cursor: help;
}

.info-icon {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 14px;
    opacity: 0.6;
    transition: opacity 0.3s;
}

.has-tooltip:hover .info-icon {
    opacity: 1;
}

.score-tooltip {
    display: none;
    position: fixed;
    background: white;
    border: 2px solid #667eea;
    border-radius: 10px;
    padding: 15px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    z-index: 10000;
    width: 380px;
    max-width: 90vw;
    max-height: 80vh;
    overflow-y: auto;
    overflow-x: hidden;
    pointer-events: none;
    word-wrap: break-word;
    word-break: break-word;
}

/* Tooltip visibility controlled by JavaScript */

/* Tooltip arrow - yukarı açıldığında (varsayılan) */
.score-tooltip::before {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    border: 8px solid transparent;
    border-top-color: #667eea;
}

.score-tooltip::after {
    content: '';
    position: absolute;
    top: 100%;
    left: 50%;
    transform: translateX(-50%);
    border: 6px solid transparent;
    border-top-color: white;
    margin-top: -2px;
}

/* Tooltip aşağı açıldığında */
.score-tooltip.tooltip-bottom::before {
    top: auto;
    bottom: 100%;
    border-top-color: transparent;
    border-bottom-color: #667eea;
}

.score-tooltip.tooltip-bottom::after {
    top: auto;
    bottom: 100%;
    border-top-color: transparent;
    border-bottom-color: white;
    margin-top: 0;
    margin-bottom: -2px;
}

.tooltip-header {
    font-weight: 700;
    font-size: 14px;
    color: #667eea;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 2px solid #ecf0f1;
}

.tooltip-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    margin-bottom: 10px;
    table-layout: auto;
}

.tooltip-table th {
    background: #f8f9fa;
    padding: 6px 8px;
    text-align: left;
    font-weight: 600;
    color: #2c3e50;
    border-bottom: 2px solid #dee2e6;
    white-space: nowrap;
}

.tooltip-table th:first-child {
    width: 55%;
    white-space: normal;
}

.tooltip-table td {
    padding: 6px 8px;
    border-bottom: 1px solid #ecf0f1;
    color: #2c3e50;
    white-space: nowrap;
    text-align: center;
}

.tooltip-table td:first-child {
    text-align: left;
    white-space: normal;
    word-break: break-word;
}

.tooltip-table tr:last-child td {
    border-bottom: none;
}

.tooltip-table .tooltip-total {
    background: #f8f9fa;
    font-weight: 600;
    border-top: 2px solid #667eea;
}

.tooltip-formula {
    background: #fff9e6;
    padding: 10px;
    border-radius: 6px;
    font-size: 11px;
    color: #2c3e50;
    border-left: 3px solid #f39c12;
    word-wrap: break-word;
    word-break: break-word;
    overflow-wrap: break-word;
    max-width: 100%;
    line-height: 1.5;
}

.tooltip-formula strong {
    color: #f39c12;
}

.tooltip-empty {
    text-align: center;
    color: #95a5a6;
    font-style: italic;
    padding: 20px 10px;
    margin: 0;
}

.score-tooltip small {
    word-wrap: break-word;
    word-break: break-word;
    overflow-wrap: break-word;
    display: inline-block;
    max-width: 100%;
    line-height: 1.4;
}

/* Tooltip scrollbar stilleri */
.score-tooltip::-webkit-scrollbar {
    width: 6px;
}

.score-tooltip::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

.score-tooltip::-webkit-scrollbar-thumb {
    background: #667eea;
    border-radius: 10px;
}

.score-tooltip::-webkit-scrollbar-thumb:hover {
    background: #5568d3;
}

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

    .filter-actions {
        flex-direction: row;
    }

    .stats-overview {
        grid-template-columns: 1fr;
    }

    .header-content {
        flex-direction: column;
        align-items: flex-start;
    }

    table {
        font-size: 12px;
    }

    thead th, tbody td {
        padding: 10px 8px;
    }

    .bonus-stats-main {
        grid-template-columns: repeat(2, 1fr);
    }

    .bonus-tabs {
        flex-direction: column;
        gap: 5px;
    }

    .bonus-tab {
        padding: 10px 15px;
        font-size: 13px;
    }

    .calc-row {
        flex-direction: column;
        align-items: flex-start;
        gap: 8px;
    }

    .modal-content {
        width: 100%;
        max-width: 100%;
    }

    .performance-table {
        font-size: 11px;
    }

    .performance-table thead th {
        padding: 8px 5px;
        font-size: 9px;
    }

    .performance-table tbody td {
        padding: 8px 5px;
    }

    .performance-table .sticky-col {
        min-width: 120px;
    }
}

@media print {
    .header-actions, .filters-container, .quick-filters, .click-hint {
        display: none !important;
    }

    .stat-card {
        break-inside: avoid;
    }
}
</style>

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