<?php

namespace Lknwp\CrowdfundingExtension\Includes;

final class LknwpCrowdfundingExtensionActivator
{
    /**
     * Short Description. (use period)
     *
     * Long Description.
     *
     * @since    1.0.0
     */
    public static function activate(): void
    {
        global $wpdb;

        // Recupera a base da URL do produto configurada no WooCommerce
        $product_base = get_option('woocommerce_permalinks')['product_base'];
        $product_base = trim($product_base, '/');

        // Recupera a lista de páginas e seus slugs
        $pages = $wpdb->get_results("SELECT ID, post_name FROM {$wpdb->posts} WHERE post_type = 'page' AND post_status = 'publish'");

        $applied_rules = [];
        $new_rules_added = false;

        // Adiciona as novas regras
        foreach ($pages as $page) {
            $page_id = $page->ID;
            $page_slug = trim($page->post_name, ' ');

            if (!isset($applied_rules[$page_id])) {
                add_rewrite_rule(
                    '^' . $product_base . '/' . $page_slug . '/([^/]+)/?$',
                    'index.php?product=$matches[1]',
                    'top'
                );

                $applied_rules[$page_id] = $page_slug;

                $new_rules_added = true;
            }
        }

        if ($new_rules_added) {
            update_option('lkn_custom_rewrite_rules', $applied_rules);
            flush_rewrite_rules();
        }
    }

}
