<style>
.statistics-section {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    border-right: #aeaeae solid 1px;
}

.file-icon {
    width: 16px;  
    height: 16px; 
    object-fit: contain; 
    border-radius: 0; 
    margin-right: 8px; 
}

.file-summary {
    display: flex;
    flex-direction: column; 
    align-items: flex-start; 
    margin: 0px 8px 20px 8px; 
}

.pie-chart-container {
    display: flex;
    justify-content: center; 
    align-items: center;  
    border: 1px solid #ccc; 
    padding: 5px; 
    border-radius: 5px; 
    background-color: #f9f9f9; 
}
.file-summary h2 {
    font-size: 1.3rem; 
    margin-bottom: 0.8rem; 
    color: #CC0000;
}

.file-summary ul {
    list-style: none;
    margin-top: 0;
    padding-left: 0;
}

.file-summary ul li {
    background-color: #f0f0f0;
    padding: 5px;
    border-radius: 5px;
    font-size: 0.9rem; 
    margin: 0.4rem 0;
}

.file-summary ul li a {
    color:rgb(50, 50, 50);
    font-weight: 500;
}
</style>
<h2>File Statistics</h2>
    <div class="file-summary">
        <ul>
            <?php
            require_once 'functions.php';

            // Use the central pmed database and table for the users piechart
            // main_db_connect.php exposes $conn (ppdco) and $conn2 (pmed_db)
            $divisionConn = isset($conn2) ? $conn2 : $conn;
            $table = 'pmed_documents';
            // Use the pmed table's file type field
            $fileTypeField = 'pmed_file_type';

            $totalFiles = 0;
            $fileCounts = [
                'Image Files' => 0,
                'Video Files' => 0,
                'Audio Files' => 0,
                'PDF Files' => 0,
                'Word Documents' => 0,
                'Excel Spreadsheets' => 0,
                'Power Point' => 0,
                'Code Files' => 0,
                'Compressed Files' => 0,
                'Other Files' => 0,
            ];

            $result = $divisionConn->query("SELECT * FROM $table WHERE 1=1");
            if ($result) {
                while ($row = $result->fetch_assoc()) {
                    $totalFiles++;
                    switch ($row[$fileTypeField]) {
                        case 'doc':
                        case 'docx':
                            $fileCounts['Word Documents']++;
                            break;
                        case 'pdf':
                            $fileCounts['PDF Files']++;
                            break;
                        case 'xls':
                        case 'xlsx':
                            $fileCounts['Excel Spreadsheets']++;
                            break;
                        case 'ppt':
                        case 'pptx':
                            $fileCounts['Power Point']++;
                            break;
                        case 'jpg':
                        case 'jpeg':
                        case 'png':
                        case 'gif':
                        case 'bmp':
                        case 'ico':
                        case 'webp':
                        case 'tiff':
                        case 'tif':
                        case 'psd':
                        case 'raw':
                        case 'heif':  
                        case 'svg':  
                        case 'svgz':  
                        case 'ai':   
                        case 'eps':  
                        case 'ps':   
                        case 'cdr':  
                        case 'wmf':  
                        case 'emf':
                            $fileCounts['Image Files']++;
                            break;
                        case 'mp4':
                        case 'm4p':
                        case 'm4v':
                        case 'mpg':
                        case 'mp2':
                        case 'mpeg':
                        case 'mpe':
                        case 'mpv':
                        case 'svi':
                        case '3gp':
                        case '3g2':
                        case 'mxf':
                        case 'roq':
                        case 'nsv':
                        case 'flv':
                        case 'f4v':
                        case 'f4p':
                        case 'f4a':
                        case 'f4b':
                        case 'mod':
                        case 'webm':
                        case 'mkv':
                        case 'vob':
                        case 'ogv':
                        case 'mov':
                        case 'avi':
                        case 'qt':
                        case 'wmv':
                        case 'yuv':
                        case 'rm':
                        case 'asf':
                        case 'amv':
                            $fileCounts['Video Files']++;
                            break;
                        case 'mp3':
                        case 'aac':
                        case 'wav':
                        case 'aiff':
                        case 'pcm':
                        case 'flac':
                        case 'alac':
                        case 'wma':
                        case 'ogg':
                        case 'oga':
                        case 'dsd':
                        case 'm4a':
                        case 'm4b':
                        case 'm4p':
                        case 'm4r':
                        case '3ga':
                        case 'mid':
                        case 'midi':
                        case 'xmf':
                        case 'rtttl':
                        case 'rtx':
                        case 'ota':
                        case 'imy':
                        case 'spx':
                        case 'opus':
                            $fileCounts['Audio Files']++;
                            break;
                        case 'h':
                        case 'H':
                        case 'html':
                        case 'php':
                        case 'js':
                        case 'css':
                        case 'sql':
                        case 'py':
                        case 'csv':
                        case 'cxx':
                        case 'CXX':
                        case 'CPP':
                        case 'c':
                            $fileCounts['Code Files']++;
                            break;
                        case 'zip':
                        case 'rar':
                        case '7z':
                        case 'tar':
                        case 'gz':
                        case 'bz2':
                        case 'xz':
                        case 'z':
                        case 'Z':
                        case 'taz':
                        case 'tgz':
                        case 'tbz':
                        case 'tbz2':
                        case 'txz':
                        case 'tlz':
                        case 'zipx':
                        case 'sit':
                        case 'sitx':
                        case 'ace':
                        case 'arj':
                        case 'cab':
                        case 'deb':
                            $fileCounts['Compressed Files']++;
                            break;
                        default:
                            $fileCounts['Other Files']++;
                            break;
                    }
                }
            }

            foreach ($fileCounts as $type => $count) {
                $percentage = ($totalFiles > 0) ? round(($count / $totalFiles) * 100, 2) : 0;

                switch ($type) {
                    case 'Image Files':
                        $iconPath = 'icons/file/image.svg';
                        break;
                    case 'Video Files':
                        $iconPath = 'icons/file/video.svg';
                        break;
                    case 'Audio Files':
                        $iconPath = 'icons/file/audio.svg';
                        break;
                    case 'PDF Files':
                        $iconPath = 'icons/file/pdf.svg';
                        break;
                    case 'Word Documents':
                        $iconPath = 'icons/file/word.svg';
                        break;
                    case 'Excel Spreadsheets':
                        $iconPath = 'icons/file/excel.svg';
                        break;
                    case 'Power Point':
                        $iconPath = 'icons/file/ppt.svg';
                        break;
                    case 'Code Files':
                        $iconPath = 'icons/file/code.svg';
                        break;
                    case 'Compressed Files':
                        $iconPath = 'icons/file/zip.svg';
                        break;
                    case 'Other Files':
                        $iconPath = 'icons/file/others.svg';
                        break;
                    default:
                }

                echo "<li><img src='$iconPath' alt='" . strtoupper($type) . " Icon' class='file-icon'><a>$type:</a> $count files ($percentage%)</li>";
            }

            echo "<li><a>Total Files:</a> $totalFiles files</li>";
            
            // Do not close $divisionConn here to avoid breaking subsequent queries on the page
            ?>
        </ul>
    </div>

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

<!-- Pie chart JavaScript (reliable Chart.js usage) -->
<script>
(function(){
    const canvas = document.getElementById('pieChart');
    if(!canvas) return;
    canvas.style.width = '100%';
    canvas.style.height = '300px';

    const labels = [
        "Word Documents", "Excel Spreadsheets", "Power Point",
        "PDF Files", "Image Files", "Video Files", "Audio Files", "Code Files", "Compressed Files", "Other Files"
    ];

    const dataArr = [
        <?= $fileCounts['Word Documents'] ?>,
        <?= $fileCounts['Excel Spreadsheets'] ?>,
        <?= $fileCounts['Power Point'] ?>,
        <?= $fileCounts['PDF Files'] ?>,
        <?= $fileCounts['Image Files'] ?>,
        <?= $fileCounts['Video Files'] ?>,
        <?= $fileCounts['Audio Files'] ?>,
        <?= $fileCounts['Code Files'] ?>,
        <?= $fileCounts['Compressed Files'] ?>,
        <?= $fileCounts['Other Files'] ?>
    ];

    const totalFiles = <?= $totalFiles ?>;

    let chartRef = null;

    function registerPluginIfNeeded(){
        try{
            if(window.Chart && window.Chart.register && window.ChartDataLabels){
                window.Chart.register(window.ChartDataLabels);
            }
        }catch(e){/* ignore */}
    }

    function createChart(){
        if(!canvas) return;
        const sidebar = document.getElementById('sidebar');
        if(sidebar && sidebar.classList.contains('hidden')) return; // don't create when hidden
        if(totalFiles <= 0) return;
        registerPluginIfNeeded();
        try{ if(chartRef) chartRef.destroy(); }catch(e){}
        const ctx = canvas.getContext('2d');
        chartRef = new Chart(ctx, {
            type: 'pie',
            data: {
                labels: labels,
                datasets: [{
                    data: dataArr,
                    backgroundColor: ['#0086E6','#00B33C','#FF7D27','#E60000','#FFD500','#32BEA6','#800080','#9c9c9c','#FF69B4','#FFD700']
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    tooltip: {
                        callbacks: {
                            label: function(context){
                                const idx = context.dataIndex;
                                const label = context.label || '';
                                const value = context.formattedValue || context.raw || 0;
                                const pct = (dataArr[idx] / <?= ($totalFiles>0?$totalFiles:1) ?> * 100).toFixed(2);
                                return label + ': ' + value + ' (' + pct + '%)';
                            }
                        }
                    },
                    datalabels: {
                        color: '#000',
                        formatter: function(value){
                            return ((value / <?= ($totalFiles>0?$totalFiles:1) ?>) * 100).toFixed(2) + '%';
                        }
                    },
                    legend: { display: false },
                    title: { display: true, text: 'File Type Distribution' }
                }
            }
        });
    }

    function destroyChart(){ if(chartRef){ try{ chartRef.destroy(); }catch(e){} chartRef = null; } }

    document.addEventListener('DOMContentLoaded', function(){ createChart(); });
    window.addEventListener('sidebarToggled', function(ev){ if(ev.detail && ev.detail.visible) createChart(); else destroyChart(); });
})();
</script>