<?php 
function alldownloads_shortcode($atts) {
    // Define shortcode attributes
    $atts = shortcode_atts(
        array(
            'category' => '', // Default to empty string if not specified
            'number' => 4, // Default number of posts per page
            'order' => 'DESC', // Default Descending order
        ),
        $atts,
        'downloads'
    );

    // Custom query to retrieve Downloads
    $downloads_args = array(
        'post_type' => 'downloads',
        'posts_per_page' => $atts['number'],
        'orderby' => 'date',
        'order' => $atts['order'],
    );

    // Check if category attribute is provided and not empty
    if (!empty($atts['category'])) {
        $downloads_args['tax_query'] = array(
            array(
                'taxonomy' => 'file_category',
                'field' => 'slug',
                'terms' => $atts['category'],
            ),
        );
    }

    $downloads_query = new WP_Query($downloads_args);

    // Start output buffer
    ob_start();
    
    ?>

<div class="row publications">
    <?php
    // Loop through the downloads and output table rows
    while ($downloads_query->have_posts()) : $downloads_query->the_post();
        $post_id = get_the_ID();

        $file_url = get_post_meta($post_id, '_file_url', true);
        $file_size = get_post_meta($post_id, '_file_size', true);
        $downloadDate = get_post_meta($post_id, '_date', true);

        // Get the file size
        $file_size = '';
        if ($file_url) {
            $headers = get_headers($file_url, 1);
            $file_size = isset($headers['Content-Length']) ? size_format($headers['Content-Length']) : '';
        }
        ?>
        <div class="col-xl-3 col-lg-3 col-sm-6">
            <div class="pub-item">
            <div class="pdf-thumbnail">
                <a href="<?= esc_url(get_permalink()); ?>">
                <?php // Display the post thumbnail
                if (has_post_thumbnail()) {
                    the_post_thumbnail();
                } else {
                    echo '<img src="' . get_template_directory_uri() . '/assets/images/default-featured.jpg" alt="HPLNOU" class="img-fluid"/>';
                }
                ?>
                </a>
            </div><!-- thumbnail !-->
            <div class="pub-meta">
            <a href="<?= esc_url(get_permalink()); ?>"><h4 class="pub-title"><?php the_title(); ?></h4></a>
            <span class="pub-date"><strong> <i class="bi bi-calendar-check"></i> Published: </strong><?= $downloadDate; ?> | <strong><i class="bi bi-file-earmark-pdf"></i> File Size: </strong><?= $file_size; ?> </span> <br />
            <div class="pub-link"><a href="<?= $file_url; ?>" target="_blank" onclick="updateDownloadCount(<?= $post_id; ?>)">View/Download </a></div>
            </div>
            </div>
        </div>
    <?php endwhile; ?>
</div>

<script>
    function updateDownloadCount(post_id) {
        jQuery.ajax({
            type: 'POST',
            url: '<?php echo admin_url("admin-ajax.php"); ?>',
            data: {
                action: 'update_download_count',
                post_id: post_id
            },
            success: function(response) {
                // Optionally handle success response
                console.log('Download count updated successfully.');
            }
        });
    }
</script>
    <?php
    // Clean output buffer and return content
    return ob_get_clean();
}
add_shortcode('home-publications', 'alldownloads_shortcode');
?>