<?php

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * AJAX Handler for Load More Projects
 */
function aump_load_more_projects() {
    if (
        !isset($_POST['nonce']) || 
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'aump_load_more_nonce')
    ) {
        die('Permission Denied');
    }

    // Sanitize and validate inputs
    $category = isset($_POST['category']) 
        ? absint(wp_unslash($_POST['category'])) 
        : 0;

    $paged = isset($_POST['page']) 
        ? max(1, intval($_POST['page'])) 
        : 1;

    $posts_per_page = get_option('aump_posts_per_page', 6); // Fetch from settings

    $args = [
        'post_type'      => 'aump_portfolio',
        'posts_per_page' => $posts_per_page,
        'paged'          => $paged,
    ];

    if (!empty($category)) {
        $args['tax_query'] = [
            [
                'taxonomy' => 'aump_portfolio_category',
                'field'    => 'term_id',
                'terms'    => [$category],
                'operator' => 'IN',
            ]
        ];
    }

    $query    = new WP_Query($args);
    $has_more = ($paged < $query->max_num_pages);

    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();

            $image_size         = get_option('aump_thumbnail_size', 'full');
            $image_url          = wp_get_attachment_image_url(get_post_thumbnail_id(), $image_size);
            $desc_limit         = get_option('aump_desc_word_limit', 15);
            $description        = get_the_excerpt();
            $short_description  = esc_html(wp_trim_words($description, $desc_limit, '...'));
            $displaybtn         = get_option('aump_show_open_button') ? 'block' : 'none';
            $details_button_text = get_option('aump_open_button_text', 'See Details');

            echo '<a href="' . esc_url(get_permalink()) . '" class="aump_wrapper-link-custom">';
            echo '    <div class="aump_project type-project status-publish et_pb_portfolio_item">';
            echo '        <span class="aump_portfolio_image">';
            if ($image_url) {
                echo '            <img src="' . esc_url($image_url) . '" alt="' . esc_attr(get_the_title()) . '">';
            }
            echo '        </span>';

            echo '        <a href="' . esc_url(get_permalink()) . '" class="aump_portfolio-details-button" style="display:' . esc_attr($displaybtn) . ';">' . esc_html($details_button_text) . '</a>';
            
            if (get_option('aump_show_title')) {
                echo '        <h3 class="aump_et_pb_module_header">' . esc_html(get_the_title()) . '</h3>';
            }
            
            if (get_option('aump_show_description') && !empty($short_description)) {
                echo '        <p class="aump_portfolio-description">' . esc_html($short_description) . '</p>';
            }

            echo '    </div>';
            echo '</a>';
        }
    }

    if (!$has_more) {
        echo '<span class="aump_no-more" style="display: none;"></span>';
    }

    wp_reset_postdata();
    die();
}

add_action('wp_ajax_aump_load_more', 'aump_load_more_projects');
add_action('wp_ajax_nopriv_aump_load_more', 'aump_load_more_projects');

/**
 * Category Filter Shortcode
 */
function aump_category_filter_shortcode() {
    ob_start();

    $enable_category_filter = get_option('aump_enable_category_filter', true);
    $load_more_text         = get_option('aump_load_more_button_text', 'Load More Items');

    if ($enable_category_filter) {
        echo '<div id="aump_category-filter">';
        
        $terms = get_terms([
            'taxonomy'   => 'aump_portfolio_category',
            'orderby'    => 'name',
            'hide_empty' => true,
        ]);

        if (!empty($terms) && !is_wp_error($terms)) {
            echo '<span class="aump_category-filter aump-all-filter" data-category="">' . esc_html__('All', 'advanced-universal-modern-portfolio-and-gallery') . '</span>';
            
            foreach ($terms as $term) {
                echo '<span class="aump_category-filter" data-category="' . esc_attr($term->term_id) . '">' . esc_html($term->name) . '</span> ';
            }
        }
        
        echo '</div>';
    }

    echo '<div class="aump_et_pb_filterable_portfolio_grid">';
    echo '    <div id="aump_projects-container" class="aump_et_pb_portfolio_items"></div>';
    echo '</div>';

    $display = get_option('aump_show_load_more_button') ? 'inline-block' : 'none';

    echo '<div class="aump_load-more-button-wrapper">';
    echo '    <button id="aump_load-more-btn" style="display:' . esc_attr($display) . ';">' . esc_html($load_more_text) . '</button>';
    echo '</div>';

    return ob_get_clean();
}
add_shortcode('aump_portfolio', 'aump_category_filter_shortcode');