<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="stylesheet" href="css/main/main.css?ver=<?php echo time(); ?>">
    <script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>
    <style>
        /* Basic styling */
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f8f9fa;
        }

        /* Responsive CSS Grid for the dashboard cards */
        .dashboard-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .card {
            padding: 20px;
            background-color: #ffffff;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            text-align: center;
            border: 2px solid #4CAF50; /* Green Border */
            box-sizing: border-box; /* Ensures padding and border are included in the element's total width */
        }

        .card h3 {
            margin-bottom: 10px;
            color: #4CAF50;
            font-size: 18px;

        }

        .card .value {
            font-size: 18px;
            font-weight: bold;
            color: #4CAF50;
        }

        /* Add icons */
        .card i {
            font-size: 30px;
            margin-bottom: 10px;
            color: #4CAF50;
        }
        

        #order-chart {
            width: 100%; /* Ensure the width is responsive */
            height: 300px; /* Fixed height for the chart */
            margin-top: 20px;
        }

        .chart-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: space-around;
            gap: 20px;
            margin-top: 20px;
        }
        .chart-box {
            width: 100%;
            max-width: 450px;
            height: 400px; /* Added: Fixed height to prevent resizing issues */
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }


        /* --- Table Styling --- */
        .table-container {
            max-height: 500px; /* Fixed height for the table */
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 8px;
            background-color: #fff;
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }
        
        thead th {
            position: sticky; /* Make the header sticky */
            top: 0;
            background-color: #4CAF50;
            color: white;
            z-index: 1; /* Ensures the header stays on top */
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ddd;
            word-wrap: break-word; /* Ensures long text will wrap */
        }

        /* Ensure the table doesn't break layout */
        td {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .table-container::-webkit-scrollbar {
            width: 8px;
        }
        .table-container::-webkit-scrollbar-thumb {
            background-color: #4CAF50;
            border-radius: 8px;
        }
        .table-container::-webkit-scrollbar-track {
            background-color: #f1f1f1;
        }
        
        /* Add a media query for small screens */
        @media screen and (max-width: 600px) {
            .card {
                width: 150px; /* Make the card width 150px on small screens */
                margin: 10px auto; /* Center the cards horizontally */
            }
        
            .dashboard-section {
                grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); /* Adjust grid for smaller cards */
                gap: 10px; /* Adjust the gap between cards */
            }
        
            /* Adjust font size and layout of the table for smaller screens */
            table {
                font-size: 12px; /* Smaller font size for better readability */
            }
        
            th, td {
                padding: 8px; /* Reduce padding for better space utilization */
            }
        
            .table-container {
                max-height: 300px; /* Reduce height for mobile */
            }
        
            #order-chart {
                height: 200px; /* Reduce chart height on small screens */
            }
        }


    </style>
</head>
<body>

    <div class="left-panel left-panel-show" id="left-panel">
    </div>

    <div class="main-content main-content-normal" id="main-content">

        <div class="dashboard-section">
            <!-- NEW CARDS ADDED BELOW -->
            <div class="card">
                <i class="fas fa-file-alt"></i>
                <h3>Knowledge Files</h3>
                <p class="value" id="knowledge-files-count">0</p>
            </div>
            <div class="card">
                <i class="fas fa-file-invoice"></i>
                <h3>Instruction Files</h3>
                <p class="value" id="instruction-files-count">0</p>
            </div>
            <!-- NEW CARDS FOR MESSAGES -->
            <div class="card">
                <i class="fas fa-comment-alt"></i>
                <h3>Total Messages</h3>
                <p class="value" id="total-messages-count">0</p>
            </div>
            <div class="card">
                <i class="fas fa-share"></i>
                <h3>Total Replies</h3>
                <p class="value" id="total-replies-count">0</p>
            </div>
            <div class="card">
                <i class="fas fa-question"></i>
                <h3>Total Queries</h3>
                <p class="value" id="total-queries-count">0</p>
            </div>
            <div class="card">
                <i class="fas fa-users"></i>
                <h3>Total Unique Users</h3>
                <p class="value" id="unique-numbers-count">0</p>
            </div>
            <!-- END OF NEW CARDS -->
        </div>

        <!-- NEW CHART CONTAINER -->
        <div class="chart-container">
            <div class="chart-box">
                <h3>Conversation Success</h3>
                <canvas id="conversion-chart"></canvas>
            </div>
        </div>


    </div>

    <script>
        // Function to fetch and display knowledge file count
        function fetchKnowledgeFilesCount() {
            fetch('../php/fetch_files.php?folder_name=knowledge')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success' && data.files) {
                        document.getElementById('knowledge-files-count').innerText = data.files.length;
                    } else {
                        console.error('Error fetching knowledge files:', data.message);
                    }
                })
                .catch(error => console.error('Error fetching knowledge files:', error));
        }

        // Function to fetch and display instruction file count
        function fetchInstructionFilesCount() {
            fetch('../php/fetch_files.php?folder_name=instruction')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success' && data.files) {
                        document.getElementById('instruction-files-count').innerText = data.files.length;
                    } else {
                        console.error('Error fetching instruction files:', data.message);
                    }
                })
                .catch(error => console.error('Error fetching instruction files:', error));
        }
        
        // Function to fetch and display message statistics
        function fetchMessageStats() {
            fetch('../php/fetch_message_log.php')
                .then(response => response.json())
                .then(data => {
                    if (Array.isArray(data)) {
                        const totalMessages = data.length;
                        const totalReplies = data.filter(msg => msg.reply_message && msg.reply_message.trim() !== '').length;
                        const totalQueries = data.filter(msg => msg.original_message && msg.original_message.trim() !== '').length;
                        
                        const uniqueRecipients = new Set(data.map(msg => msg.recipient));

                        document.getElementById('total-messages-count').innerText = totalMessages;
                        document.getElementById('total-replies-count').innerText = totalReplies;
                        document.getElementById('total-queries-count').innerText = totalQueries;
                        document.getElementById('unique-numbers-count').innerText = uniqueRecipients.size;

                        // Create the donut chart
                        createDonutChart(totalReplies, totalQueries);
                    } else {
                        console.error('Error: Data from message log is not a valid array.');
                    }
                })
                .catch(error => console.error('Error fetching message stats:', error));
        }

        // Function to create the donut chart
        function createDonutChart(totalReplies, totalQueries) {
            const ctx = document.getElementById('conversion-chart').getContext('2d');
            
            const unsuccessfulQueries = totalQueries - totalReplies;

            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['Total Replies', 'Unsuccessful Queries'],
                    datasets: [{
                        data: [totalReplies, unsuccessfulQueries],
                        backgroundColor: [
                            '#4CAF50', // Green for replies
                            '#FF6384'  // Red for unsuccessful queries
                        ],
                        hoverOffset: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'top',
                        },
                        title: {
                            display: true,
                            text: 'Conversation Success Rate'
                        }
                    }
                }
            });
        }

        // Load data when the page is loaded
        document.addEventListener('DOMContentLoaded', () => {
            fetchKnowledgeFilesCount();
            fetchInstructionFilesCount();
            fetchMessageStats();
        });
    </script>

</body>
</html>
