<?php
/*
    Template Name: Страница кабинета
*/

    if (!is_user_logged_in()) {
        wp_redirect(home_url());
        exit;
    }

    $paged = get_query_var('paged') ? get_query_var('paged') : 1;

    $platform = isset($_COOKIE['platform']) ? sanitize_text_field($_COOKIE['platform']) : 'tradingview';

    $filter = isset($_GET['filter']) ? sanitize_text_field($_GET['filter']) : 'all';

    $args = array(
        'post_type'      => 'post',
        'posts_per_page' => 9,
        'orderby'        => 'date',
        'order'          => 'DESC',
         'post_status'    => 'publish',
        'paged'          => $paged,
    );

    $args['tax_query'] = [
        [
            'taxonomy' => 'platform',
            'field'    => 'slug',
            'terms'    => $platform,
        ]
    ];

    if ($filter === 'indicators') {
        $args['category_name'] = 'indicators';
    }
    elseif ($filter === 'scripts') {
        $args['category_name'] = 'scripts';
    }

    $post_query = new WP_Query($args);

get_header();
?>
<main class="px-6 py-8">
    <div class="max-w-7xl mx-auto">
        <div class="text-center mb-8">
            <p class="text-gray-400 mb-4"><?php pll_e('Тут можна переглянути та завантажити скрипти та індикатори:'); ?></p>
            <h2 class="text-3xl font-bold text-white mb-6"><?php pll_e('Індикатори та стратегії'); ?></h2>
            <div class="flex items-center justify-center space-x-4 mb-8">
                <button data-filter="all" class="px-6 py-2 rounded-full transition-colors !rounded-button whitespace-nowrap"><?php pll_e('Всі'); ?></button>
                <button data-filter="indicators" class="px-6 py-2 rounded-full transition-colors !rounded-button whitespace-nowrap"><?php pll_e('Індикатори'); ?></button>
                <button data-filter="scripts" class="px-6 py-2 rounded-full transition-colors !rounded-button whitespace-nowrap"><?php pll_e('Скрипти'); ?></button>
            </div>
        </div>
        <?php  if ($post_query->have_posts()): ?>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
                <?php while ($post_query->have_posts()) : $post_query->the_post(); ?>
                    <?php
                        $categories = get_the_category();
                        $category = '';
                        if (!empty($categories)) {
                            $category = esc_html($categories[0]->name);
                        }
                    ?>
                    <div class="glass-effect rounded-xl p-6 card-hover">
                        <div class="relative">
                            <img src="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'medium'); ?>" alt="Trading Script" class="w-full h-40 object-cover rounded-lg mb-4">
                            <span class="absolute top-2 right-2 bg-red-600 text-white text-xs font-semibold px-2 py-1 rounded">
                                <?php echo $category; ?>
                            </span>
                        </div>
                        <h3 class="text-lg font-semibold text-white mb-2"><?php echo get_the_title(); ?></h3>
                        <p class="text-slate-400 text-sm mb-4"><?php echo get_the_excerpt(); ?></p>
                        <a href="<?php echo get_permalink(); ?>" class="btn-primary !rounded-button w-full block text-center py-2 text-white font-medium whitespace-nowrap bg-blue-600 hover:bg-blue-700">
                            <?php pll_e('Відкрити інструкцію'); ?>
                        </a>
                    </div>
                <?php
                    endwhile;
                    wp_reset_postdata();
                ?>
            </div>
            <?php
                $total_pages = $post_query->max_num_pages;
                if ($total_pages > 1) {
                    $big = 999999999;
                    $base = str_replace($big, '%#%', esc_url(get_pagenum_link($big)));

                // сохраняем фильтр
                    if ($filter !== 'all') {
                        $base = add_query_arg('filter', $filter, $base);
                    }

                    echo '<div class="flex justify-center mt-8">';
                    echo paginate_links([
                        'base'      => $base,
                        'format'    => '?paged=%#%',
                        'current'   => $paged,
                        'total'     => $total_pages,
                        'prev_text' => '«',
                        'next_text' => '»',
                        'type'      => 'list',
                        'end_size'  => 1,
                        'mid_size'  => 1,
                    ]);
                    echo '</div>';
             }
            ?>
        <?php  endif; ?>
    </div>
</main>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', function(e) {
                e.preventDefault();
                fetch('/wp-admin/admin-ajax.php?action=logout')
                    .then(response => response.json())
                    .then(data => {
                        window.location.href = data.data.redirect;
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        window.location.href = '/';
                    });
            });
        }
    });
</script>
<?php
get_footer();
