<?php
/**
 * Main plugin class for FBT Templates for Bricks Builder
 *
 * @package FBT_Templates_For_Bricks_Builder
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Main plugin class
 */
class FBT_Templates_For_Bricks_Builder {

    /**
     * Constructor
     */
    public function __construct() {
        // Constructor initialization
    }

    /**
     * Initialize the plugin
     *
     * @return void
     */
    public function init() {
        // Clear all template-related transients on init
        $this->clear_template_transients();
        
        // Add filter to inject templates into Bricks
        add_filter('bricks/get_templates', array($this, 'inject_templates'), 10, 1);
        
        // Add assets for template badges
        add_action('bricks_after_footer', array($this, 'enqueue_template_assets'));
        
        // Add action to clear transients when visiting admin page
        add_action('admin_init', array($this, 'clear_template_transients'));
    }
    
    /**
     * Clear all template-related transients
     * This ensures fresh template data is loaded each time
     */
    public function clear_template_transients() {
        delete_transient('fbt_templates_for_bricks_builder_free_templates');
        delete_transient('fbt_templates_for_bricks_builder_premium_templates');
        delete_transient('fbt_free_templates');
        delete_transient('fbt_premium_templates');
        
        // Clear any other potential template caches using WordPress cache API
        $cache_keys = wp_cache_get('fbt_templates_for_bricks_builder_template_cache_keys', 'fbt_templates_for_bricks_builder_templates');
        if (is_array($cache_keys)) {
            foreach ($cache_keys as $key) {
                wp_cache_delete($key, 'fbt_templates_for_bricks_builder_templates');
            }
        }
        
        // Clean up the cache keys themselves
        wp_cache_delete('fbt_templates_for_bricks_builder_template_cache_keys', 'fbt_templates_for_bricks_builder_templates');
    }

    /**
     * Enqueue assets for template badges
     *
     * @return void
     */
    public function enqueue_template_assets() {
        // Set cache prevention headers
        $this->set_cache_prevention_headers();
        
        wp_enqueue_style(
            'fbt-templates-for-bricks-builder',
            FBT_TEMPLATES_FOR_BRICKS_BUILDER_URL . 'assets/css/fbt-templates-for-bricks-builder.css',
            array(),
            time() // Use time() for aggressive cache-busting
        );
    }
    
    /**
     * Set cache prevention headers
     * This helps prevent browsers from caching our assets
     */
    private function set_cache_prevention_headers() {
        // Only set headers if we haven't sent them yet
        if (!headers_sent()) {
            header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
            header("Cache-Control: post-check=0, pre-check=0", false);
            header("Pragma: no-cache");
            header("Expires: 0");
        }
    }

    /**
     * Inject templates into Bricks
     *
     * @param array $templates Existing templates
     * @return array Modified templates
     */
    public function inject_templates($templates) {
        // Get free templates only
        $free_templates = $this->get_free_templates();
        
        // Merge templates
        $all_templates = array_merge($templates, $free_templates);
        
        return $all_templates;
    }

    /**
     * Get free templates from the templates directory
     *
     * @return array Free templates
     */
    private function get_free_templates() {
        $templates = array();
        $templates_dir = FBT_TEMPLATES_FOR_BRICKS_BUILDER_PATH . 'templates/';
        
        // Check if directory exists
        if (!is_dir($templates_dir)) {
            return $templates;
        }
        
        // Get all JSON files
        $files = glob($templates_dir . '*.json');
        
        foreach ($files as $file) {
            $template_data = $this->parse_template_file($file);
            
            if ($template_data) {
                // Add template source
                $template_data['source'] = 'fbt-templates-for-bricks-builder-free';
                $template_data['templateType'] = isset($template_data['templateType']) ? $template_data['templateType'] : 'section';
                
                $templates[] = $template_data;
            }
        }
        
        return $templates;
    }


    /**
     * Parse template file
     *
     * @param string $file File path
     * @return array|false Template data or false on failure
     */
    private function parse_template_file($file) {
        $content = file_get_contents($file);
        
        if (!$content) {
            return false;
        }
        
        $template_data = json_decode($content, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return false;
        }
        
        // Add preview image based on template filename
        $filename = basename($file, '.json');
        $image_filename = $filename . '.jpg';
        $image_path = FBT_TEMPLATES_FOR_BRICKS_BUILDER_PATH . 'assets/images/templates/' . $image_filename;
        $image_url = FBT_TEMPLATES_FOR_BRICKS_BUILDER_URL . 'assets/images/templates/' . $image_filename;
        
        // Check if a matching image exists, otherwise use placeholder
        if (file_exists($image_path)) {
            $template_data['preview'] = $image_url;
        } else {
            $template_data['preview'] = FBT_TEMPLATES_FOR_BRICKS_BUILDER_URL . 'assets/images/placeholder.jpg';
        }
        
        return $template_data;
    }
}
