<?php
namespace IntentDeep\VirtualFiles\Core;

trait RewriteRulesTrait {
    /**
     * Schedule rewrite rules flush for better performance
     */
    protected function scheduleRewriteFlush(): void {
        // Set a transient to trigger rewrite flush on next page load
        set_transient('intentdeep_vf_flush_rewrite_rules', true, 30);

        // Also flush immediately for critical cases
        $this->forceRewriteFlush();
    }

    /**
     * Force rewrite rules to be flushed immediately
     */
    protected function forceRewriteFlush(): void {
        // Re-register our rewrite rules
        $this->registerRewriteRules();

        // Flush rewrite rules to apply changes
        flush_rewrite_rules(false);
    }

    /**
     * Register rewrite rules
     */
    protected function registerRewriteRules(): void {
        add_action('init', [$this, 'registerVirtualFileRewriteRules'], 1);

        // Force immediate registration
        $this->registerVirtualFileRewriteRules();
    }

    /**
     * Register virtual file rewrite rules
     */
    public function registerVirtualFileRewriteRules(): void {
        $virtual_files = $this->getActiveVirtualFiles();

        foreach ($virtual_files as $file) {
            $filename = get_post_meta($file->ID, '_vf_filename', true);
            $status = get_post_meta($file->ID, '_vf_status', true);

            if (!empty($filename) && $status === 'active') {
                // Sanitize filename for rewrite rules
                $sanitized_filename = sanitize_title($filename);

                // Register rewrite rule using WordPress API
                add_rewrite_rule(
                    '^' . preg_quote($sanitized_filename, '/') . '/?$',
                    'index.php?virtual_file=' . $file->ID,
                    'top'
                );
            }
        }
    }

    /**
     * Get active virtual files for rewrite rules
     */
    private function getActiveVirtualFiles(): array {
        return get_posts([
            'post_type' => 'idep_virtual_file',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'meta_query' => [
                [
                    'key' => '_vf_status',
                    'value' => 'active',
                    'compare' => '='
                ],
                [
                    'key' => '_vf_filename',
                    'value' => '',
                    'compare' => '!='
                ]
            ]
        ]);
    }
}