<?php
function display_pie_chart() {
    ob_start();
    
    // Ensure Chart.js is loaded
    ?>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <?php
    
    $news_args = array(
        'post_type' => array('page'),
        'posts_per_page' => 20,
        'category_name' => 'pie-chart',
    );
    
    $news_query = new WP_Query($news_args);
    
    if ($news_query->have_posts()) : 
        ?>
        <div class="container">
        <div class="row news-card">
            <?php $i = 0; // Counter for unique canvas IDs
            while ($news_query->have_posts()) :
                $news_query->the_post();
                
                // Get the page title as the category label
                $title = get_the_title();
                
                     // Get the page content and clean it
                $content = trim(get_the_content());
                
                // Extract numeric values safely using regex
                preg_match('/\d+/', $content, $matches);
                
                // If a valid number is found, use it; otherwise, set a default value
                $percentage = isset($matches[0]) ? (int) $matches[0] : 50;
                
                // Ensure percentage is within 0-100 range
                if ($percentage < 0 || $percentage > 100) {
                    $percentage = 50; // Assign a safe default value
                }

                $remainingPercentage = 100 - $percentage; // Calculate the remaining space
                
                $i++; // Increment for each unique canvas ID
                ?>
                
                <div class="col-md-4 card card-body mb-3 border-0" data-aos="fade-up">
                    <canvas id="myPieChart<?= $i; ?>" class="pie-chart"></canvas>
                    <a href="<?= esc_url(get_permalink()); ?>">
                        <?php the_content(); ?>
                    </a>
                    <a href="<?= esc_url(get_permalink()); ?>"><h3><?php the_title(); ?></h3></a>

                    <script>
                        document.addEventListener("DOMContentLoaded", function () {
                            var ctx = document.getElementById('myPieChart<?= $i; ?>').getContext('2d');
                            var myPieChart = new Chart(ctx, {
                                type: 'pie',
                                data: {
                                    datasets: [{
                                        data: [<?= $percentage; ?>, <?= $remainingPercentage; ?>], // Use percentage and remaining space
                                        backgroundColor: ['rgb(255, 241, 23)', '#830025'], // Given color and white for the remaining space
                                        borderColor: ['rgb(255, 241, 23)', '#830025'],
                                        borderWidth: [1, 1]
                                    }]
                                },
                                options: {
                                    responsive: true
                                }
                            });
                        });
                    </script>
                </div><!-- col !-->
            
            <?php endwhile;
                wp_reset_postdata();
            else :
                echo 'No news found.';
            endif;
            ?>
        </div><!-- Row !-->
        </div>
        
        <?php
    return ob_get_clean(); // Return the buffered content
}

add_shortcode('pie_chart', 'display_pie_chart');
?>
