<?php
/**
 * JSR Theme - Shortcodes
 * Version: 2.0
 * Security hardened and optimized
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/* =============================================
   1. SERVICES PAGES SHORTCODE
   ============================================= */

/**
 * Displays service pages from a specific category
 * 
 * @param array $atts Shortcode attributes
 * @return string HTML output
 */
function jsr_services_pages_shortcode($atts) {
    $atts = shortcode_atts([
        'category' => 'services',
    ], $atts);

    // Sanitize category slug
    $category = sanitize_title($atts['category']);

    $args = [
        'post_type'      => 'page',
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'tax_query'      => [
            [
                'taxonomy' => 'page_category',
                'field'    => 'slug',
                'terms'    => $category,
            ]
        ]
    ];

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return '';
    }

    // Icons in display order
    $icons = [
        'fa-magnifying-glass-dollar',
        'fa-users',
        'fa-handshake',
        'fa-building',
        'fa-folder-open',
        'fa-tags',
        'fa-money-bill-wave',
        'fa-user-tie',
    ];

    $cards = [];
    $i = 0;

    while ($query->have_posts()) {
        $query->the_post();
        $cards[] = [
            'title' => get_the_title(),
            'link'  => get_permalink(),
            'icon'  => $icons[$i] ?? 'fa-briefcase',
        ];
        $i++;
    }

    wp_reset_postdata();

    ob_start();
    ?>

    <section class="services1-section">
        <div class="services1-container container">
            <!-- TOP SECTION -->
            <div class="services1-top">
                <div class="services1-text">
                    <h2>
                        Delivering sustained outcomes<br>
                        which make a difference
                    </h2>
                    <p>
                        Capitalizing on the real-world experience of our financial advisors
                        and business consultants.
                    </p>
                </div>

                <div class="services1-top-cards">
                    <?php for ($i = 0; $i < 3 && $i < count($cards); $i++): ?>
                        <a href="<?php echo esc_url($cards[$i]['link']); ?>" class="service1-card">
                            <div class="service1-icon">
                                <i class="fa-solid <?php echo esc_attr($cards[$i]['icon']); ?>"></i>
                            </div>
                            <h3><?php echo esc_html($cards[$i]['title']); ?></h3>
                            <span>Read More &gt;&gt;</span>
                        </a>
                    <?php endfor; ?>
                </div>
            </div>

            <!-- BOTTOM SECTION -->
            <?php if (count($cards) > 3): ?>
                <div class="services1-bottom">
                    <?php for ($i = 3; $i < count($cards); $i++): ?>
                        <a href="<?php echo esc_url($cards[$i]['link']); ?>" class="service1-card">
                            <div class="service1-icon">
                                <i class="fa-solid <?php echo esc_attr($cards[$i]['icon']); ?>"></i>
                            </div>
                            <h3><?php echo esc_html($cards[$i]['title']); ?></h3>
                            <span>Read More &gt;&gt;</span>
                        </a>
                    <?php endfor; ?>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <?php
    return ob_get_clean();
}
add_shortcode('services1_pages', 'jsr_services_pages_shortcode');

/* =============================================
   2. IMPACT HERO SHORTCODE
   ============================================= */

/**
 * Displays hero section with animated counters
 */
function jsr_impact_hero_shortcode() {
    static $instance = 0;
    $instance++;
    $uid = 'impact-hero-' . $instance;
    $bg = get_template_directory_uri() . '/assets/images/infrastructure-Samanga-Solutions2.jpg';

    ob_start();
    ?>
    <section id="<?php echo esc_attr($uid); ?>" class="impact-hero" style="background-image:url('<?php echo esc_url($bg); ?>');">
        <div class="impact-overlay"></div>
        <div class="impact-content container">
            <h1>
                Providing <span>SOLUTIONS</span><br> and making a
                <span>DIFFERENCE</span> in <span>EAST <br> AFRICA</span>.
            </h1>

            <div class="impact-stats">
                <div class="stat">
                    <h2 class="counter" data-target="350">0</h2>
                    <p>Projects completed</p>
                </div>
                <div class="stat">
                    <h2 class="counter" data-target="38">0</h2>
                    <p>JSR Experts</p>
                </div>
                <div class="stat">
                    <h2 class="counter" data-target="165">0</h2>
                    <p>Satisfied Customers</p>
                </div>
            </div>
        </div>
    </section>

    <script>
    (function() {
        const section = document.getElementById('<?php echo esc_js($uid); ?>');
        if (!section) return;

        const counters = section.querySelectorAll('.counter');
        let started = false;

        function animateCounters() {
            if (started) return;
            started = true;

            counters.forEach(counter => {
                const target = parseInt(counter.getAttribute('data-target'), 10);
                if (isNaN(target)) {
                    counter.textContent = '0';
                    return;
                }

                let count = 0;
                const step = Math.max(1, target / 120);
                const duration = 2000;
                const interval = 16;
                const increment = target / (duration / interval);
                let current = 0;

                const timer = setInterval(() => {
                    current += increment;
                    if (current >= target) {
                        counter.textContent = target;
                        clearInterval(timer);
                    } else {
                        counter.textContent = Math.floor(current);
                    }
                }, interval);
            });
        }

        const observer = new IntersectionObserver(entries => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    animateCounters();
                    observer.disconnect();
                }
            });
        }, { threshold: 0.4 });

        observer.observe(section);
    })();
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('impact_hero', 'jsr_impact_hero_shortcode');

/* =============================================
   3. INSIGHTS SHORTCODES
   ============================================= */

/**
 * Homepage insights (no pagination)
 */
function jsr_insights_home_shortcode($atts) {
    $atts = shortcode_atts([
        'posts_per_page' => 3,
    ], $atts);

    $args = [
        'post_type'      => 'post',
        'posts_per_page' => absint($atts['posts_per_page']),
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC'
    ];

    $query = new WP_Query($args);

    if (!$query->have_posts()) {
        return '';
    }

    ob_start();
    ?>
    <section class="insights-home">
        <div class="insights-intro">
            <h1 style="font-size: 45px; font-weight: 700; color: var(--jsr-base); margin: 10px 0; line-height: 1.15;">Our Insights</h1>
            <p>We explore some of the latest trends and strategies</p>
        </div>

        <div class="insights-grid">
            <?php while ($query->have_posts()) : $query->the_post(); ?>
                <article class="insight-card">
                    <div class="insight-thumb">
                        <a href="<?php the_permalink(); ?>">
                            <?php if (has_post_thumbnail()) : ?>
                                <?php the_post_thumbnail('large'); ?>
                            <?php else : ?>
                                <img src="<?php echo esc_url(get_template_directory_uri() . '/assets/images/placeholder.jpg'); ?>" alt="Placeholder">
                            <?php endif; ?>
                        </a>
                    </div>
                    <div class="insight-content">
                        <div class="insight-meta"><?php echo esc_html(get_the_date()); ?></div>
                        <h3 class="insight-title">
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        </h3>
                        <div class="insight-excerpt">
                            <?php echo esc_html(wp_trim_words(get_the_excerpt(), 22)); ?>
                        </div>
                        <div class="insight-readmore">
                            <a href="<?php the_permalink(); ?>">Read More</a>
                        </div>
                    </div>
                </article>
            <?php endwhile; ?>
        </div>
    </section>
    <?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('insights_home', 'jsr_insights_home_shortcode');

/**
 * Blog/Insights page with pagination
 */
function jsr_insights_posts_shortcode($atts) {
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;

    $atts = shortcode_atts([
        'posts_per_page' => 6,
        'paged'          => $paged,
    ], $atts);

    $args = [
        'post_type'      => 'post',
        'posts_per_page' => absint($atts['posts_per_page']),
        'paged'          => absint($atts['paged']),
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC'
    ];

    $query = new WP_Query($args);

    ob_start();
    ?>
    <section class="insights-page">
        <div class="insights-intro">
            <p>
                Welcome to <strong>JSR Blog Centre,</strong><br>
                A collection of stories about our people, our capabilities, our research, and the ever-changing face of our firm.
            </p>
        </div>

        <?php if ($query->max_num_pages > 1) : ?>
            <div class="insights-pagination insights-pagination-top">
                <?php echo paginate_links([
                    'total'     => $query->max_num_pages,
                    'current'   => max(1, $atts['paged']),
                    'prev_text' => '&laquo;',
                    'next_text' => '&raquo;'
                ]); ?>
            </div>
        <?php endif; ?>

        <div class="insights-grid">
            <?php if ($query->have_posts()) : ?>
                <?php while ($query->have_posts()) : $query->the_post(); ?>
                    <article class="insight-card">
                        <div class="insight-thumb">
                            <a href="<?php the_permalink(); ?>">
                                <?php if (has_post_thumbnail()) : ?>
                                    <?php the_post_thumbnail('large'); ?>
                                <?php else : ?>
                                    <img src="<?php echo esc_url(get_template_directory_uri() . '/assets/images/placeholder.jpg'); ?>" alt="Placeholder">
                                <?php endif; ?>
                            </a>
                        </div>
                        <div class="insight-content">
                            <div class="insight-meta"><?php echo esc_html(get_the_date()); ?></div>
                            <h3 class="insight-title">
                                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            </h3>
                            <div class="insight-excerpt">
                                <?php echo esc_html(wp_trim_words(get_the_excerpt(), 22)); ?>
                            </div>
                            <div class="insight-readmore">
                                <a href="<?php the_permalink(); ?>">Read More</a>
                            </div>
                        </div>
                    </article>
                <?php endwhile; ?>
            <?php else : ?>
                <p>No insights found.</p>
            <?php endif; ?>
        </div>
    </section>
    <?php
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('insights_posts', 'jsr_insights_posts_shortcode');

/* =============================================
   4. CORE VALUES SHORTCODE
   ============================================= */

function jsr_core_values_shortcode() {
    $bg = get_template_directory_uri() . '/assets/images/who-we-are-cores-bg.jpg';
    $values = [
        [
            'icon' => 'professionalism.png',
            'title' => 'Professionalism',
            'desc' => 'we adhere to the highest professional standards and prioritize our clients\' interests'
        ],
        [
            'icon' => 'integrity.png',
            'title' => 'Integrity',
            'desc' => 'we observe high ethical standards and build enduring relationships based on trust'
        ],
        [
            'icon' => 'innovation.png',
            'title' => 'Innovation',
            'desc' => 'we anticipate our clients\' needs and reshape markets.'
        ],
        [
            'icon' => 'excellence.png',
            'title' => 'Excellence',
            'desc' => 'We aim to be great, not just good and create an unrivalled environment for the growth of all our people'
        ]
    ];

    ob_start();
    ?>
    <section class="core-values-section" style="background-image:url('<?php echo esc_url($bg); ?>');">
        <div class="core-values-overlay"></div>
        <div class="core-values-container container">
            <h2 class="core-values-title">Our Core Values</h2>
            <span class="core-values-line"></span>
            <div class="core-values-grid">
                <?php foreach ($values as $value) : ?>
                    <div class="core-value-card">
                        <div class="core-value-header">
                            <img src="<?php echo esc_url(get_template_directory_uri() . '/assets/images/' . $value['icon']); ?>" alt="<?php echo esc_attr($value['title']); ?>">
                            <h3><?php echo esc_html($value['title']); ?></h3>
                        </div>
                        <div class="core-value-body">
                            <p><?php echo esc_html($value['desc']); ?></p>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </section>
    <?php
    return ob_get_clean();
}
add_shortcode('core_values', 'jsr_core_values_shortcode');

/* =============================================
   5. DOWNLOADS SHORTCODE
   ============================================= */

/**
 * AJAX handler for download counts
 */
function jsr_update_download_count() {
    // Verify nonce for security
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'jsr_download_nonce')) {
        wp_die('Security check failed');
    }

    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    
    if (!$post_id) {
        wp_die('Invalid post ID');
    }

    $current_count = (int) get_post_meta($post_id, '_download_count', true);
    update_post_meta($post_id, '_download_count', $current_count + 1);
    
    wp_die('success');
}
add_action('wp_ajax_update_download_count', 'jsr_update_download_count');
add_action('wp_ajax_nopriv_update_download_count', 'jsr_update_download_count');

/**
 * Services & Downloads shortcode
 */
function jsr_services_downloads_shortcode() {
    wp_enqueue_script('jquery');
    
    ob_start();
    ?>
    <div class="jsr-section">
        <h2 class="jsr-title" style="margin-top:0;">Downloads</h2>
        <div class="jsr-downloads">
            <!-- Header controls -->
            <div class="jsr-downloads-header">
                <div class="jsr-length-wrapper">
                    <label>
                        Display 
                        <select id="jsr-length" name="jsr-length" aria-controls="jsr-downloads">
                            <option value="10" selected>10</option>
                            <option value="25">25</option>
                            <option value="50">50</option>
                            <option value="100">100</option>
                        </select> 
                        downloads per page
                    </label>
                </div>
                <div class="jsr-search">
                    <label>
                        Search: 
                        <input type="text" id="jsr-search" placeholder="Search downloads..." aria-controls="jsr-downloads">
                    </label>
                </div>
            </div>

            <!-- Table head -->
            <div class="jsr-downloads-head">
                <div class="sorting sorting_asc">Title</div>
                <div class="sorting">Category</div>
                <div class="sorting hidden-sm hidden-xs">Last Updated</div>
                <div class="sorting">Downloads</div>
                <div>Action</div>
            </div>

            <?php
            $downloads = get_posts([
                'post_type'      => 'downloads',
                'posts_per_page' => -1,
                'post_status'    => 'publish',
                'orderby'        => 'date',
                'order'          => 'DESC'
            ]);

            $nonce = wp_create_nonce('jsr_download_nonce');
            $total = count($downloads);
            ?>

            <div id="jsr-downloads-container">
                <?php foreach ($downloads as $index => $download) : 
                    $file_url = get_post_meta($download->ID, '_file_url', true);
                    $external_file = get_post_meta($download->ID, '_external_file', true);
                    $download_count = (int) get_post_meta($download->ID, '_download_count', true);
                    
                    // Get file size safely
                    $file_size = '';
                    if ($file_url && filter_var($file_url, FILTER_VALIDATE_URL)) {
                        $headers = @get_headers($file_url, 1);
                        if ($headers && isset($headers['Content-Length'])) {
                            $file_size = size_format((int) $headers['Content-Length']);
                        }
                    }
                    
                    // Get categories
                    $categories = get_the_terms($download->ID, 'file_category');
                    $category_list = '';
                    if ($categories && !is_wp_error($categories)) {
                        $category_names = wp_list_pluck($categories, 'name');
                        $category_list = esc_html(implode(', ', $category_names));
                    }
                    
                    // Determine download file
                    $download_file = $external_file ?: $file_url;
                    ?>
                    
                    <div class="jsr-download-row" 
                         data-title="<?php echo esc_attr($download->post_title); ?>" 
                         data-category="<?php echo esc_attr($category_list); ?>">
                        <div class="title __dt_col __dt_col_title">
                            <strong><?php echo esc_html($download->post_title); ?></strong>
                            <?php if ($file_size) : ?>
                                <span class="file-size">(<?php echo esc_html($file_size); ?>)</span>
                            <?php endif; ?>
                        </div>
                        <div class="category"><?php echo $category_list ?: 'Uncategorized'; ?></div>
                        <div class="date hidden-sm hidden-xs"><?php echo esc_html(get_the_date('F j, Y', $download)); ?></div>
                        <div class="download-count"><?php echo esc_html($download_count); ?></div>
                        <div class="download">
                            <?php if ($download_file && filter_var($download_file, FILTER_VALIDATE_URL)) : ?>
                                <a class="download-btn" 
                                   href="<?php echo esc_url($download_file); ?>" 
                                   download="<?php echo esc_attr(basename($download_file)); ?>" 
                                   target="_blank"
                                   data-post-id="<?php echo esc_attr($download->ID); ?>"
                                   data-nonce="<?php echo esc_attr($nonce); ?>">
                                    Download
                                </a>
                            <?php else : ?>
                                <span class="no-file">No file available</span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Footer -->
            <div class="jsr-footer">
                <span>Showing 1 to <?php echo esc_html($total); ?> of <?php echo esc_html($total); ?> downloads</span>
                <div class="jsr-pagination">
                    <a class="prev">Previous</a>
                    <span class="current">1</span>
                    <a class="next">Next</a>
                </div>
            </div>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        // Search functionality
        $('#jsr-search').on('keyup', function() {
            var searchTerm = $(this).val().toLowerCase();
            $('.jsr-download-row').each(function() {
                var title = $(this).data('title').toLowerCase();
                var category = $(this).data('category').toLowerCase();
                $(this).toggle(title.includes(searchTerm) || category.includes(searchTerm));
            });
        });

        // Download count tracking
        $('.download-btn').on('click', function(e) {
            var postId = $(this).data('post-id');
            var nonce = $(this).data('nonce');
            
            if (postId) {
                $.ajax({
                    url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                    method: 'POST',
                    data: {
                        action: 'update_download_count',
                        post_id: postId,
                        nonce: nonce
                    },
                    success: function() {
                        var countElement = $(e.target).closest('.jsr-download-row').find('.download-count');
                        var currentCount = parseInt(countElement.text()) || 0;
                        countElement.text(currentCount + 1);
                    }
                });
            }
        });
    });
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('jsr_services_downloads', 'jsr_services_downloads_shortcode');

/* =============================================
   6. PUBLICATIONS POST TYPE
   ============================================= */

function jsr_register_publication_post_type() {
    register_post_type('publication', [
        'labels' => [
            'name'          => 'Publications',
            'singular_name' => 'Publication',
            'add_new'       => 'Add New Publication',
            'add_new_item'  => 'Add New Publication',
            'edit_item'     => 'Edit Publication',
            'new_item'      => 'New Publication',
            'view_item'     => 'View Publication',
            'search_items'  => 'Search Publications',
            'not_found'     => 'No publications found',
        ],
        'public'        => true,
        'has_archive'   => true,
        'rewrite'       => ['slug' => 'publications'],
        'supports'      => ['title', 'editor', 'thumbnail', 'excerpt'],
        'show_in_rest'  => true,
        'menu_icon'     => 'dashicons-media-document',
    ]);
}
add_action('init', 'jsr_register_publication_post_type');

function jsr_publication_file_metabox($post) {
    wp_nonce_field('jsr_save_publication_file', 'jsr_publication_file_nonce');
    $value = get_post_meta($post->ID, 'file', true);
    ?>
    <p>
        <label for="jsr_publication_file">PDF File URL</label>
    </p>
    <input type="url" id="jsr_publication_file" name="jsr_publication_file" 
           value="<?php echo esc_url($value); ?>" style="width:100%" 
           placeholder="https://example.com/file.pdf" />
    <p style="margin-top:6px;font-size:12px;color:#555">
        Upload the PDF in Media Library and paste the file URL here.
    </p>
    <?php
}

function jsr_save_publication_file($post_id) {
    // Verify nonce
    if (!isset($_POST['jsr_publication_file_nonce']) || 
        !wp_verify_nonce($_POST['jsr_publication_file_nonce'], 'jsr_save_publication_file')) {
        return;
    }
    
    // Check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    // Check permissions
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // Save file URL
    if (isset($_POST['jsr_publication_file'])) {
        $file_url = esc_url_raw($_POST['jsr_publication_file']);
        if ($file_url) {
            update_post_meta($post_id, 'file', $file_url);
        } else {
            delete_post_meta($post_id, 'file');
        }
    }
}
add_action('save_post_publication', 'jsr_save_publication_file');

/* =============================================
   7. TEAM POST TYPE
   ============================================= */

function jsr_register_team_post_type() {
    register_post_type('team', [
        'labels' => [
            'name'          => 'Team',
            'singular_name' => 'Team Member',
            'add_new'       => 'Add Team Member',
            'add_new_item'  => 'Add New Team Member',
            'edit_item'     => 'Edit Team Member',
            'new_item'      => 'New Team Member',
            'view_item'     => 'View Team Member',
            'search_items'  => 'Search Team Members',
            'not_found'     => 'No team members found',
        ],
        'public'        => true,
        'has_archive'   => false,
        'rewrite'       => ['slug' => 'team'],
        'supports'      => ['title', 'editor', 'thumbnail', 'excerpt'],
        'show_in_rest'  => true,
        'menu_icon'     => 'dashicons-groups',
    ]);
}
add_action('init', 'jsr_register_team_post_type');

/* =============================================
   8. CAREER CENTER SHORTCODE
   ============================================= */

function jsr_career_center_shortcode() {
    $args = [
        'post_type'      => 'downloads',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'tax_query'      => [
            [
                'taxonomy' => 'file_category',
                'field'    => 'slug',
                'terms'    => 'jobs',
            ],
        ],
    ];
    
    $query = new WP_Query($args);
    $nonce = wp_create_nonce('jsr_download_nonce');
    
    ob_start();
    ?>
    <div class="jsr-cc-wrap">
        <p class="jsr-cc-intro">
            Welcome to <strong>JSR Career Centre</strong><br>
            Browse through a collection of available job openings, and kickstart your career with us.
        </p>

        <form class="jsr-cc-toolbar" id="jsr-filter-form">
            <div class="jsr-cc-row">
                <div class="row">
                    <div class="col-lg-6 col-md-12 mb-2">
                        <input type="search" id="jsr-search" placeholder="Search Keyword..." class="form-control">
                    </div>
                    <div class="col-lg-2 col-md-4 mb-2">
                        <select id="jsr-orderby" class="custom-select">
                            <option value="" disabled selected>Order By:</option>
                            <option value="date">Publish Date</option>
                            <option value="title">Title</option>
                            <option value="downloads">Downloads</option>
                        </select>
                    </div>
                    <div class="col-lg-2 col-md-4 mb-2">
                        <select id="jsr-order" class="custom-select">
                            <option value="" disabled selected>Order:</option>
                            <option value="DESC">Descending</option>
                            <option value="ASC">Ascending</option>
                        </select>
                    </div>
                    <div class="col-lg-2 col-md-4 mb-2">
                        <button type="submit" class="btn btn-info btn-block">Apply Filter</button>
                    </div>
                </div>
            </div>
        </form>

        <div class="jsr-cc-list" id="jsr-job-list">
            <?php if ($query->have_posts()) : ?>
                <?php while ($query->have_posts()) : $query->the_post();
                    $file_url = get_post_meta(get_the_ID(), '_file_url', true);
                    $external_file = get_post_meta(get_the_ID(), '_external_file', true);
                    $download_count = (int) get_post_meta(get_the_ID(), '_download_count', true);
                    $download_link = $external_file ?: $file_url;
                    
                    // Get file size safely
                    $file_size = '';
                    if ($file_url && filter_var($file_url, FILTER_VALIDATE_URL)) {
                        $headers = @get_headers($file_url, 1);
                        if ($headers && isset($headers['Content-Length'])) {
                            $file_size = size_format((int) $headers['Content-Length']);
                        }
                    }
                ?>
                    <div class="jsr-cc-item"
                         data-title="<?php echo esc_attr(get_the_title()); ?>"
                         data-date="<?php echo esc_attr(get_the_date('Y-m-d')); ?>"
                         data-downloads="<?php echo esc_attr($download_count); ?>">
                        <div class="jsr-cc-media">
                            <div class="jsr-cc-icon">
                                <img src="<?php echo esc_url(get_template_directory_uri() . '/assets/images/pdf.svg'); ?>" alt="PDF">
                            </div>
                            <div class="jsr-cc-content">
                                <h3>
                                    <?php the_title(); ?>
                                    <span style="font-size:8pt;font-weight:300" class="text-muted ml-4">
                                        <i class="fas fa-hdd mr-1"></i> <?php echo esc_html($file_size); ?>
                                        <i class="ml-3 far fa-arrow-alt-circle-down mr-1"></i> <?php echo esc_html($download_count); ?> downloads
                                    </span>
                                </h3>
                            </div>
                            <div class="jsr-cc-action">
                                <?php if ($download_link && filter_var($download_link, FILTER_VALIDATE_URL)) : ?>
                                    <a href="<?php echo esc_url($download_link); ?>"
                                       class="jsr-cc-btn jsr-download"
                                       data-post="<?php echo esc_attr(get_the_ID()); ?>"
                                       data-nonce="<?php echo esc_attr($nonce); ?>"
                                       download>
                                        Download
                                    </a>
                                <?php else : ?>
                                    <span class="no-file">No file available</span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
                <?php wp_reset_postdata(); ?>
            <?php else : ?>
                <p>No job postings available.</p>
            <?php endif; ?>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($) {
        $('#jsr-filter-form').on('submit', function(e) {
            e.preventDefault();
            
            var keyword = $('#jsr-search').val().toLowerCase();
            var orderBy = $('#jsr-orderby').val();
            var order = $('#jsr-order').val();
            var items = $('#jsr-job-list .jsr-cc-item').get();
            
            // Filter
            items.forEach(function(item) {
                var title = $(item).data('title').toLowerCase();
                $(item).toggle(title.includes(keyword));
            });
            
            // Sort
            items.sort(function(a, b) {
                var A, B;
                
                switch(orderBy) {
                    case 'title':
                        A = $(a).data('title').toLowerCase();
                        B = $(b).data('title').toLowerCase();
                        break;
                    case 'downloads':
                        A = parseInt($(a).data('downloads'), 10);
                        B = parseInt($(b).data('downloads'), 10);
                        break;
                    default:
                        A = new Date($(a).data('date'));
                        B = new Date($(b).data('date'));
                }
                
                if (order === 'ASC') {
                    return A > B ? 1 : -1;
                } else {
                    return A < B ? 1 : -1;
                }
            });
            
            $.each(items, function(i, item) {
                $('#jsr-job-list').append(item);
            });
        });
        
        // Download count tracking
        $('.jsr-download').on('click', function(e) {
            var postId = $(this).data('post');
            var nonce = $(this).data('nonce');
            
            $.ajax({
                url: '<?php echo esc_url(admin_url('admin-ajax.php')); ?>',
                method: 'POST',
                data: {
                    action: 'update_download_count',
                    post_id: postId,
                    nonce: nonce
                }
            });
        });
    });
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('jsr_career_center', 'jsr_career_center_shortcode');

/* =============================================
   9. CONTACT MAP SHORTCODE
   ============================================= */

function jsr_contact_map_shortcode() {
    ob_start();
    ?>
    <style>
        .contact-wrap {
            margin: 3rem auto;
            padding: 0 .75rem;
            font-family: 'Kumbh Sans', sans-serif;
        }
        .contact-row {
            display: flex;
            flex-wrap: wrap;
        }
        .contact-left {
            flex: 0 0 41.666%;
            max-width: 41.666%;
        }
        .contact-right {
            flex: 0 0 58.333%;
            max-width: 58.333%;
        }
        .contact-title {
            color: #8dafdc;
            font-size: 32px;
            font-weight: 700;
        }
        .contact-sub {
            color: #0e125a;
            font-size: 20px;
            font-weight: 700;
        }
        .contact-box {
            margin: 15px 0;
            border-left: 4px solid #8dafdc;
            padding-left: 15px;
        }
        .contact-box strong {
            display: block;
            margin-bottom: 5px;
        }
        @media (max-width: 768px) {
            .contact-left, .contact-right {
                flex: 0 0 100%;
                max-width: 100%;
            }
        }
    </style>
    
    <div class="contact-wrap">
        <div class="contact-row">
            <div class="contact-left">
                <p class="contact-title">Let's Get in Touch</p>
                <p class="contact-sub">Do you have questions? Reach out to us using the contact info below.</p>
                <div class="contact-box">
                    <strong>Physical Address:</strong>
                    2nd Floor, Regency Plaza, Plot 30 Lugogo By-Pass Naguru<br>
                    P.O. Box 22934 Kampala, Uganda
                </div>
                <div class="contact-box">
                    <strong>Tel Contact:</strong>
                    +256 772 703444 / +256 786 624855
                </div>
                <div class="contact-box">
                    <strong>Write to Us:</strong>
                    <a style="color:var(--jsr-primary); font-weight:500" href="mailto:info@jsamuelrichards.com">info@jsamuelrichards.com</a>
                </div>
            </div>
            <div class="contact-right">
                <iframe id="contactMap" 
                        src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d15959.009193807431!2d32.6064204!3d0.329614!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0xd8814ed18004fc3d!2sJ.%20Samuel%20Richards!5e0!3m2!1sen!2scz!4v1646211640508!5m2!1sen!2scz" 
                        style="border:0; width:100%; height:450px" 
                        loading="lazy" 
                        allowfullscreen>
                </iframe>
            </div>
        </div>
    </div>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Fix for iframe reload issue
        var mapFrame = document.getElementById('contactMap');
        if (mapFrame && mapFrame.src) {
            mapFrame.src = mapFrame.src;
        }
    });
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('contact_map_section', 'jsr_contact_map_shortcode');