<?php

namespace FleekDash\Controllers\Post;

/**
 * Page template discovery (theme + plugin directories).
 *
 * @package FleekDash\Controllers\Post
 */
class PageTemplateHelper
{
    /**
     * Get all available page templates (theme + plugins).
     *
     * @return array<int, array{value: string, label: string}>
     */
    public static function getAllPageTemplates(): array
    {
        $templates = [];

        try {
            $theme = \wp_get_theme();
            $themeTemplates = $theme->get_page_templates();
            foreach ($themeTemplates as $file => $name) {
                $templates[] = ['value' => $file, 'label' => $name];
            }
        } catch (\Exception $e) {
            // Silently continue
        }

        foreach (self::scanPluginTemplates() as $file => $name) {
            $exists = false;
            foreach ($templates as $existing) {
                if ($existing['value'] === $file || $existing['label'] === $name) {
                    $exists = true;
                    break;
                }
            }
            if (!$exists) {
                $templates[] = ['value' => $file, 'label' => $name];
            }
        }

        usort($templates, static function ($a, $b) {
            return strcmp($a['label'], $b['label']);
        });

        return $templates;
    }

    /**
     * Scan plugin directories for page templates (Template Name header).
     *
     * @return array<string, string> File => template name
     */
    public static function scanPluginTemplates(): array
    {
        $templates = [];

        if (!defined('FLEEKDASH_PLUGIN_DIR')) {
            return $templates;
        }

        $pluginDirs = [
            FLEEKDASH_PLUGIN_DIR . 'views/',
            FLEEKDASH_PLUGIN_DIR . 'views/templates/',
        ];

        foreach ($pluginDirs as $dir) {
            if (!is_dir($dir)) {
                continue;
            }
            $files = glob($dir . '*.php');
            if ($files === false) {
                continue;
            }
            foreach ($files as $file) {
                if (!is_file($file)) {
                    continue;
                }
                $data = \get_file_data($file, ['Template Name' => 'Template Name']);
                if (!empty($data['Template Name'])) {
                    $templates[basename($file)] = $data['Template Name'];
                }
            }
        }

        return $templates;
    }
}
