<?php

function aurora_lite_load_more_posts() {
    if (!isset($_POST['security']) || !wp_verify_nonce($_POST['security'], 'aurora_lite_load_more_nonce')) {
        wp_send_json_error(array('message' => 'Security check failed'), 403);
    }

    $query_vars = isset($_POST['query_vars']) ? json_decode(stripslashes($_POST['query_vars']), true) : array();

    if (empty($query_vars) || !is_array($query_vars)) {
        wp_send_json_error(array('message' => 'Invalid query parameters'), 400);
    }

    $allowed_keys = [
        'post_type', 'post_status', 'cat', 'tag', 'tag_id',
        'author', 'year', 'monthnum', 'day', 'orderby', 'order',
        'posts_per_page', 'paged', 's', 'tax_query', 'meta_query',
        'category_name', 'tag_slug__in', 'ignore_sticky_posts',
    ];

    $query_vars = array_intersect_key( $query_vars, array_flip( $allowed_keys ) );

    $query_vars['post_status']         = 'publish';
    $query_vars['ignore_sticky_posts'] = true;
    $query_vars['paged']               = isset($_POST['paged']) ? absint($_POST['paged']) : 1;

    $posts_per_page = get_theme_mod('aurora_lite_posts_per_page', 12);
    if ($posts_per_page > 0) {
        $query_vars['posts_per_page'] = $posts_per_page;
    }

    $query = new WP_Query($query_vars);

    if ($query->have_posts()) {
        $archive_layout = get_theme_mod('aurora_lite_archive_layout', 'Default');
        $ajax_template  = get_template_directory() . '/template-parts/layouts/archives/ajax/' . $archive_layout . '.php';

        if (file_exists($ajax_template)) {
            ob_start();
            include $ajax_template;
            $content = ob_get_clean();

            wp_reset_postdata();
            wp_send_json_success(array('content' => $content));
        } else {
            wp_send_json_error(array('message' => 'Template not found'), 404);
        }
    } else {
        wp_send_json_error(array('message' => 'No more posts'), 404);
    }
}
add_action('wp_ajax_aurora_lite_load_more', 'aurora_lite_load_more_posts');
add_action('wp_ajax_nopriv_aurora_lite_load_more', 'aurora_lite_load_more_posts');


function aurora_lite_enqueue_load_more_js() {
    if (!is_singular() && !is_404()) {
        global $wp_query;
        
        $load_more_js = get_template_directory() . '/assets/js/load-more.js';
        wp_enqueue_script(
            'aurora-lite-load-more',
            get_template_directory_uri() . '/assets/js/load-more.js',
            array('jquery'),
            file_exists( $load_more_js ) ? filemtime( $load_more_js ) : false,
            true
        );

        wp_localize_script('aurora-lite-load-more', 'aurora_lite_load_more', array(
            'ajaxurl'     => admin_url('admin-ajax.php'),
            'nonce'       => wp_create_nonce('aurora_lite_load_more_nonce'),
            'query_vars'  => json_encode($wp_query->query_vars),
            'current_page'=> max(1, get_query_var('paged')),
            'max_pages'   => $wp_query->max_num_pages
        ));
    }
}
add_action('wp_enqueue_scripts', 'aurora_lite_enqueue_load_more_js', 9);


function aurora_lite_use_masonry() {

    $aurora_lite_masonry = ['Default'];
    $current_layout = get_theme_mod('aurora_lite_archive_layout', 'Default');
    $masonry_enabled = get_theme_mod('aurora_lite_archive_masonry_enabled', false);

    if (!in_array($current_layout, $aurora_lite_masonry, true)) {
        return false;
    }
    
    if (!$masonry_enabled) {
        return false;
    }

    return true;
}


function aurora_lite_enqueue_masonry_script() {
    if (!aurora_lite_use_masonry()) { return; }
    
    wp_enqueue_script('masonry');
    wp_enqueue_script('imagesloaded');
    
    $masonry_js = get_template_directory() . '/assets/js/masonry-init.js';
    wp_enqueue_script(
        'aurora-lite-masonry-init',
        get_template_directory_uri() . '/assets/js/masonry-init.js',
        ['jquery', 'masonry', 'imagesloaded'],
        file_exists( $masonry_js ) ? filemtime( $masonry_js ) : false,
        true
    );
    
    wp_localize_script('aurora-lite-load-more', 'aurora_lite_masonry_config', [
        'enabled' => true
    ]);
}
add_action('wp_enqueue_scripts', 'aurora_lite_enqueue_masonry_script');


function aurora_lite_fix_query_vars($query) {
    if ( ! is_admin() && $query->is_main_query() && ( is_archive() || is_search() || is_author() ) ) {
        $posts_per_page = (int) get_theme_mod('aurora_lite_posts_per_page', 16);
        $query->set('posts_per_page', $posts_per_page === 0 ? -1 : $posts_per_page);
    }
}
add_action('pre_get_posts', 'aurora_lite_fix_query_vars');


function aurora_lite_get_archive_query() {
    $paged = max(1, absint(get_query_var('paged')));
    $posts_per_page = (int) get_theme_mod('aurora_lite_posts_per_page', 16);

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => $posts_per_page === 0 ? -1 : $posts_per_page,
        'paged'          => $paged,
    );

    return new WP_Query($args);
}


function aurora_lite_no_content_message() {
    if ( have_posts() ) {
        return;
    }

    if ( is_search() ) {
        echo '<p class="no-results">' . esc_html__( 'No results found.', 'aurora-lite' ) . '</p>';
    } else {
        echo '<p class="no-posts">' . esc_html__( 'No posts found.', 'aurora-lite' ) . '</p>';
    }
}


function aurora_lite_paginate($query) {
    if (!$query || !($query instanceof WP_Query)) {
        return;
    }

    if (! (is_archive() || is_search() || is_author()) ) {
        return;
    }

    $posts_per_page   = get_theme_mod('aurora_lite_posts_per_page', 16);
    $show_more_option = get_theme_mod('aurora_lite_show_more_option', 'pagination');
    $total_pages      = $query->max_num_pages;

    if ($posts_per_page == 0 || $total_pages <= 1) {
        return;
    }

    if ($show_more_option === 'pagination') {
        echo '<div class="pagination">';
        echo paginate_links([
            'base'      => str_replace(999999999, '%#%', esc_url(get_pagenum_link(999999999))),
            'format'    => '?paged=%#%',
            'total'     => $total_pages,
            'current'   => max(1, get_query_var('paged', 1)),
            'mid_size'  => 2,
            'prev_text' => __('←', 'aurora-lite'),
            'next_text' => __('→', 'aurora-lite'),
        ]);
        echo '</div>';
    } elseif ($show_more_option === 'load_more') {
        echo '<div class="load-more">
                <button id="load-more-posts" class="load-more-button" data-current-page="1" data-max-pages="'. esc_attr($total_pages) .'" style="cursor: pointer">
                    ' . esc_html__('Load More Posts', 'aurora-lite') . '
                </button>
              </div>';
    }
}


function aurora_lite_archive_breadcrumbs() {

    if ( ! ( is_category() || is_tag() || is_date() ) ) {
        return;
    }

    echo '<nav class="aurora-lite-breadcrumbs">';

    echo '<a href="' . esc_url( home_url() ) . '" class="bc-home">';
    echo '<i class="fa-solid fa-house"></i> ' . esc_html__( 'Home', 'aurora-lite' );
    echo '</a>';
    echo '<span class="bc-sep">›</span>';

    if ( is_category() ) {
        $term = single_cat_title( '', false );
    } elseif ( is_tag() ) {
        $term = single_tag_title( '', false );
    } elseif ( is_date() ) {
        if ( is_day() ) {
            $term = get_the_date();
        } elseif ( is_month() ) {
            $term = get_the_date( 'F Y' );
        } elseif ( is_year() ) {
            $term = get_the_date( 'Y' );
        } else {
            $term = '';
        }
    } else {
        $term = '';
    }

    if ( $term ) {
        echo '<span class="bc-archive">' . esc_html( $term ) . '</span>';
    }

    echo '</nav>';
}

function aurora_lite_banner_term() {

    if ( is_category() ) {
        $term = single_cat_title( '', false );
        return esc_html__( 'Category: ', 'aurora-lite' ) . esc_html( $term );
    }

    if ( is_tag() ) {
        $term = single_tag_title( '', false );
        return esc_html__( 'Tag: ', 'aurora-lite' ) . esc_html( $term );
    }

    if ( is_date() ) {

        if ( is_day() ) {
            $date = get_the_date();
        } elseif ( is_month() ) {
            $date = get_the_date( 'F Y' );
        } elseif ( is_year() ) {
            $date = get_the_date( 'Y' );
        } else {
            $date = '';
        }

        if ( $date ) {
            return esc_html__( 'Date: ', 'aurora-lite' ) . esc_html( $date );
        }
    }

    return '';
}

function aurora_lite_render_archive_banner() {

    if ( get_theme_mod( 'aurora_lite_disable_archive_banner', false ) ) {
        return;
    }

    if ( ! ( is_category() || is_tag() || is_date() ) ) {
        return;
    }

    echo '<div class="archive-banner">';
        echo '<h1>' . esc_html( aurora_lite_banner_term() ) . '</h1>';
        aurora_lite_archive_breadcrumbs();
    echo '</div>';
}


function aurora_lite_enqueue_masonry_styles() {

    if ( ! ( is_archive() || is_date() || is_search() || is_author() ) ) {
        return;
    }

    if ( ! function_exists('aurora_lite_use_masonry') || ! aurora_lite_use_masonry() ) {
        return;
    }

    $file_path = get_template_directory() . '/assets/css/masonry.css';
    $file_url  = get_template_directory_uri() . '/assets/css/masonry.css';

    if ( file_exists( $file_path ) ) {
        wp_enqueue_style(
            'aurora-lite-masonry',
            $file_url,
            [],
            filemtime( $file_path )
        );
    }
}
add_action( 'wp_enqueue_scripts', 'aurora_lite_enqueue_masonry_styles' );