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

Auth::requireLogin();

$db = new Database();

// Manuel kayıt ekleme
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_record') {
    try {
        $companyId = trim($_POST['company_id'] ?? '');
        $companyName = trim($_POST['company_name'] ?? '');
        $salesSource = trim($_POST['sales_source'] ?? '');
        $supportRep = trim($_POST['support_representative'] ?? '');
        $trainingDate = trim($_POST['training_completion_date'] ?? '');
        $salesType = trim($_POST['sales_type'] ?? '');
        $packageType = trim($_POST['package_type'] ?? '');

        // Zorunlu alan kontrolü
        if (empty($companyId)) {
            throw new Exception('Firma ID boş olamaz');
        }
        if (empty($companyName)) {
            throw new Exception('Firma Adı boş olamaz');
        }
        if (empty($salesType)) {
            throw new Exception('Satış Tipi boş olamaz');
        }
        if (empty($packageType)) {
            throw new Exception('Paket Türü boş olamaz');
        }

        // Tarihi düzenle (boş olabilir)
        $formattedDate = null;
        if (!empty($trainingDate)) {
            $formattedDate = date('Y-m-d', strtotime($trainingDate));
        }

        // Aynı firma ID + satış tipi + paket türü kombinasyonu var mı kontrol et
        // Aynı firma farklı paketler alabilir, ama aynı paketi tekrar alamaz
        $existing = $db->fetchOne(
            "SELECT id FROM training_completion
             WHERE company_id = ? AND sales_type = ? AND package_type = ?",
            [$companyId, $salesType, $packageType]
        );

        if ($existing) {
            throw new Exception('Bu Firma ID, Satış Tipi ve Paket Türü kombinasyonu zaten kayıtlı. Aynı firma farklı paket alabilir.');
        }

        // Yeni kayıt ekle
        $db->query(
            "INSERT INTO training_completion
                (company_id, company_name, sales_source, support_representative,
                 training_completion_date, sales_type, package_type)
            VALUES (?, ?, ?, ?, ?, ?, ?)",
            [
                $companyId,
                $companyName,
                $salesSource,
                $supportRep,
                $formattedDate,
                $salesType,
                $packageType
            ]
        );

        $message = 'Kayıt başarıyla eklendi!';
        $messageType = 'success';

        // Sayfayı yenile (POST verilerini temizlemek için)
        header("Location: training_completion.php?success=1");
        exit;

    } catch (Exception $e) {
        $message = 'Hata: ' . $e->getMessage();
        $messageType = 'error';
    }
}

$pageTitle = 'Eğitim Tamamlama ve ERP Kurulum Takip';
include 'includes/header.php';

// Başarı mesajı kontrolü
if (isset($_GET['success']) && $_GET['success'] == '1') {
    $message = 'Kayıt başarıyla eklendi!';
    $messageType = 'success';
}

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

// Diğer filtreler
$selectedSalesType = $_GET['sales_type'] ?? '';
$selectedRep = $_GET['representative'] ?? '';
$searchQuery = $_GET['search'] ?? '';

// Paket kriterlerini çek
$packageCriteria = $db->fetchAll("
    SELECT name, code 
    FROM criteria 
    WHERE category = 'Paket Kriterleri' AND is_active = 1 
    ORDER BY display_order ASC, name ASC
");

// Personel bazında istatistikler (stats-overview için)
$personalStats = $db->fetchAll("
    SELECT
        support_representative,
        COUNT(*) as total_trainings,
        COUNT(DISTINCT company_id) as unique_companies
    FROM training_completion
    WHERE support_representative IS NOT NULL 
        AND support_representative != ''
        AND training_completion_date IS NOT NULL
        AND training_completion_date BETWEEN ? AND ?
    GROUP BY support_representative
    ORDER BY total_trainings DESC
", [$startDate, $endDate]);

// Dinamik SQL oluştur - Her paket kriteri için SUM ekle
$packageSumCases = [];
foreach ($packageCriteria as $pkg) {
    $code = $pkg['code'];
    $name = $pkg['name'];
    $packageSumCases[] = "SUM(CASE WHEN package_type = '{$name}' THEN 1 ELSE 0 END) as {$code}";
}
$packageSumSQL = !empty($packageSumCases) ? ', ' . implode(', ', $packageSumCases) : '';

// Destek temsilcilerine göre istatistikler
$repStatsSQL = "
    SELECT
        support_representative,
        COUNT(CASE WHEN training_completion_date IS NOT NULL THEN 1 END) as completed_count
        {$packageSumSQL}
    FROM training_completion
    WHERE support_representative IS NOT NULL AND support_representative != ''
        AND training_completion_date IS NOT NULL
        AND training_completion_date BETWEEN ? AND ?
    GROUP BY support_representative
    ORDER BY completed_count DESC
    LIMIT 10
";

$repStats = $db->fetchAll($repStatsSQL, [$startDate, $endDate]);

// Tüm kayıtlar (filtreleme ile)
$whereClauses = [];
$params = [];

if (!empty($searchQuery)) {
    $whereClauses[] = "(company_id LIKE ? OR company_name LIKE ? OR support_representative LIKE ?)";
    $searchParam = "%$searchQuery%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

if (!empty($selectedSalesType)) {
    $whereClauses[] = "sales_type = ?";
    $params[] = $selectedSalesType;
}

if (!empty($selectedRep)) {
    $whereClauses[] = "support_representative = ?";
    $params[] = $selectedRep;
}

if ($startDate && $endDate) {
    $whereClauses[] = "(training_completion_date BETWEEN ? AND ? OR training_completion_date IS NULL)";
    $params[] = $startDate;
    $params[] = $endDate;
}

$whereSQL = !empty($whereClauses) ? 'WHERE ' . implode(' AND ', $whereClauses) : '';

$allRecords = $db->fetchAll("
    SELECT
        id,
        company_id,
        company_name,
        sales_source,
        support_representative,
        training_completion_date,
        sales_type,
        package_type,
        created_at
    FROM training_completion
    $whereSQL
    ORDER BY
        CASE WHEN training_completion_date IS NULL THEN 0 ELSE 1 END,
        training_completion_date DESC,
        created_at DESC
", $params);

// Benzersiz değerleri al (filtre için)
$allSalesTypes = $db->fetchAll("SELECT DISTINCT sales_type FROM training_completion WHERE sales_type IS NOT NULL AND sales_type != '' ORDER BY sales_type");
$allReps = $db->fetchAll("SELECT DISTINCT support_representative FROM training_completion WHERE support_representative IS NOT NULL AND support_representative != '' ORDER BY support_representative");

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

// Grafik verileri için hazırlık
// 1. Personel bazlı tamamlanan eğitimler (ilk 10)
$chartPersonnelData = $db->fetchAll("
    SELECT
        support_representative,
        COUNT(*) as total_trainings
    FROM training_completion
    WHERE support_representative IS NOT NULL 
        AND support_representative != ''
        AND training_completion_date IS NOT NULL
        AND training_completion_date BETWEEN ? AND ?
    GROUP BY support_representative
    ORDER BY total_trainings DESC
    LIMIT 10
", [$startDate, $endDate]);

// 2. Paket türü dağılımı
$chartPackageData = $db->fetchAll("
    SELECT
        package_type,
        COUNT(*) as count
    FROM training_completion
    WHERE package_type IS NOT NULL 
        AND package_type != ''
        AND training_completion_date IS NOT NULL
        AND training_completion_date BETWEEN ? AND ?
    GROUP BY package_type
    ORDER BY count DESC
", [$startDate, $endDate]);

// 3. Satış kaynağı dağılımı
$chartSalesSourceData = $db->fetchAll("
    SELECT
        sales_source,
        COUNT(*) as count
    FROM training_completion
    WHERE sales_source IS NOT NULL 
        AND sales_source != ''
        AND training_completion_date IS NOT NULL
        AND training_completion_date BETWEEN ? AND ?
    GROUP BY sales_source
    ORDER BY count DESC
    LIMIT 10
", [$startDate, $endDate]);

?>

<div class="page-header">
    <div class="header-content">
        <h1 class="page-title">📚 Eğitim Tamamlama ve ERP Kurulum Takip</h1>
        <?php if (Auth::isAdmin()): ?>
        <div class="header-actions">
            <button onclick="openAddModal()" class="btn btn-primary">➕ Yeni Kayıt</button>
            <a href="upload_training.php" class="btn btn-primary">📤 Veri Yükle</a>
            <a href="download_training_template.php" class="btn btn-success">📥 Şablon İndir</a>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<!-- Hızlı Filtreler (Ay Bazlı) -->
<div class="filters-container">
    <div class="quick-filters">
        <?php foreach ($months as $month): ?>
            <?php
                // Eğer hiç quick filter seçilmemişse ve bu ay ise aktif yap
                $isActive = $quickFilter === "month_{$month['offset']}" || (!$quickFilter && $month['offset'] === 0);
            ?>
            <a href="?quick_filter=month_<?php echo $month['offset']; ?><?php echo $selectedSalesType ? '&sales_type='.$selectedSalesType : ''; ?><?php echo $selectedRep ? '&representative='.$selectedRep : ''; ?><?php echo $searchQuery ? '&search='.urlencode($searchQuery) : ''; ?>"
               class="quick-filter-btn <?php echo $isActive ? 'active' : ''; ?>">
                <?php echo $month['short']; ?>
            </a>
        <?php endforeach; ?>
    </div>
</div>

<!-- Filtreler -->
<div class="filters-container">
    <form method="GET" class="filters-form">
        <div class="filter-group filter-date-range">
            <label>Tarih Aralığı</label>
            <div class="date-range">
                <input type="date" name="start_date" value="<?php echo $startDate; ?>" class="form-control">
                <span>-</span>
                <input type="date" name="end_date" value="<?php echo $endDate; ?>" class="form-control">
            </div>
        </div>

        <div class="filter-group">
            <label>Satış Tipi</label>
            <select name="sales_type" class="form-control">
                <option value="">Tümü</option>
                <?php foreach ($allSalesTypes as $st): ?>
                    <option value="<?php echo htmlspecialchars($st['sales_type']); ?>"
                            <?php echo $selectedSalesType === $st['sales_type'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($st['sales_type']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="filter-group">
            <label>Destek Temsilcisi</label>
            <select name="representative" class="form-control">
                <option value="">Tümü</option>
                <?php foreach ($allReps as $rep): ?>
                    <option value="<?php echo htmlspecialchars($rep['support_representative']); ?>"
                            <?php echo $selectedRep === $rep['support_representative'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($rep['support_representative']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="filter-group filter-search">
            <label>Arama</label>
            <input type="text" name="search" value="<?php echo htmlspecialchars($searchQuery); ?>"
                   placeholder="Firma ID, Adı veya Temsilci..." class="form-control">
        </div>

        <div class="filter-actions">
            <button type="submit" class="btn btn-primary btn-compact">🔍</button>
            <a href="training_completion.php" class="btn btn-secondary btn-compact">🔄</a>
        </div>
    </form>
</div>

<!-- Personel Bazında İstatistikler -->
<div class="stats-overview">
    <?php if (empty($personalStats)): ?>
        <div class="stat-card blue" style="grid-column: 1 / -1; text-align: center;">
            <div class="stat-label">Bilgi</div>
            <div class="stat-subtitle">Seçili dönemde tamamlanmış eğitim bulunamadı</div>
        </div>
    <?php else: ?>
        <?php 
        $colors = ['blue', 'green', 'purple', 'orange'];
        foreach ($personalStats as $index => $stat): 
            $colorClass = $colors[$index % count($colors)];
        ?>
            <div class="stat-card <?php echo $colorClass; ?> personnel-card" 
                 onclick="showPersonnelDetails('<?php echo htmlspecialchars($stat['support_representative'], ENT_QUOTES); ?>', '<?php echo $startDate; ?>', '<?php echo $endDate; ?>')">
                <div class="stat-label">👤 <?php echo htmlspecialchars($stat['support_representative']); ?></div>
                <div class="stat-value"><?php echo number_format($stat['total_trainings']); ?></div>
                <div class="stat-subtitle">
                    <?php echo number_format($stat['unique_companies']); ?> firma · 
                    <?php echo date('d.m', strtotime($startDate)) . ' - ' . date('d.m', strtotime($endDate)); ?>
                </div>
                <div class="click-hint">Detaylar için tıklayın</div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>


<!-- Destek Temsilcisi Performansı -->
<div class="data-table-container">
    <div class="section-header">
        <h2 class="section-title">👥 Destek Temsilcisi Performansı</h2>
    </div>
    <table>
        <thead>
            <tr>
                <th>Sıra</th>
                <th>Destek Temsilcisi</th>
                <th>Tamamlanan</th>
                <?php foreach ($packageCriteria as $pkg): ?>
                    <th><?php echo htmlspecialchars($pkg['name']); ?></th>
                <?php endforeach; ?>
            </tr>
        </thead>
        <tbody>
            <?php
            // Her paket türü için sütun bazında değerleri topla (dikey renklendirme için)
            $columnValues = [];
            foreach ($packageCriteria as $pkg) {
                $columnValues[$pkg['code']] = [];
                foreach ($repStats as $rep) {
                    $value = isset($rep[$pkg['code']]) ? (int)$rep[$pkg['code']] : 0;
                    if ($value > 0) {
                        $columnValues[$pkg['code']][] = $value;
                    }
                }
            }
            
            // Her sütun için renk seviyelerini hesapla
            $columnColorLevels = [];
            foreach ($packageCriteria as $pkg) {
                $values = $columnValues[$pkg['code']];
                if (!empty($values)) {
                    $uniqueValues = array_unique($values);
                    rsort($uniqueValues);
                    
                    $levels = [];
                    foreach ($uniqueValues as $levelIndex => $val) {
                        $levels[$val] = $levelIndex;
                    }
                    $columnColorLevels[$pkg['code']] = [
                        'levels' => $levels,
                        'total' => count($levels)
                    ];
                }
            }
            
            // Pastel renk fonksiyonu
            function getColumnColor($value, $levelInfo) {
                if ($value == 0) return 'rgba(248, 249, 250, 0.5)'; // Çok açık gri
                
                if (!isset($levelInfo['levels'][$value])) {
                    return 'rgba(224, 224, 224, 0.3)';
                }
                
                $level = $levelInfo['levels'][$value];
                $totalLevels = $levelInfo['total'];
                
                if ($totalLevels == 1) {
                    return 'rgba(134, 239, 172, 0.5)'; // Pastel yeşil
                }
                
                // Pastel renk gradyanı: Yeşil -> Açık Yeşil -> Sarı -> Turuncu
                $ratio = $level / ($totalLevels - 1);
                
                if ($ratio <= 0.25) {
                    return 'rgba(134, 239, 172, 0.6)'; // Pastel koyu yeşil - en yüksek
                } elseif ($ratio <= 0.5) {
                    return 'rgba(187, 247, 208, 0.5)'; // Pastel açık yeşil
                } elseif ($ratio <= 0.75) {
                    return 'rgba(254, 240, 138, 0.5)'; // Pastel sarı
                } else {
                    return 'rgba(254, 202, 202, 0.5)'; // Pastel turuncu/kırmızı - en düşük
                }
            }
            ?>
            <?php foreach ($repStats as $index => $rep): ?>
                <tr class="clickable-row" onclick="showPersonnelDetails('<?php echo htmlspecialchars($rep['support_representative'], ENT_QUOTES); ?>', '<?php echo $startDate; ?>', '<?php echo $endDate; ?>')">
                    <td><strong><?php echo $index + 1; ?></strong></td>
                    <td><strong><?php echo htmlspecialchars($rep['support_representative']); ?></strong></td>
                    <td style="color: #27ae60;"><strong><?php echo number_format($rep['completed_count']); ?></strong></td>
                    <?php foreach ($packageCriteria as $pkg): ?>
                        <?php
                            $value = isset($rep[$pkg['code']]) ? (int)$rep[$pkg['code']] : 0;
                            $levelInfo = $columnColorLevels[$pkg['code']] ?? null;
                            $bgColor = $levelInfo ? getColumnColor($value, $levelInfo) : 'rgba(248, 249, 250, 0.5)';
                            $textColor = ($value == 0) ? '#999' : '#2c3e50';
                            $fontWeight = ($value > 0) ? 'bold' : 'normal';
                        ?>
                        <td style="background-color: <?php echo $bgColor; ?>; color: <?php echo $textColor; ?>; font-weight: <?php echo $fontWeight; ?>;">
                            <?php echo $value > 0 ? number_format($value) : '-'; ?>
                        </td>
                    <?php endforeach; ?>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- İstatistik Grafikleri -->
<div class="data-table-container">
    <div class="section-header">
        <h2 class="section-title">📊 İstatistik Grafikleri</h2>
    </div>
    
    <div class="charts-grid">
        <!-- Personel Bazlı Tamamlanan Eğitimler -->
        <div class="chart-container">
            <h3 class="chart-title">👥 Personel Bazlı Tamamlanan Eğitimler</h3>
            <canvas id="personnelChart"></canvas>
        </div>
        
        <!-- Paket Türü Dağılımı -->
        <div class="chart-container">
            <h3 class="chart-title">📦 Paket Türü Dağılımı</h3>
            <canvas id="packageChart"></canvas>
        </div>
        
        <!-- Satış Kaynağı Dağılımı -->
        <div class="chart-container">
            <h3 class="chart-title">🎯 Satış Kaynağı Dağılımı</h3>
            <canvas id="salesSourceChart"></canvas>
        </div>
    </div>
</div>

<!-- Tüm Kayıtlar -->
<div class="data-table-container">
    <div class="section-header">
        <h2 class="section-title">📋 Tüm Kayıtlar</h2>
    </div>
    
    <?php
    // Paket türlerine göre gruplandırma
    $allRecordsPackageStats = [];
    foreach ($allRecords as $record) {
        $pkg = $record['package_type'] ?? 'Diğer';
        if (!isset($allRecordsPackageStats[$pkg])) {
            $allRecordsPackageStats[$pkg] = 0;
        }
        $allRecordsPackageStats[$pkg]++;
    }
    
    // Paket türlerini sayıya göre sırala
    arsort($allRecordsPackageStats);
    ?>
    
    <div class="records-filter-header">
        <div class="records-filter-buttons">
            <button class="record-filter-btn active" data-package="" style="background-color: rgba(149, 165, 166, 0.3);">
                <span class="filter-label">Tümü</span>
                <span class="filter-count"><?php echo count($allRecords); ?></span>
            </button>
            <?php foreach ($allRecordsPackageStats as $pkg => $count): ?>
                <button class="record-filter-btn" data-package="<?php echo htmlspecialchars($pkg); ?>" style="background-color: <?php echo getPackageTypeColor($pkg); ?>;">
                    <span class="filter-label"><?php echo htmlspecialchars($pkg); ?></span>
                    <span class="filter-count"><?php echo $count; ?></span>
                </button>
            <?php endforeach; ?>
        </div>
    </div>
    
    <div id="recordsTableWrapper">
    <table id="recordsTable">
        <thead>
            <tr>
                <th>Firma ID</th>
                <th>Firma Adı</th>
                <th>Satış Kaynağı</th>
                <th>Destek Temsilcisi</th>
                <th>Eğitim Tarihi</th>
                <th>Satış Tipi</th>
                <th>Paket Türü</th>
            </tr>
        </thead>
        <tbody>
            <?php
            // Benzersiz satış kaynaklarını topla ve renkler ata
            $uniqueSources = [];
            $uniqueReps = [];
            foreach ($allRecords as $record) {
                if (!empty($record['sales_source']) && !isset($uniqueSources[$record['sales_source']])) {
                    $uniqueSources[$record['sales_source']] = true;
                }
                if (!empty($record['support_representative']) && !isset($uniqueReps[$record['support_representative']])) {
                    $uniqueReps[$record['support_representative']] = true;
                }
            }
            
            // Pastel renkler paleti
            $pastelColors = [
                'rgba(134, 239, 172, 0.4)', // Pastel yeşil
                'rgba(147, 197, 253, 0.4)', // Pastel mavi
                'rgba(216, 180, 254, 0.4)', // Pastel mor
                'rgba(251, 207, 232, 0.4)', // Pastel pembe
                'rgba(253, 224, 71, 0.4)',  // Pastel sarı
                'rgba(253, 186, 116, 0.4)', // Pastel turuncu
                'rgba(165, 243, 252, 0.4)', // Pastel turkuaz
                'rgba(196, 181, 253, 0.4)', // Pastel lavanta
            ];
            
            // Her satış kaynağına renk ata
            $sourceColors = [];
            $colorIndex = 0;
            foreach (array_keys($uniqueSources) as $source) {
                $sourceColors[$source] = $pastelColors[$colorIndex % count($pastelColors)];
                $colorIndex++;
            }
            
            // Her destek temsilcisine renk ata
            $repColors = [];
            $colorIndex = 0;
            foreach (array_keys($uniqueReps) as $rep) {
                $repColors[$rep] = $pastelColors[$colorIndex % count($pastelColors)];
                $colorIndex++;
            }
            
            // Satış tipi renkleri
            function getSalesTypeColor($salesType) {
                if (empty($salesType)) return 'rgba(229, 231, 235, 0.4)';
                
                $type = strtolower($salesType);
                if (strpos($type, 'yeni') !== false && strpos($type, 'satış') !== false) {
                    return 'rgba(134, 239, 172, 0.5)'; // Yeşil - Yeni Satış
                } elseif (strpos($type, 'yenileme') !== false || strpos($type, 'lisans') !== false) {
                    return 'rgba(147, 197, 253, 0.5)'; // Mavi - Lisans Yenileme
                }
                return 'rgba(216, 180, 254, 0.4)'; // Mor - Diğer
            }
            
            // Paket türü renkleri
            function getPackageTypeColor($packageType) {
                if (empty($packageType)) return 'rgba(229, 231, 235, 0.4)';

                $pkg = strtolower($packageType);

                // SOPYO PAKETLERİ - Lacivert/Mavi Soft Tonlar
                if (strpos($pkg, 'profesyonel') !== false && strpos($pkg, 'ideasoft') === false) {
                    return 'rgba(123, 159, 209, 0.6)'; // Soft mavi #7B9FD1
                } elseif (strpos($pkg, 'gelişmiş') !== false) {
                    return 'rgba(107, 142, 199, 0.6)'; // Orta mavi #6B8EC7
                } elseif (strpos($pkg, 'uzman') !== false) {
                    return 'rgba(90, 125, 184, 0.6)'; // Lacivert #5A7DB8
                }

                // IDEASOFT PAKETLERİ - Turkuaz/Yeşil-Mavi Tonları
                elseif (strpos($pkg, 'ideasoft erp') !== false) {
                    return 'rgba(0, 184, 169, 0.5)'; // Turkuaz #00B8A9
                } elseif (strpos($pkg, 'ideasoft mini 2') !== false) {
                    return 'rgba(31, 200, 184, 0.5)'; // Açık turkuaz #1FC8B8
                } elseif (strpos($pkg, 'ideasoft mini 3') !== false) {
                    return 'rgba(61, 212, 196, 0.5)'; // Daha açık turkuaz #3DD4C4
                } elseif (strpos($pkg, 'ideasoft maksi') !== false || strpos($pkg, 'maksi') !== false) {
                    return 'rgba(0, 168, 157, 0.5)'; // Koyu turkuaz #00A89D
                } elseif (strpos($pkg, 'ideasoft') !== false) {
                    return 'rgba(0, 184, 169, 0.5)'; // Genel Ideasoft - Turkuaz
                }

                // SOPYO ERP/MUHASEBE - Soft Mor/Eflatun
                elseif (strpos($pkg, 'sopyo logo') !== false) {
                    return 'rgba(167, 141, 194, 0.5)'; // Soft mor #A78DC2
                } elseif (strpos($pkg, 'nebim') !== false) {
                    return 'rgba(184, 159, 209, 0.5)'; // Açık eflatun #B89FD1
                } elseif (strpos($pkg, 'sopyo') !== false) {
                    return 'rgba(175, 150, 201, 0.5)'; // Genel Sopyo ERP
                }

                // LİSANS YENİLEME - Altın/Turuncu (Bonus)
                elseif (strpos($pkg, 'lisans') !== false || strpos($pkg, 'yenileme') !== false) {
                    return 'rgba(232, 160, 93, 0.6)'; // Soft turuncu-altın #E8A05D
                }

                return 'rgba(196, 181, 253, 0.4)'; // Lavanta - Diğer
            }
            ?>
            <?php foreach ($allRecords as $record): ?>
                <tr class="record-row" data-package="<?php echo htmlspecialchars($record['package_type'] ?? ''); ?>">
                    <td><strong><?php echo htmlspecialchars($record['company_id']); ?></strong></td>
                    <td><?php echo htmlspecialchars($record['company_name']); ?></td>
                    <td>
                        <?php if (!empty($record['sales_source'])): ?>
                            <span class="colored-badge" style="background-color: <?php echo $sourceColors[$record['sales_source']]; ?>; color: #2c3e50;">
                                <?php echo htmlspecialchars($record['sales_source']); ?>
                            </span>
                        <?php else: ?>
                            <span style="color: #999;">-</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($record['support_representative'])): ?>
                            <span class="colored-badge" style="background-color: <?php echo $repColors[$record['support_representative']]; ?>; color: #2c3e50;">
                                <?php echo htmlspecialchars($record['support_representative']); ?>
                            </span>
                        <?php else: ?>
                            <span style="color: #999;">-</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php
                            if ($record['training_completion_date']) {
                                echo date('d.m.Y', strtotime($record['training_completion_date']));
                            } else {
                                echo '<span style="color: #e74c3c;">Bekliyor</span>';
                            }
                        ?>
                    </td>
                    <td>
                        <?php if (!empty($record['sales_type'])): ?>
                            <span class="colored-badge" style="background-color: <?php echo getSalesTypeColor($record['sales_type']); ?>; color: #2c3e50;">
                                <?php echo htmlspecialchars($record['sales_type']); ?>
                            </span>
                        <?php else: ?>
                            <span style="color: #999;">-</span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if (!empty($record['package_type'])): ?>
                            <span class="colored-badge" style="background-color: <?php echo getPackageTypeColor($record['package_type']); ?>; color: #2c3e50;">
                                <?php echo htmlspecialchars($record['package_type']); ?>
                            </span>
                        <?php else: ?>
                            <span style="color: #999;">-</span>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
    </div>
    
    <div id="recordsPagination" class="pagination">
        <div class="pagination-info"></div>
        <div class="pagination-controls"></div>
    </div>
</div>

<!-- Eğitim Detay Modal -->
<div id="trainingDetailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="trainingDetailModalTitle">Eğitim Detayı</h2>
            <span class="close" onclick="closeTrainingDetailModal()">×</span>
        </div>
        <div id="trainingDetailModalContent" class="modal-body">
            <div class="loading">Yükleniyor...</div>
        </div>
    </div>
</div>

<!-- Personel Detay Modal -->
<div id="personnelModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 id="personnelModalTitle">Personel Eğitimleri</h2>
            <span class="close" onclick="closePersonnelModal()">×</span>
        </div>
        <div id="personnelModalContent" class="modal-body">
            <div class="loading">Yükleniyor...</div>
        </div>
    </div>
</div>

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

<!-- Manuel Kayıt Ekleme Modal -->
<div id="addModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>➕ Yeni Eğitim Kaydı Ekle</h2>
            <span class="close" onclick="closeAddModal()">×</span>
        </div>
        <form method="POST" class="add-form">
            <input type="hidden" name="action" value="add_record">

            <div class="form-row">
                <div class="form-group">
                    <label for="company_id">Firma ID <span class="required">*</span></label>
                    <input type="text" name="company_id" id="company_id" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="company_name">Firma Adı <span class="required">*</span></label>
                    <input type="text" name="company_name" id="company_name" class="form-control" required>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="sales_source">Satış Kaynağı</label>
                    <input type="text" name="sales_source" id="sales_source" class="form-control">
                </div>
                <div class="form-group">
                    <label for="support_representative">Destek Temsilcisi</label>
                    <input type="text" name="support_representative" id="support_representative" class="form-control">
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="sales_type">Satış Tipi <span class="required">*</span></label>
                    <select name="sales_type" id="sales_type" class="form-control" required>
                        <option value="">Seçiniz...</option>
                        <option value="Yeni Satış">Yeni Satış</option>
                        <option value="Lisans Yenileme">Lisans Yenileme</option>
                        <option value="Google Yorum">Google Yorum</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="package_type">Paket Türü <span class="required">*</span></label>
                    <select name="package_type" id="package_type" class="form-control" required>
                        <option value="">Seçiniz...</option>
                        <?php foreach ($packageCriteria as $pkg): ?>
                            <option value="<?php echo htmlspecialchars($pkg['name']); ?>">
                                <?php echo htmlspecialchars($pkg['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group">
                    <label for="training_completion_date">Eğitim Tamamlanma Tarihi</label>
                    <input type="date" name="training_completion_date" id="training_completion_date" class="form-control">
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn btn-primary">💾 Kaydet</button>
                <button type="button" class="btn btn-secondary" onclick="closeAddModal()">❌ İptal</button>
            </div>
        </form>
    </div>
</div>

<script>
// Global değişkenler
let currentPage = 1;
const itemsPerPage = 10;
let allTrainings = [];
let filterPackage = ''; // Aktif paket filtresi

// Global değişkenler için tarihleri sakla
let currentStartDate = '';
let currentEndDate = '';

// Personel detaylarını göster
async function showPersonnelDetails(representative, startDate, endDate) {
    const modal = document.getElementById('personnelModal');
    const title = document.getElementById('personnelModalTitle');
    const content = document.getElementById('personnelModalContent');

    // Modal'ı aç ve yükleme göster
    modal.style.display = 'flex';
    title.textContent = '👤 ' + representative + ' - Eğitim Detayları';
    content.innerHTML = '<div class="loading">Yükleniyor...</div>';

    // Sayfa numarasını sıfırla, tarihleri sakla ve filtreyi temizle
    currentPage = 1;
    currentStartDate = startDate;
    currentEndDate = endDate;
    filterPackage = ''; // Filtreyi temizle

    try {
        // AJAX ile personel detaylarını al
        const response = await fetch('get_personnel_trainings.php?representative=' + encodeURIComponent(representative) + '&start_date=' + startDate + '&end_date=' + endDate);
        const data = await response.json();

        if (data.success && data.trainings.length > 0) {
            allTrainings = data.trainings;
            renderPersonnelDetails(data, startDate, endDate);
        } else {
            content.innerHTML = '<div class="no-data">Bu dönemde eğitim kaydı bulunamadı.</div>';
        }
    } catch (error) {
        content.innerHTML = '<div class="error">Veriler yüklenirken bir hata oluştu.</div>';
    }
}

// Personel detaylarını render et
function renderPersonnelDetails(data, startDate, endDate) {
    const content = document.getElementById('personnelModalContent');

    // Paket filtresini uygula
    const filteredTrainings = filterPackage
        ? allTrainings.filter(t => t.package_type === filterPackage)
        : allTrainings;

    const totalPages = Math.ceil(filteredTrainings.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const endIndex = startIndex + itemsPerPage;
    const currentTrainings = filteredTrainings.slice(startIndex, endIndex);

    // Duplicate kontrolü için map oluştur
    const companyIdMap = {};
    const companyNameMap = {};
    allTrainings.forEach((training, index) => {
        const id = training.company_id.toLowerCase();
        const name = training.company_name.toLowerCase();

        if (!companyIdMap[id]) companyIdMap[id] = [];
        if (!companyNameMap[name]) companyNameMap[name] = [];

        companyIdMap[id].push(index);
        companyNameMap[name].push(index);
    });

    // Paket türlerine göre gruplandırma
    const packageStats = {};
    allTrainings.forEach(training => {
        const pkg = training.package_type || 'Diğer';
        if (!packageStats[pkg]) {
            packageStats[pkg] = 0;
        }
        packageStats[pkg]++;
    });

    // Paket türlerini sayıya göre sırala
    const sortedPackages = Object.entries(packageStats).sort((a, b) => b[1] - a[1]);

    let html = '<div class="personnel-details">';
    html += '<div class="personnel-stats-header">';
    html += '<div class="stats-main stats-main-dynamic">';

    // "Tümü" paketi
    html += '<div class="main-stat package-stat-item' + (filterPackage === '' ? ' active' : '') + '" onclick="filterByPackage(\'\', event)">';
    html += '<span class="stat-label">Tümü</span>';
    html += '<strong class="stat-big">' + allTrainings.length + '</strong>';
    html += '</div>';

    // Her paket türü için ayrı sütun
    sortedPackages.forEach(([pkg, count]) => {
        html += '<div class="main-stat package-stat-item' + (filterPackage === pkg ? ' active' : '') + '" onclick="filterByPackage(\'' + pkg.replace(/'/g, "\\'") + '\', event)">';
        html += '<span class="stat-label">' + escapeHtml(pkg) + '</span>';
        html += '<strong class="stat-big">' + count + '</strong>';
        html += '</div>';
    });

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

    html += '<div class="table-wrapper">';
    html += '<table class="personnel-table">';
    html += '<thead><tr><th>Firma ID</th><th>Firma Adı</th><th>Paket Türü</th><th>Satış Tipi</th><th>Tarih</th></tr></thead>';
    html += '<tbody>';

    currentTrainings.forEach((training, idx) => {
        const globalIndex = startIndex + idx;
        const id = training.company_id.toLowerCase();
        const name = training.company_name.toLowerCase();

        // Duplicate kontrolü
        const isDuplicateId = companyIdMap[id] && companyIdMap[id].length > 1;
        const isDuplicateName = companyNameMap[name] && companyNameMap[name].length > 1;
        const isDuplicate = isDuplicateId || isDuplicateName;

        html += '<tr' + (isDuplicate ? ' class="duplicate-row"' : '') + '>';
        html += '<td><strong>' + escapeHtml(training.company_id) + '</strong>' +
               '</td>';
        html += '<td>' + escapeHtml(training.company_name) +
              '</td>';
        html += '<td><span class="badge ' + getPackageBadgeClass(training.package_type) + '">' + escapeHtml(training.package_type) + '</span></td>';
        html += '<td><span class="badge ' + getSalesBadgeClass(training.sales_type) + '">' + escapeHtml(training.sales_type) + '</span></td>';
        html += '<td>' + formatDate(training.training_completion_date) + '</td>';
        html += '</tr>';
    });

    html += '</tbody></table>';
    html += '</div>';
    
    // Sayfalama kontrollerini ekle
    if (totalPages > 1 || filterPackage) {
        html += '<div class="pagination">';
        const infoText = filterPackage
            ? 'Sayfa ' + currentPage + ' / ' + totalPages + ' (Filtrelenmiş: ' + filteredTrainings.length + ' / Toplam: ' + allTrainings.length + ' kayıt)'
            : 'Sayfa ' + currentPage + ' / ' + totalPages + ' (Toplam: ' + filteredTrainings.length + ' kayıt)';
        html += '<div class="pagination-info">' + infoText + '</div>';
        html += '<div class="pagination-controls">';
        
        // İlk sayfa butonu
        html += '<button onclick="goToPage(1)" ' + (currentPage === 1 ? 'disabled' : '') + ' class="page-btn">«</button>';
        
        // Önceki sayfa butonu
        html += '<button onclick="goToPage(' + (currentPage - 1) + ')" ' + (currentPage === 1 ? 'disabled' : '') + ' class="page-btn">‹</button>';
        
        // Sayfa numaraları
        let startPage = Math.max(1, currentPage - 2);
        let endPage = Math.min(totalPages, currentPage + 2);
        
        if (currentPage <= 3) {
            endPage = Math.min(5, totalPages);
        }
        if (currentPage >= totalPages - 2) {
            startPage = Math.max(1, totalPages - 4);
        }
        
        for (let i = startPage; i <= endPage; i++) {
            html += '<button onclick="goToPage(' + i + ')" class="page-btn ' + (i === currentPage ? 'active' : '') + '">' + i + '</button>';
        }
        
        // Sonraki sayfa butonu
        html += '<button onclick="goToPage(' + (currentPage + 1) + ')" ' + (currentPage === totalPages ? 'disabled' : '') + ' class="page-btn">›</button>';
        
        // Son sayfa butonu
        html += '<button onclick="goToPage(' + totalPages + ')" ' + (currentPage === totalPages ? 'disabled' : '') + ' class="page-btn">»</button>';
        
        html += '</div>';
        html += '</div>';
    }
    
    html += '</div>';
    content.innerHTML = html;
}

// Sayfaya git
function goToPage(page) {
    const filteredTrainings = filterPackage
        ? allTrainings.filter(t => t.package_type === filterPackage)
        : allTrainings;
    const totalPages = Math.ceil(filteredTrainings.length / itemsPerPage);
    if (page < 1 || page > totalPages) return;

    currentPage = page;
    renderPersonnelDetails({
        trainings: allTrainings,
        total_trainings: allTrainings.length,
        unique_companies: new Set(allTrainings.map(t => t.company_id)).size
    }, currentStartDate, currentEndDate);
}

// Paket filtresi
function filterByPackage(packageType, event) {
    if (event) {
        event.stopPropagation();
    }
    filterPackage = packageType;
    currentPage = 1; // Filtrelenince ilk sayfaya dön
    renderPersonnelDetails({
        trainings: allTrainings,
        total_trainings: allTrainings.length,
        unique_companies: new Set(allTrainings.map(t => t.company_id)).size
    }, currentStartDate, currentEndDate);
}

// Paket türü için badge sınıfı döndür
function getPackageBadgeClass(packageType) {
    if (!packageType) return 'package-default';
    const pkg = packageType.toLowerCase();

    if (pkg.includes('profesyonel')) return 'package-profesyonel';
    if (pkg.includes('enterprise') || pkg.includes('gelişmiş')) return 'package-enterprise';
    if (pkg.includes('standart') || pkg.includes('standard')) return 'package-standart';
    if (pkg.includes('mikro')) return 'package-mikro';
    if (pkg.includes('muhasebe')) return 'package-muhasebe';

    return 'package-default';
}

// Satış tipi için badge sınıfı döndür
function getSalesBadgeClass(salesType) {
    if (!salesType) return 'sales-default';
    const sales = salesType.toLowerCase();

    if (sales.includes('yeni') && sales.includes('satış')) return 'sales-yeni';
    if (sales.includes('yenileme') || sales.includes('lisans')) return 'sales-yenileme';

    return 'sales-default';
}

function closePersonnelModal() {
    document.getElementById('personnelModal').style.display = 'none';
}

function openAddModal() {
    document.getElementById('addModal').style.display = 'flex';
}

function closeAddModal() {
    document.getElementById('addModal').style.display = 'none';
}

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 escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Eğitim detayını göster
async function showTrainingDetails(trainingId) {
    const modal = document.getElementById('trainingDetailModal');
    const title = document.getElementById('trainingDetailModalTitle');
    const content = document.getElementById('trainingDetailModalContent');

    // Modal'ı aç ve yükleme göster
    modal.style.display = 'flex';
    title.textContent = 'Eğitim Detayı';
    content.innerHTML = '<div class="loading">Yükleniyor...</div>';

    try {
        // AJAX ile eğitim detayını al
        const response = await fetch('get_training_detail.php?id=' + trainingId);
        const data = await response.json();

        if (data.success) {
            renderTrainingDetail(data.training);
        } else {
            content.innerHTML = '<div class="error">Eğitim detayı bulunamadı.</div>';
        }
    } catch (error) {
        content.innerHTML = '<div class="error">Veriler yüklenirken bir hata oluştu.</div>';
    }
}

// Eğitim detayını render et
function renderTrainingDetail(training) {
    const content = document.getElementById('trainingDetailModalContent');
    
    let html = '<div class="training-detail">';
    html += '<div class="detail-grid">';
    
    // Firma Bilgileri
    html += '<div class="detail-section">';
    html += '<h3 class="detail-section-title">Firma Bilgileri</h3>';
    html += '<div class="detail-item"><span class="detail-label">Firma ID:</span> <strong>' + escapeHtml(training.company_id) + '</strong></div>';
    html += '<div class="detail-item"><span class="detail-label">Firma Adı:</span> <strong>' + escapeHtml(training.company_name) + '</strong></div>';
    html += '</div>';
    
    // Eğitim Bilgileri
    html += '<div class="detail-section">';
    html += '<h3 class="detail-section-title">Eğitim Bilgileri</h3>';
    html += '<div class="detail-item"><span class="detail-label">Satış Kaynağı:</span> ' + (training.sales_source ? escapeHtml(training.sales_source) : '-') + '</div>';
    html += '<div class="detail-item"><span class="detail-label">Destek Temsilcisi:</span> ' + (training.support_representative ? escapeHtml(training.support_representative) : '-') + '</div>';
    html += '<div class="detail-item"><span class="detail-label">Eğitim Tarihi:</span> ' + formatDate(training.training_completion_date) + '</div>';
    html += '</div>';
    
    // Paket Bilgileri
    html += '<div class="detail-section">';
    html += '<h3 class="detail-section-title">Paket Bilgileri</h3>';
    html += '<div class="detail-item"><span class="detail-label">Satış Tipi:</span> ' + (training.sales_type ? escapeHtml(training.sales_type) : '-') + '</div>';
    html += '<div class="detail-item"><span class="detail-label">Paket Türü:</span> ' + (training.package_type ? escapeHtml(training.package_type) : '-') + '</div>';
    html += '</div>';
    
    html += '</div>'; // detail-grid
    html += '</div>'; // training-detail
    
    content.innerHTML = html;
}

function closeTrainingDetailModal() {
    document.getElementById('trainingDetailModal').style.display = 'none';
}

// Tüm Kayıtlar için filtreleme ve sayfalama
let currentRecordsPage = 1;
const recordsPerPage = 10;
let activePackageFilter = '';

// Sayfa yüklendiğinde başlat
document.addEventListener('DOMContentLoaded', function() {
    initializeRecordsTable();
});

function initializeRecordsTable() {
    // Filtre butonlarına event listener ekle
    const filterButtons = document.querySelectorAll('.record-filter-btn');
    filterButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            // Aktif sınıfı güncelle
            filterButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // Filtre değerini al
            activePackageFilter = this.getAttribute('data-package');
            currentRecordsPage = 1; // İlk sayfaya dön
            
            // Tabloyu güncelle
            updateRecordsTable();
        });
    });
    
    // İlk yükleme
    updateRecordsTable();
}

function updateRecordsTable() {
    const allRows = document.querySelectorAll('.record-row');
    
    // Filtreleme uygula
    let filteredRows = Array.from(allRows);
    if (activePackageFilter) {
        filteredRows = filteredRows.filter(row => {
            return row.getAttribute('data-package') === activePackageFilter;
        });
    }
    
    // Toplam sayfa sayısını hesapla
    const totalPages = Math.ceil(filteredRows.length / recordsPerPage);
    
    // Tüm satırları gizle
    allRows.forEach(row => row.style.display = 'none');
    
    // Mevcut sayfadaki satırları göster
    const startIndex = (currentRecordsPage - 1) * recordsPerPage;
    const endIndex = startIndex + recordsPerPage;
    const rowsToShow = filteredRows.slice(startIndex, endIndex);
    
    rowsToShow.forEach(row => row.style.display = '');
    
    // Sayfalama kontrollerini güncelle
    updateRecordsPagination(filteredRows.length, totalPages);
}

function updateRecordsPagination(totalRecords, totalPages) {
    const paginationInfo = document.querySelector('#recordsPagination .pagination-info');
    const paginationControls = document.querySelector('#recordsPagination .pagination-controls');
    
    if (totalPages <= 1) {
        paginationInfo.innerHTML = 'Toplam: ' + totalRecords + ' kayıt';
        paginationControls.innerHTML = '';
        return;
    }
    
    // Bilgi metni
    const infoText = activePackageFilter
        ? 'Sayfa ' + currentRecordsPage + ' / ' + totalPages + ' (Filtrelenmiş: ' + totalRecords + ' kayıt)'
        : 'Sayfa ' + currentRecordsPage + ' / ' + totalPages + ' (Toplam: ' + totalRecords + ' kayıt)';
    paginationInfo.innerHTML = infoText;
    
    // Kontrol butonları
    let html = '';
    
    // İlk sayfa butonu
    html += '<button onclick="goToRecordsPage(1)" ' + (currentRecordsPage === 1 ? 'disabled' : '') + ' class="page-btn">«</button>';
    
    // Önceki sayfa butonu
    html += '<button onclick="goToRecordsPage(' + (currentRecordsPage - 1) + ')" ' + (currentRecordsPage === 1 ? 'disabled' : '') + ' class="page-btn">‹</button>';
    
    // Sayfa numaraları
    let startPage = Math.max(1, currentRecordsPage - 2);
    let endPage = Math.min(totalPages, currentRecordsPage + 2);
    
    if (currentRecordsPage <= 3) {
        endPage = Math.min(5, totalPages);
    }
    if (currentRecordsPage >= totalPages - 2) {
        startPage = Math.max(1, totalPages - 4);
    }
    
    for (let i = startPage; i <= endPage; i++) {
        html += '<button onclick="goToRecordsPage(' + i + ')" class="page-btn ' + (i === currentRecordsPage ? 'active' : '') + '">' + i + '</button>';
    }
    
    // Sonraki sayfa butonu
    html += '<button onclick="goToRecordsPage(' + (currentRecordsPage + 1) + ')" ' + (currentRecordsPage === totalPages ? 'disabled' : '') + ' class="page-btn">›</button>';
    
    // Son sayfa butonu
    html += '<button onclick="goToRecordsPage(' + totalPages + ')" ' + (currentRecordsPage === totalPages ? 'disabled' : '') + ' class="page-btn">»</button>';
    
    paginationControls.innerHTML = html;
}

function goToRecordsPage(page) {
    const allRows = document.querySelectorAll('.record-row');
    let filteredRows = Array.from(allRows);
    if (activePackageFilter) {
        filteredRows = filteredRows.filter(row => {
            return row.getAttribute('data-package') === activePackageFilter;
        });
    }
    
    const totalPages = Math.ceil(filteredRows.length / recordsPerPage);
    if (page < 1 || page > totalPages) return;
    
    currentRecordsPage = page;
    updateRecordsTable();
}

// Modal dışına tıklayınca kapat
window.onclick = function(event) {
    const addModal = document.getElementById('addModal');
    const personnelModal = document.getElementById('personnelModal');
    const trainingDetailModal = document.getElementById('trainingDetailModal');
    
    if (event.target === addModal) {
        closeAddModal();
    }
    if (event.target === personnelModal) {
        closePersonnelModal();
    }
    if (event.target === trainingDetailModal) {
        closeTrainingDetailModal();
    }
}

// Chart.js grafikleri - Sayfa yüklendiğinde oluştur
document.addEventListener('DOMContentLoaded', function() {
    // PHP'den gelen verileri JavaScript'e aktar
    const personnelData = <?php echo json_encode($chartPersonnelData); ?>;
    const packageData = <?php echo json_encode($chartPackageData); ?>;
    const salesSourceData = <?php echo json_encode($chartSalesSourceData); ?>;
    
    // Renk paleti
    const colorPalette = [
        'rgba(102, 126, 234, 0.8)',
        'rgba(118, 75, 162, 0.8)',
        'rgba(52, 152, 219, 0.8)',
        'rgba(46, 204, 113, 0.8)',
        'rgba(155, 89, 182, 0.8)',
        'rgba(241, 196, 15, 0.8)',
        'rgba(230, 126, 34, 0.8)',
        'rgba(231, 76, 60, 0.8)',
        'rgba(26, 188, 156, 0.8)',
        'rgba(149, 165, 166, 0.8)'
    ];
    
    // 1. Personel Bazlı Tamamlanan Eğitimler (Bar Chart)
    if (personnelData && personnelData.length > 0) {
        const ctx1 = document.getElementById('personnelChart').getContext('2d');
        new Chart(ctx1, {
            type: 'bar',
            data: {
                labels: personnelData.map(item => item.support_representative),
                datasets: [{
                    label: 'Tamamlanan Eğitim Sayısı',
                    data: personnelData.map(item => parseInt(item.total_trainings)),
                    backgroundColor: colorPalette.slice(0, personnelData.length),
                    borderColor: colorPalette.slice(0, personnelData.length).map(color => color.replace('0.8', '1')),
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.parsed.y + ' eğitim';
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }
    
    // 2. Paket Türü Dağılımı (Pie Chart)
    if (packageData && packageData.length > 0) {
        const ctx2 = document.getElementById('packageChart').getContext('2d');
        const total = packageData.reduce((sum, item) => sum + parseInt(item.count), 0);
        
        new Chart(ctx2, {
            type: 'pie',
            data: {
                labels: packageData.map(item => item.package_type),
                datasets: [{
                    data: packageData.map(item => parseInt(item.count)),
                    backgroundColor: colorPalette.slice(0, packageData.length),
                    borderColor: '#ffffff',
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        position: 'right',
                        labels: {
                            padding: 15,
                            font: {
                                size: 12
                            }
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const percentage = ((context.parsed / total) * 100).toFixed(1);
                                return context.label + ': ' + context.parsed + ' (' + percentage + '%)';
                            }
                        }
                    }
                }
            }
        });
    }
    
    // 3. Satış Kaynağı Dağılımı (Bar Chart)
    if (salesSourceData && salesSourceData.length > 0) {
        const ctx3 = document.getElementById('salesSourceChart').getContext('2d');
        new Chart(ctx3, {
            type: 'bar',
            data: {
                labels: salesSourceData.map(item => item.sales_source),
                datasets: [{
                    label: 'Eğitim Sayısı',
                    data: salesSourceData.map(item => parseInt(item.count)),
                    backgroundColor: colorPalette.slice(0, salesSourceData.length),
                    borderColor: colorPalette.slice(0, salesSourceData.length).map(color => color.replace('0.8', '1')),
                    borderWidth: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: true,
                plugins: {
                    legend: {
                        display: false
                    },
                    title: {
                        display: false
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                return context.parsed.y + ' eğitim';
                            }
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                }
            }
        });
    }
});
</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-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;
}

/* 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: 2fr 1fr 1fr 1fr auto;
    gap: 15px;
    align-items: end;
}

.filter-group {
    grid-column: span 1;
}

.filter-group.filter-date-range {
    grid-column: span 1;
}

.filter-group.filter-search {
    grid-column: span 1;
}

.filter-actions {
    grid-column: span 1;
    display: flex;
    flex-direction: row;
    gap: 8px;
}

.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;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.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 .btn {
    white-space: nowrap;
    justify-content: center;
}

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

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

/* Personnel Card Styling */
.personnel-card {
    cursor: pointer;
}

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

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

/* Modal Body */
.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;
}

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

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

/* Personnel Details */
.personnel-details {
    padding: 0;
    width: 100%;
}

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

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

.stats-main.stats-main-dynamic {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
}

.main-stat {
    text-align: center;
}

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

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

.main-stat .stat-date {
    display: block;
    font-size: 14px;
    color: #2c3e50;
    font-weight: 600;
    line-height: 1.4;
}

.main-stat.package-stat-item {
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid transparent;
    padding: 15px;
    border-radius: 10px;
    background: white;
}

.main-stat.package-stat-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
    border-color: #667eea;
}

.main-stat.package-stat-item.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-color: #667eea;
}

.main-stat.package-stat-item.active .stat-label {
    color: rgba(255, 255, 255, 0.9);
}

.main-stat.package-stat-item.active .stat-big {
    color: white;
}

.package-filter-section {
    grid-column: 1 / -1;
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-top: 20px;
    padding-top: 20px;
    border-top: 2px solid #dee2e6;
}

.package-label {
    font-size: 12px;
    color: #6c757d;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 700;
}

.package-badges {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.package-stat-badge {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 14px;
    border-radius: 20px;
    color: white;
    font-size: 13px;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transition: all 0.2s;
    cursor: pointer;
    position: relative;
}

.package-stat-badge:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.package-stat-badge.active {
    box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.3);
    transform: scale(1.05);
}

.package-stat-badge.active::after {
    content: '✓';
    position: absolute;
    top: -5px;
    right: -5px;
    background: #27ae60;
    color: white;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    font-weight: 700;
}

.package-stat-badge .pkg-name {
    flex: 1;
}

.package-stat-badge .pkg-count {
    background: rgba(255, 255, 255, 0.3);
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 700;
}

/* Tümü badge rengi */
.badge.package-all,
.package-stat-badge.package-all {
    background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
    color: white;
}

.personnel-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 13px;
}

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

.personnel-table thead th {
    padding: 10px 12px;
    text-align: left;
    font-weight: 600;
    font-size: 12px;
    white-space: nowrap;
}

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

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

.clickable-row {
    cursor: pointer;
    transition: all 0.2s ease;
}

.clickable-row:hover {
    background-color: #e3f2fd !important;
    transform: scale(1.01);
}

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

/* Pagination Styles */
.pagination {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 2px solid #ecf0f1;
}

.pagination-info {
    text-align: center;
    color: #7f8c8d;
    font-size: 12px;
    margin-bottom: 12px;
    font-weight: 500;
}

.pagination-controls {
    display: flex;
    justify-content: center;
    gap: 8px;
    flex-wrap: wrap;
}

.page-btn {
    padding: 6px 10px;
    border: 2px solid #e0e0e0;
    background: white;
    color: #2c3e50;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    min-width: 36px;
}

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

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

.page-btn:disabled {
    opacity: 0.4;
    cursor: not-allowed;
}

.table-wrapper {
    overflow-x: auto;
    width: 100%;
    -webkit-overflow-scrolling: touch;
}

.table-wrapper::-webkit-scrollbar {
    height: 8px;
}

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

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

.table-wrapper::-webkit-scrollbar-thumb:hover {
    background: #555;
}

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

.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;
}

table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;
    border: 1px solid #dee2e6;
}

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

thead th {
    padding: 15px;
    text-align: center;
    font-weight: 600;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border: 1px solid rgba(255, 255, 255, 0.2);
}

tbody tr {
    border-bottom: 1px solid #dee2e6;
    transition: background-color 0.2s;
}

tbody tr:hover {
    background-color: #f8f9fa;
}

tbody td {
    padding: 15px;
    color: #2c3e50;
    text-align: center;
    border: 1px solid #dee2e6;
}

/* Destek Temsilcisi sütununu genişlet */
.data-table-container table thead th:nth-child(2),
.data-table-container table tbody td:nth-child(2) {
    min-width: 180px;
    text-align: left;
}

/* Sıra sütununu daralt */
.data-table-container table thead th:nth-child(1),
.data-table-container table tbody td:nth-child(1) {
    width: 60px;
}

/* Badges */
.badge {
    display: inline-block;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-align: center;
    white-space: nowrap;
}

.badge.excellent {
    background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
    color: white;
}

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

.badge.average {
    background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
    color: white;
}

.badge.poor {
    background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
    color: white;
}

/* Paket Türü Badge Renkleri */
.badge.package-profesyonel {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
}

.badge.package-enterprise {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: white;
}

.badge.package-standart {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    color: white;
}

.badge.package-mikro {
    background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
    color: white;
}

.badge.package-muhasebe {
    background: linear-gradient(135deg, #30cfd0 0%, #330867 100%);
    color: white;
}

.badge.package-default {
    background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
    color: #2c3e50;
}

/* Satış Tipi Badge Renkleri */
.badge.sales-yeni {
    background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
    color: white;
}

.badge.sales-yenileme {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    color: white;
}

.badge.sales-default {
    background: linear-gradient(135deg, #fbc2eb 0%, #a6c1ee 100%);
    color: white;
}

/* Duplicate Highlight */
.duplicate-row {
    background-color: #fff3cd !important;
    border-left: 4px solid #ffc107 !important;
}

.duplicate-badge {
    display: inline-block;
    padding: 2px 6px;
    background: #ffc107;
    color: #856404;
    border-radius: 4px;
    font-size: 10px;
    font-weight: 700;
    margin-left: 5px;
}

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

.progress-fill {
    height: 100%;
    border-radius: 10px;
    transition: width 0.5s ease;
}

.progress-fill.excellent {
    background: linear-gradient(90deg, #56ab2f 0%, #a8e063 100%);
}

.progress-fill.good {
    background: linear-gradient(90deg, #3498db 0%, #2980b9 100%);
}

.progress-fill.average {
    background: linear-gradient(90deg, #f39c12 0%, #e67e22 100%);
}

.progress-fill.poor {
    background: linear-gradient(90deg, #e74c3c 0%, #c0392b 100%);
}

/* Alert Messages */
.alert {
    padding: 15px 20px;
    border-radius: 10px;
    margin-bottom: 20px;
    font-weight: 500;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-error {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}

/* 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: 85vh;
    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;
}

.add-form {
    padding: 25px 30px;
}

.form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 18px;
}

.form-row:last-of-type {
    grid-template-columns: 1fr;
}

#addModal .modal-content {
    max-width: 700px;
    max-height: 90vh;
}

#personnelModal .modal-content {
    width: 98%;
    max-width: 1400px;
    max-height: 98vh;
}

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

.required {
    color: #e74c3c;
}

.form-actions {
    display: flex;
    gap: 15px;
    margin-top: 30px;
    justify-content: flex-end;
}

.form-actions .btn {
    padding: 12px 30px;
}

/* Colored Badge Styling */
.colored-badge {
    display: inline-block;
    padding: 6px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-align: center;
    white-space: nowrap;
    transition: all 0.2s ease;
}

/* Training Detail Modal Styling */
.training-detail {
    padding: 0;
    width: 100%;
}

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

.detail-section {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    padding: 20px;
    border: 1px solid #dee2e6;
}

.detail-section-title {
    font-size: 16px;
    font-weight: 700;
    color: #667eea;
    margin: 0 0 15px 0;
    padding-bottom: 10px;
    border-bottom: 2px solid #dee2e6;
}

.detail-item {
    margin-bottom: 12px;
    font-size: 14px;
    color: #2c3e50;
    line-height: 1.6;
}

.detail-item:last-child {
    margin-bottom: 0;
}

.detail-label {
    font-weight: 600;
    color: #6c757d;
    display: inline-block;
    min-width: 150px;
}

#trainingDetailModal .modal-content {
    max-width: 900px;
    max-height: 90vh;
}

/* Records Filter Header */
.records-filter-header {
    margin-bottom: 25px;
    padding: 20px;
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px;
    border: 1px solid #dee2e6;
}

.records-filter-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    justify-content: center;
}

.record-filter-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 18px;
    border: 2px solid transparent;
    background: white;
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.record-filter-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.2);
    border-color: #667eea;
}

.record-filter-btn.active {
    border-width: 3px;
    border-color: #2c3e50;
    box-shadow: 0 6px 16px rgba(44, 62, 80, 0.4);
    transform: translateY(-3px);
}

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

.record-filter-btn.active .filter-label {
    color: #2c3e50;
    font-weight: 700;
}

.record-filter-btn .filter-count {
    background: rgba(255, 255, 255, 0.6);
    color: #2c3e50;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 12px;
    font-weight: 700;
    min-width: 28px;
    text-align: center;
}

.record-filter-btn.active .filter-count {
    background: white;
    color: #2c3e50;
    font-weight: 800;
}

/* Charts Grid */
.charts-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
    gap: 30px;
    margin-top: 25px;
}

.chart-container {
    background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
    border-radius: 12px;
    padding: 25px;
    border: 1px solid #e0e0e0;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.chart-container:hover {
    box-shadow: 0 4px 15px rgba(102, 126, 234, 0.15);
    border-color: #667eea;
}

.chart-title {
    font-size: 16px;
    font-weight: 700;
    color: #2c3e50;
    margin: 0 0 20px 0;
    padding-bottom: 12px;
    border-bottom: 2px solid #ecf0f1;
    text-align: center;
}

.chart-container canvas {
    max-height: 350px;
}

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

    #addModal .modal-content {
        width: 95%;
        max-height: 95vh;
    }

    .modal-header {
        padding: 18px 20px;
    }

    .add-form {
        padding: 20px;
    }

    .form-actions {
        flex-direction: column;
    }

    .form-actions .btn {
        width: 100%;
    }

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

    #personnelModal .stats-main {
        grid-template-columns: 1fr;
    }

    #personnelModal .package-badges {
        flex-direction: column;
    }
}

/* Responsive */
@media (max-width: 1600px) {
    #personnelModal .modal-content {
        max-width: 95%;
    }
}

@media (max-width: 1400px) {
    .filters-form {
        grid-template-columns: 2fr 1fr 1fr 1.5fr auto;
    }

    #personnelModal .modal-content {
        max-width: 98%;
    }
}

@media (max-width: 1200px) {
    .filters-form {
        grid-template-columns: 1fr 1fr auto;
        gap: 15px;
    }

    .filter-group.filter-date-range {
        grid-column: span 2;
    }

    .filter-group,
    .filter-group.filter-search {
        grid-column: span 1;
    }

    .filter-actions {
        grid-column: span 1;
        grid-row: 1;
        align-self: end;
    }

    .filter-group.filter-date-range {
        grid-row: 1;
    }

    .filter-group:nth-child(2) {
        grid-row: 2;
    }

    .filter-group:nth-child(3) {
        grid-row: 2;
    }

    .filter-group.filter-search {
        grid-row: 2;
    }

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

    #personnelModal .stats-main.stats-main-dynamic {
        grid-template-columns: repeat(auto-fit, minmax(130px, 1fr));
    }
}

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

    .filter-group,
    .filter-group.filter-date-range,
    .filter-group.filter-search {
        grid-column: span 1;
        grid-row: auto;
    }

    .filter-actions {
        grid-column: span 1;
        grid-row: 1;
        align-self: end;
    }

    .filter-group.filter-date-range {
        grid-row: 1;
    }

    .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;
    }

    .quick-filters {
        justify-content: flex-start;
    }

    .quick-filter-btn {
        font-size: 12px;
        padding: 6px 12px;
    }

    #personnelModal .modal-content {
        width: 100%;
        max-width: 100%;
        max-height: 95vh;
    }

    #personnelModal .modal-body {
        padding: 20px 15px;
    }

    #personnelModal .personnel-stats-header {
        padding: 15px;
    }

    #personnelModal .stats-main {
        grid-template-columns: 1fr;
        gap: 15px;
        margin-bottom: 15px;
        padding-bottom: 15px;
    }

    #personnelModal .stats-main.stats-main-dynamic {
        grid-template-columns: 1fr;
    }

    #personnelModal .main-stat .stat-big {
        font-size: 24px;
    }

    #personnelModal .main-stat .stat-date {
        font-size: 12px;
    }

    #personnelModal .main-stat.package-stat-item {
        padding: 12px;
    }

    #personnelModal .main-stat.package-stat-item .stat-label {
        font-size: 10px;
    }

    #personnelModal .main-stat.package-stat-item .stat-big {
        font-size: 20px;
    }

    #personnelModal .personnel-table {
        font-size: 11px;
    }

    #personnelModal .personnel-table thead th,
    #personnelModal .personnel-table tbody td {
        padding: 8px 6px;
    }

    #personnelModal .pagination-controls {
        gap: 5px;
    }

    #personnelModal .page-btn {
        padding: 5px 8px;
        font-size: 12px;
        min-width: 32px;
    }
}
</style>

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