<?php

// ===============================
// 1. AJAX Handler for Filtering & Pagination
// ===============================
function filter_downloads_by_file_category() {
    $slug = sanitize_text_field($_POST['category_slug']);
    $posts_per_page = isset($_POST['posts_per_page']) ? intval($_POST['posts_per_page']) : 10;
    $paged = isset($_POST['paged']) ? intval($_POST['paged']) : 1;
    
    $args = array(
        'post_type' => 'downloads',
        'posts_per_page' => $posts_per_page,
        'orderby' => 'date',
        'order' => 'DESC',
        'paged' => $paged,
    );

    if (!empty($slug) && $slug !== 'all') {
        $args['tax_query'] = array(array(
            'taxonomy' => 'file_category',
            'field'    => 'slug',
            'terms'    => $slug,
        ));
    }

    $query = new WP_Query($args);
    
    ob_start();
    ?>
    <table id="downloads-table" class="table expandable-table w-100 dataTable no-footer" style="width: 100%;" aria-describedby="downloads-table_info">
        <thead>
            <tr>
                <th class="sorting" tabindex="0" aria-controls="downloads-table" rowspan="1" colspan="1" style="width: 20%;">File</th>
                <th class="sorting" tabindex="0" aria-controls="downloads-table" rowspan="1" colspan="1" style="width: 80%;">Details</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $count = 0;
            if ($query->have_posts()) :
                while ($query->have_posts()) : $query->the_post(); 
                    $count++;
                    $post_id = get_the_ID();
                    $file_url = get_post_meta($post_id, '_file_url', true);
                    $download_count = get_post_meta($post_id, '_download_count', true);
                    $file_size = '';
                    if ($file_url) {
                        $headers = @get_headers($file_url, 1);
                        $file_size = isset($headers['Content-Length']) ? size_format($headers['Content-Length']) : '';
                    }
                    $row_class = ($count % 2 == 0) ? 'even' : 'odd';
                    $link = esc_url(get_permalink());
            ?>
            <tr class="<?php echo $row_class; ?> clickable-row" data-href="<?php echo $link; ?>">
                <td class="sorting_1">
                    <img decoding="async" src="<?php echo get_template_directory_uri(); ?>/assets/images/publication.jpg" alt="publication" style="width: 100px;">
                </td>
                <td>
                    <div class="py-1">
                        <small>Downloads: <?php echo esc_html($download_count); ?> | Size: <?php echo esc_html($file_size); ?></small>
                    </div>
                    <h4 class="pub-title"><?php echo get_the_title(); ?></h4>
                    <div class="pub-link">
                        <p><?php the_excerpt(); ?></p>
                    </div>
                </td>
            </tr>
            <?php 
                endwhile;
            else :
            ?>
            <tr>
                <td colspan="2" style="text-align: center;">No downloads found for this category.</td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>
    
    <div class="dataTables_info" id="downloads-table_info" role="status" aria-live="polite">
        Showing <?php echo (($paged - 1) * $posts_per_page) + 1; ?> to <?php echo min($paged * $posts_per_page, $query->found_posts); ?> of <?php echo $query->found_posts; ?> entries
    </div>
    
    <div class="dataTables_paginate paging_simple_numbers" id="downloads-table_paginate">
        <?php
        echo paginate_links(array(
            'total' => $query->max_num_pages,
            'current' => $paged,
            'prev_text' => __('Previous'),
            'next_text' => __('Next'),
            'type' => 'plain',
        ));
        ?>
    </div>
    <?php
    wp_reset_postdata();
    $output = ob_get_clean();
    echo $output;
    wp_die();
}
add_action('wp_ajax_filter_downloads_by_file_category', 'filter_downloads_by_file_category');
add_action('wp_ajax_nopriv_filter_downloads_by_file_category', 'filter_downloads_by_file_category');

// ===============================
// 2. Publications Shortcode
// ===============================
function download_shortcode($atts) {
    $atts = shortcode_atts(array(
        'category' => '',
        'number' => 10,
        'order' => 'DESC',
    ), $atts, 'publication');

    $paged = max(1, get_query_var('paged') ?: 1);
    $posts_per_page = isset($_GET['entries']) ? intval($_GET['entries']) : $atts['number'];

    $args = array(
        'post_type' => 'downloads',
        'posts_per_page' => $posts_per_page,
        'orderby' => 'date',
        'order' => $atts['order'],
        'paged' => $paged,
    );

    if (!empty($atts['category'])) {
        $args['tax_query'] = array(array(
            'taxonomy' => 'file_category',
            'field'    => 'slug',
            'terms'    => $atts['category'],
        ));
    }

    $query = new WP_Query($args);
    ob_start();
    ?>

    <div id="downloads-container">
        <div id="downloads-table_wrapper" class="dataTables_wrapper no-footer">
            <div class="dataTables_length" id="downloads-table_length">
                <label>Show 
                    <select name="downloads-table_length" aria-controls="downloads-table" class="entries-select">
                        <option value="10" <?php selected($posts_per_page, 10); ?>>10</option>
                        <option value="25" <?php selected($posts_per_page, 25); ?>>25</option>
                        <option value="50" <?php selected($posts_per_page, 50); ?>>50</option>
                        <option value="100" <?php selected($posts_per_page, 100); ?>>100</option>
                    </select> entries
                </label>
            </div>
            <div id="downloads-table_filter" class="dataTables_filter">
                <label>Search:<input type="search" class="search-input" placeholder="" aria-controls="downloads-table"></label>
            </div>
            
            <div id="downloads-content">
                <table id="downloads-table" class="table expandable-table w-100 dataTable no-footer" style="width: 100%;" aria-describedby="downloads-table_info">
                    <thead>
                        <tr>
                            <th class="sorting" tabindex="0" aria-controls="downloads-table" rowspan="1" colspan="1" style="width: 20%;">File</th>
                            <th class="sorting" tabindex="0" aria-controls="downloads-table" rowspan="1" colspan="1" style="width: 80%;">Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $count = 0;
                        if ($query->have_posts()) :
                            while ($query->have_posts()) : $query->the_post(); 
                                $count++;
                                $post_id = get_the_ID();
                                $file_url = get_post_meta($post_id, '_file_url', true);
                                $download_count = get_post_meta($post_id, '_download_count', true);
                                $file_size = '';
                                if ($file_url) {
                                    $headers = @get_headers($file_url, 1);
                                    $file_size = isset($headers['Content-Length']) ? size_format($headers['Content-Length']) : '';
                                }
                                $row_class = ($count % 2 == 0) ? 'even' : 'odd';
                                $link = esc_url(get_permalink());
                        ?>
                        <tr class="<?php echo $row_class; ?> clickable-row" data-href="<?php echo $link; ?>">
                            <td class="sorting_1">
                                <img decoding="async" src="<?php echo get_template_directory_uri(); ?>/assets/images/publication.jpg" alt="publication" style="width: 100px;">
                            </td>
                            <td>
                                <div class="py-1">
                                    <small>Downloads: <?php echo esc_html($download_count); ?> | Size: <?php echo esc_html($file_size); ?></small>
                                </div>
                                <h4 class="pub-title"><?php echo get_the_title(); ?></h4>
                                <div class="pub-link">
                                    <p><?php the_excerpt(); ?></p>
                                </div>
                            </td>
                        </tr>
                        <?php 
                            endwhile;
                        else :
                        ?>
                        <tr>
                            <td colspan="2" style="text-align: center;">No downloads found.</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                
                <div class="dataTables_info" id="downloads-table_info" role="status" aria-live="polite">
                    Showing <?php echo (($paged - 1) * $posts_per_page) + 1; ?> to <?php echo min($paged * $posts_per_page, $query->found_posts); ?> of <?php echo $query->found_posts; ?> entries
                </div>
                
                <div class="dataTables_paginate paging_simple_numbers" id="downloads-table_paginate">
                    <?php
                    echo paginate_links(array(
                        'total' => $query->max_num_pages,
                        'current' => $paged,
                        'prev_text' => __('Previous'),
                        'next_text' => __('Next'),
                        'type' => 'plain',
                        'add_args' => array(
                            'entries' => $posts_per_page
                        ),
                    ));
                    ?>
                </div>
            </div>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        var currentCategory = '<?php echo esc_js($atts['category']); ?>';
        var currentPage = <?php echo $paged; ?>;
        var currentEntries = <?php echo $posts_per_page; ?>;

        // Show entries functionality
        $('.entries-select').change(function() {
            var entries = $(this).val();
            currentEntries = entries;
            currentPage = 1; // Reset to first page when changing entries
            
            // Update URL without page reload
            var newUrl = updateQueryStringParameter(window.location.href, 'entries', entries);
            newUrl = removeQueryStringParameter(newUrl, 'paged');
            history.replaceState(null, '', newUrl);
            
            loadDownloads(currentCategory, currentPage, entries);
        });

        // Search functionality
        $('.search-input').keyup(function() {
            var searchText = $(this).val().toLowerCase();
            $('#downloads-table tbody tr').each(function() {
                var rowText = $(this).text().toLowerCase();
                $(this).toggle(rowText.indexOf(searchText) > -1);
            });
        });

        // Pagination click handler
        $(document).on('click', '.page-numbers a', function(e) {
            e.preventDefault();
            var href = $(this).attr('href');
            var pageMatch = href.match(/paged=(\d+)/);
            var entriesMatch = href.match(/entries=(\d+)/);
            
            if (pageMatch) {
                currentPage = parseInt(pageMatch[1]);
            }
            if (entriesMatch) {
                currentEntries = parseInt(entriesMatch[1]);
                $('.entries-select').val(currentEntries);
            }
            
            loadDownloads(currentCategory, currentPage, currentEntries);
        });

        // Make table row clickable
        $('.clickable-row').on('click', function() {
            window.location = $(this).data('href');
        });

        // AJAX function to load downloads
        function loadDownloads(category, page, entries) {
            $.ajax({
                type: 'POST',
                url: '<?php echo admin_url("admin-ajax.php"); ?>',
                data: {
                    action: 'filter_downloads_by_file_category',
                    category_slug: category,
                    paged: page,
                    posts_per_page: entries
                },
                beforeSend: function() {
                    $('#downloads-content').html('<div style="text-align: center; padding: 20px;">Loading...</div>');
                },
                success: function(response) {
                    $('#downloads-content').html(response);
                    
                    // Re-initialize clickable rows
                    $('.clickable-row').on('click', function() {
                        window.location = $(this).data('href');
                    });
                    
                    // Update current page
                    currentPage = page;
                },
                error: function() {
                    $('#downloads-content').html('<div style="text-align: center; padding: 20px; color: red;">Error loading content. Please try again.</div>');
                }
            });
        }

        // Helper functions for URL manipulation
        function updateQueryStringParameter(uri, key, value) {
            var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
            var separator = uri.indexOf('?') !== -1 ? "&" : "?";
            if (uri.match(re)) {
                return uri.replace(re, '$1' + key + "=" + value + '$2');
            } else {
                return uri + separator + key + "=" + value;
            }
        }

        function removeQueryStringParameter(uri, key) {
            return uri
                .replace(new RegExp("([?&])" + key + "=[^&;]+[&;]?"), "$1")
                .replace(new RegExp("([?&])" + key + "=[^&;]+[&;]?"), "$1")
                .replace(/[?&]$/, '');
        }
    });
    </script>

    <?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('publication', 'download_shortcode');

// ===============================
// 3. Downloads Category Menu Shortcode (Keep as is)
// ===============================
function downloads_category_menu_shortcode($atts) {
    $categories = get_terms(array(
        'taxonomy' => 'file_category',
        'hide_empty' => true,
        'orderby' => 'name',
        'parent' => 0,
    ));

    if (empty($categories) || is_wp_error($categories)) {
        return '<div class="downloads-category-menu-notice">No categories available</div>';
    }

    ob_start(); ?>

    <div class="downloads-category-menu">
        <h4 class="category-menu-title">Other Resources</h4>
        <ul class="category-menu-list">
            <?php foreach ($categories as $category): 
            $link = home_url('/' . $category->slug . '/'); ?>
            <li class="category-menu-item">
                <a href="<?php echo esc_url($link); ?>" class="category-menu-link">
                    <span class="category-name"><?php echo esc_html($category->name); ?></span>
                    <span class="category-count">(<?php echo esc_html($category->count); ?>)</span>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>

    <style>
    .downloads-category-menu {
        background: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }
    .category-menu-title {
        font-size: 1.2rem;
        font-weight: 600;
        margin-bottom: 15px;
    }
    .category-menu-list {
        list-style: none;
        padding: 0;
        margin: 0;
    }
    .category-menu-item {
        margin-bottom: 8px;
    }
    .category-menu-link {
        text-decoration: none;
        color: #333;
        display: flex;
        justify-content: space-between;
        padding: 10px;
        border-radius: 5px;
        transition: background 0.3s, color 0.3s;
    }
    .category-menu-link:hover {
        background: #f0f0f0;
        color: #007bff;
    }
    .category-count {
        background: #eee;
        padding: 2px 8px;
        border-radius: 10px;
        font-size: 0.85em;
    }
/* Pagination Wrapper */
.dataTables_paginate.paging_simple_numbers {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 2rem;
    gap: 0.5rem;
    flex-wrap: wrap;
}

/* Pagination Links (Default) */
.dataTables_paginate .page-numbers {
    display: inline-block;
    padding: 0.5rem 0.75rem;
    border: 1px solid #e5e7eb;
    background: #ffffff;
    color: #6b7280;
    font-size: 0.875rem;
    border-radius: 6px;
    text-decoration: none;
    transition: all 0.2s ease;
}

/* Hover Effect */
.dataTables_paginate .page-numbers:hover {
    background: #f3f4f6;
    border-color: #d1d5db;
    color: #374151;
}

/* Current Page */
.dataTables_paginate .page-numbers.current {
    background: #2563eb; /* Blue */
    color: #ffffff;
    border-color: #2563eb;
    cursor: default;
}

/* Previous/Next Buttons */
.dataTables_paginate .prev,
.dataTables_paginate .next {
    font-weight: 600;
}

/* Disabled State */
.dataTables_paginate .disabled {
    opacity: 0.5;
    pointer-events: none;
}

/* Dots (…) */
.dataTables_paginate .dots {
    border: none;
    background: transparent;
    padding: 0.5rem;
    color: #9ca3af;
}

/* Mobile Responsive */
@media (max-width: 768px) {
    .dataTables_paginate.paging_simple_numbers {
        gap: 0.3rem;
    }

    .dataTables_paginate .page-numbers {
        padding: 0.4rem 0.6rem;
        font-size: 0.8rem;
    }
}

    </style>

    <?php
    return ob_get_clean();
}
add_shortcode('downloads_category_menu', 'downloads_category_menu_shortcode');