<?php

if (!defined('ABSPATH')) { exit; }

class AIEO_Fulfillment_Templates {

    
    public static function active_template_id() {
        $tpl = AIEO_Fulfillment_Settings::get('templates.active', 'Simple');
        $tpl = is_string($tpl) && $tpl !== '' ? $tpl : 'Simple';
        return $tpl;
    }

    
    public static function locate($template_id, $doc) {
        $template_id = sanitize_file_name((string) $template_id);
        $doc         = sanitize_file_name((string) $doc);
        if ($template_id === '' || $doc === '') { return ''; }

        
        $theme_dirs = array(get_stylesheet_directory(), get_template_directory());
        foreach (array_unique($theme_dirs) as $td) {
            $cand = trailingslashit($td) . 'aieo/fulfillment/' . $template_id . '/' . $doc . '.php';
            if (file_exists($cand)) { return $cand; }
        }

        
        $bundled = AIEO_DIR . 'templates/fulfillment/' . $template_id . '/' . $doc . '.php';
        if (file_exists($bundled)) { return $bundled; }

        return '';
    }

    
    public static function render($template_id, $doc, array $data) {
        $path = self::locate($template_id, $doc);
        if ($path === '') {
            
            return new WP_Error('template_not_found', sprintf(__('Template not found: %1$s / %2$s', 'ai-eshop-optimizer'), $template_id, $doc));
        }
        
        extract($data, EXTR_SKIP);
        
        ob_start();
        include $path;
        return (string) ob_get_clean();
    }

    
    public static function list_installed() {
        $out = array('Simple' => __('Simple', 'ai-eshop-optimizer'));

        $bundled_root = AIEO_DIR . 'templates/fulfillment/';
        if (is_dir($bundled_root)) {
            foreach ((array) glob($bundled_root . '*', GLOB_ONLYDIR) as $dir) {
                $name = basename($dir);
                if ($name !== '' && !isset($out[$name])) { $out[$name] = $name; }
            }
        }
        
        foreach (array_unique(array(get_stylesheet_directory(), get_template_directory())) as $td) {
            $theme_root = trailingslashit($td) . 'aieo/fulfillment/';
            if (!is_dir($theme_root)) { continue; }
            foreach ((array) glob($theme_root . '*', GLOB_ONLYDIR) as $dir) {
                $name = basename($dir);
                if ($name !== '' && !isset($out[$name])) {
                    $out[$name] = sprintf('%s (theme override)', $name);
                }
            }
        }
        return $out;
    }
}
