<?php
defined( 'ABSPATH' ) || exit;

/**
 * Helper to get templates
 * 
 * @return array List of templates
 */
function cafi_get_templates() {
    // 1. Always load the File Config (Source of Truth for IDs, Names, Files)
    $json_file = CAFI_PLUGIN_DIR . 'admin/templates.json';
    $base_url = CAFI_PLUGIN_URL . 'admin/assets/images/templates/';
    
    $config_templates = [];
    if (file_exists($json_file)) {
        $json_content = file_get_contents($json_file);
        $decoded = json_decode($json_content, true);
        if ($decoded) $config_templates = $decoded;
    }

    // 2. Get User Saved Settings (DB)
    // We treat this primarily as a store for 'settings' (customizations)
    $stored_templates = get_option( 'cafi_templates_config' );
    $stored_settings_map = [];

    if ( $stored_templates && is_array( $stored_templates ) ) {
        foreach ( $stored_templates as $st ) {
            if ( isset( $st['id'] ) && isset( $st['settings'] ) ) {
                $stored_settings_map[ $st['id'] ] = $st['settings'];
            }
        }
    }

    $final_templates = [];
    
    // 3. Merge & Construct
    foreach ($config_templates as $tmpl) {
        $type = isset($tmpl['type']) ? $tmpl['type'] : 'image';
        
        $item = [
            'id' => $tmpl['id'],
            'name' => $tmpl['name'],
            'type' => $type,
            'category' => isset($tmpl['category']) ? strtolower($tmpl['category']) : 'all',
            // Default settings from JSON
            'settings' => isset($tmpl['settings']) ? $tmpl['settings'] : []
        ];

        // Construct Value (URL or Color)
        if ($type === 'color' || $type === 'gradient') {
            $item['value'] = $tmpl['value'];
        } else {
            $item['type'] = 'image'; 
            if(isset($tmpl['file'])) {
                // Dynamic URL generation ensures it works across domains/folders
                $item['value'] = $base_url . $tmpl['file'];
            } else {
                $item['value'] = ''; 
            }
        }

        // Overlay User Settings if they exist
        if ( isset( $stored_settings_map[ $tmpl['id'] ] ) ) {
            // We merge user settings over defaults. 
            // array_merge replaces keys in the first array with keys from the second
            $item['settings'] = array_merge( $item['settings'], $stored_settings_map[ $tmpl['id'] ] );
        }
        
        $final_templates[] = $item;
    }
    
    // Safety fallback if JSON failed
    if ( empty( $final_templates ) && ! empty( $stored_templates ) ) {
        return $stored_templates; 
    }
    
    return $final_templates;
}

/**
 * Helper to get current template URL or Color
 * Returns object { type: 'color'|'file', value: '...' }
 */
function cafi_get_current_template_data($options) {
    $current_id = isset( $options['template'] ) ? $options['template'] : '';
    $templates = cafi_get_templates();
    
    // Find match
    foreach($templates as $t) {
        if($t['id'] === $current_id) {
            return $t;
        }
    }
    
    // Return first if not found
    return isset($templates[0]) ? $templates[0] : [];
}

/**
 * Legacy helper for backward compatibility/CSS inline styles
 */
function cafi_get_current_template_url($options) {
    $data = cafi_get_current_template_data($options);
    if (isset($data['type']) && $data['type'] === 'file') {
        return $data['value']; 
    }
    return ''; // specific fix for colors
}
