<?php
namespace IntentDeep\VirtualFiles\Traits;

trait VirtualFilesHelper {
    
    /**
     * Format file size for display
     */
    private function formatFileSize($bytes) {
        if ($bytes === 0) return '0 B';
        $units = ['B', 'KB', 'MB', 'GB'];
        $factor = floor((strlen($bytes) - 1) / 3);
        return sprintf("%.2f", $bytes / pow(1024, $factor)) . ' ' . $units[$factor];
    }

    /**
     * Get file URL
     */
    private function getFileUrl($post, $filename) {
        $site_url = get_site_url();
        return $site_url . '/' . ltrim($filename, '/');
    }

    /**
     * Get file extension from filename
     */
    private function getFileExtension($filename) {
        return pathinfo($filename, PATHINFO_EXTENSION);
    }

    /**
     * Get filename without extension
     */
    private function getFilenameWithoutExtension($filename) {
        if (empty($filename)) return '';
        $extension = $this->getFileExtension($filename);
        if ($extension) {
            return substr($filename, 0, -(strlen($extension) + 1));
        }
        return $filename;
    }

    /**
     * Detect MIME type based on file extension
     */
    private function detectMimeType($filename) {
        $extension = $this->getFileExtension($filename);

        $mime_types = [
            'txt' => 'text/plain; charset=utf-8',
            'md' => 'text/markdown; charset=utf-8',
            'json' => 'application/json; charset=utf-8',
            'jsonld' => 'application/ld+json; charset=utf-8',
            'xml' => 'application/xml; charset=utf-8',
            'rss' => 'application/rss+xml; charset=utf-8',
            'csv' => 'text/csv; charset=utf-8',
            'yml' => 'text/yaml; charset=utf-8',
            'yaml' => 'text/yaml; charset=utf-8',
            'log' => 'text/plain; charset=utf-8',
        ];

        return $mime_types[strtolower($extension)] ?? 'text/plain; charset=utf-8';
    }

    /**
     * Get file type options for dropdown
     */
    private function getFileTypeOptions() {
        return [
            'txt' => [
                'label' => __('Plain Text (.txt)', 'intentdeep-virtual-files'),
                'mime' => 'text/plain; charset=utf-8',
                'pro' => false,
                'description' => __('Basic text files', 'intentdeep-virtual-files')
            ],
            'md' => [
                'label' => __('Markdown (.md)', 'intentdeep-virtual-files'),
                'mime' => 'text/markdown; charset=utf-8',
                'pro' => false,
                'description' => __('Markdown documentation', 'intentdeep-virtual-files')
            ],
            'json' => [
                'label' => __('JSON (.json)', 'intentdeep-virtual-files'),
                'mime' => 'application/json; charset=utf-8',
                'pro' => false,
                'description' => __('JSON data files', 'intentdeep-virtual-files')
            ],
            'jsonld' => [
                'label' => __('JSON-LD (.jsonld)', 'intentdeep-virtual-files'),
                'mime' => 'application/ld+json; charset=utf-8',
                'pro' => true,
                'description' => __('JSON-LD structured data', 'intentdeep-virtual-files')
            ],
            'xml' => [
                'label' => __('XML (.xml)', 'intentdeep-virtual-files'),
                'mime' => 'application/xml; charset=utf-8',
                'pro' => true,
                'description' => __('XML sitemaps and data', 'intentdeep-virtual-files')
            ],
            'rss' => [
                'label' => __('RSS Feed (.rss)', 'intentdeep-virtual-files'),
                'mime' => 'application/rss+xml; charset=utf-8',
                'pro' => true,
                'description' => __('RSS feeds', 'intentdeep-virtual-files')
            ],
            'csv' => [
                'label' => __('CSV (.csv)', 'intentdeep-virtual-files'),
                'mime' => 'text/csv; charset=utf-8',
                'pro' => true,
                'description' => __('CSV data files', 'intentdeep-virtual-files')
            ],
            'yml' => [
                'label' => __('YAML (.yml)', 'intentdeep-virtual-files'),
                'mime' => 'text/yaml; charset=utf-8',
                'pro' => true,
                'description' => __('YAML configuration', 'intentdeep-virtual-files')
            ],
            'yaml' => [
                'label' => __('YAML (.yaml)', 'intentdeep-virtual-files'),
                'mime' => 'text/yaml; charset=utf-8',
                'pro' => true,
                'description' => __('YAML configuration', 'intentdeep-virtual-files')
            ],
            'log' => [
                'label' => __('Log File (.log)', 'intentdeep-virtual-files'),
                'mime' => 'text/plain; charset=utf-8',
                'pro' => true,
                'description' => __('Log files', 'intentdeep-virtual-files')
            ]
        ];
    }

    // This method is now in SettingHelper trait

    // This method is now in RewriteRulesTrait

    // This method is now in SettingHelper trait

    /**
     * Check if a file is accessible for free users in admin (max 5 files, newest first)
     */
    private function isFileAccessibleForFreeUserInAdmin($file_id): bool {
        // Get all active virtual files, ordered by modification date (newest first)
        $all_active_files = get_posts([
            'post_type' => 'idep_virtual_file',
            'posts_per_page' => -1,
            'post_status' => 'publish',
            'meta_query' => [
                [
                    'key' => '_vf_status',
                    'value' => 'active',
                    'compare' => '='
                ]
            ],
            'orderby' => 'meta_value_num', // Sort by modified timestamp
            'meta_key' => '_vf_modified',
            'order' => 'DESC'
        ]);

        // If 5 or fewer files, all are accessible
        if (count($all_active_files) <= 5) {
            return true;
        }

        // Get the first 5 (newest) file IDs
        $accessible_file_ids = array_slice(wp_list_pluck($all_active_files, 'ID'), 0, 5);

        return in_array($file_id, $accessible_file_ids);
    }

    /**
     * Sanitize content based on file type
     */
    private function sanitizeVirtualFileContent($content, $extension) {
        if (empty($content)) {
            return '';
        }

        // For structured data files and Markdown, preserve the structure but ensure basic security
        $structured_extensions = ['xml', 'json', 'jsonld', 'yml', 'yaml', 'rss', 'csv', 'md', 'markdown'];

        if (in_array(strtolower($extension), $structured_extensions)) {
            // Additional security checks for structured files
            $content = $this->sanitizeStructuredContent($content);

            // Normalize line endings and trim for consistency
            $content = str_replace(["\r\n", "\r"], "\n", $content);
            return trim($content);
        }

        // For text files, use WordPress post sanitization (HTML-aware)
        return wp_kses_post($content);
    }

    /**
     * Sanitize structured content (XML, JSON, Markdown) while preserving valid syntax
     */
    private function sanitizeStructuredContent($content) {
        // Remove dangerous PHP tags (case-insensitive, multiline)
        $content = preg_replace('/<\?php.*?\?>/si', '', $content);

        // Remove script tags with attributes and content
        $content = preg_replace('/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/mi', '', $content);

        // Remove iframe tags with attributes and content
        $content = preg_replace('/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/mi', '', $content);

        // Remove dangerous HTML event handlers that might be in XML/JSON attributes
        $dangerous_events = ['onload', 'onerror', 'onclick', 'onmouseover', 'onfocus', 'onblur'];
        foreach ($dangerous_events as $event) {
            $content = preg_replace('/\b' . preg_quote($event, '/') . '\s*=/i', '', $content);
        }

        // Remove javascript: and data: URLs that could be dangerous
        $content = preg_replace('/\b(javascript|data|vbscript):/i', '', $content);

        // Limit content size to prevent memory issues (1MB max)
        if (strlen($content) > 1048576) {
            $content = substr($content, 0, 1048576);
        }

        return $content;
    }

    // This method is now in RewriteRulesTrait

    /**
     * Invalidate cache when virtual file meta is saved
     */
    private function invalidateCacheOnSave($post_id) {
        // Delete the specific file cache
        $this->cache->delete_file_cache($post_id);

        // Log cache invalidation for debugging
        intentdeep_vf_log("Virtual Files: Cache invalidated on save for file ID {$post_id}");
    }

    /**
     * Invalidate file cache when a virtual file is modified
     */
    public function invalidateFileCache($post_id) {
        $post_type = get_post_type($post_id);

        if ($post_type !== 'idep_virtual_file') {
            return;
        }

        // Delete the specific file cache
        $this->cache->delete_file_cache($post_id);

        // Log cache invalidation for debugging
        intentdeep_vf_log("Virtual Files: Cache invalidated for file ID {$post_id}");
    }
}