<?php

namespace GriffinForms\Admin;

class Format extends \GriffinForms\Format
{
    protected $config;
    protected $meta;
    protected $lang;
    protected $top_level_pages;
    protected $internal_pages;
    
    protected function purgeString($str)
    {
        $chaff = array(' ', '_', '-');
        foreach ($chaff as $value) {
            $str = str_replace($value, '', $str);
        }
        
        return $str;
    }
    
    protected function setHelper($helper, $type = null)
    {
        if($type === null) {
            $type = $this->meta;
        }
        
        $helper_class = '\GriffinForms\Admin\\' . $helper . '\\' . $type;
        $helper_file = plugin_dir_path(__FILE__) . $helper . '/' . strtolower($type) . '.php';
        if (file_exists($helper_file)) {
            $this->$helper = $helper_class::getInstance();
        }
    }
    
    protected function setLang($type = null)
    {
        if ($type === null) {
            $type = $this->meta;
        }
        
        $file = plugin_dir_path(__FILE__) . 'language/' . $type. '.php';
        if (file_exists(strtolower($file))) {
            $lang_class = '\GriffinForms\Admin\Language\\' . $type;
            if (!class_exists($lang_class)) {
                return;
            }

            $reflection = new \ReflectionClass($lang_class);
            if ($reflection->isAbstract() || !$reflection->hasMethod('getInstance')) {
                return;
            }

            $this->lang = $lang_class::getInstance();
        }
    }

    protected function getImg($name, $type = 'icon', $output = 'html', $subfolder = '')
    {
        // Sanitize name and subfolder to prevent path traversal
        $name = preg_replace('/[^a-zA-Z0-9_\-]/', '', $name);
        $subfolder = preg_replace('/[^a-zA-Z0-9_\-\/]/', '', $subfolder);

        $folder = $type === 'icon' ? 'icons' : 'images';
        $subfolderPath = $subfolder ? trim($subfolder, '/') . '/' : '';

        $path = $this->config->getRootPath() . 'admin/images/' . $folder . '/' . $subfolderPath . $name . '.svg';

        if (!file_exists($path)) {
            return ''; // Optional: Log or return fallback SVG
        }

        $content = file_get_contents($path);

        if ($output === 'html') {
            return $content; // Return inline SVG
        }

        if ($output === 'url') {
            return $this->config->getRootUrl() . 'admin/images/' . $folder . '/' . $subfolderPath . $name . '.svg';
        }

        return ''; // Prevent invalid output types
    }
}
