<?php

namespace GriffinForms\Admin\Html\FormControls;

/**
 * Renders a folder icon selection control for the GriffinForms folder edit page.
 * Displays all available icons from a directory as radio buttons with previews.
 */
class FolderIcon extends \GriffinForms\Admin\Html\FormControls\Format
{
    /**
     * Outputs the HTML container for the folder icon picker.
     */
    public function html()
    {
        echo '<div class="d-flex mb-3" id="gf-folder-icon-container">';
        $this->getIcons();
        echo '</div>';        
    }

    /**
     * Scans the icon directory and renders each valid image file (png/svg)
     * as a selectable radio input with a preview.
     * Automatically selects the first icon if no match is found for the current value.
     */
    private function getIcons()
    {
        // Prepare paths and selected value
        $icon_dir = $this->config->getRootPath() . 'admin/images/folder/';
        $icon_url = $this->config->getRootUrl() . 'admin/images/folder/';
        $selected = (string) intval($this->value);

        // Skip if icon directory is missing
        if (!is_dir($icon_dir)) {
            return;
        }

        $files = scandir($icon_dir);
        $match_found = false;
        $first_icon = null;

        // Loop through valid image files
        foreach ($files as $file) {
            if (in_array($file, ['.', '..']) || !preg_match('/\.(png|svg)$/i', $file)) {
                continue;
            }

            $filename_no_ext = pathinfo($file, PATHINFO_FILENAME);
            if (empty($filename_no_ext)) {
                continue;
            }

            // Track first icon and match against selected value
            if ($first_icon === null) {
                $first_icon = $filename_no_ext;
            }
            if ($selected === $filename_no_ext) {
                $match_found = true;
            }
            $is_checked = ($selected === $filename_no_ext) || (!$match_found && $first_icon === $filename_no_ext);

            $input_id = 'gf-folder-icon-' . sanitize_title($file);
            $file_url_esc = $icon_url . $file;

            // Render each icon with its radio input
            echo '<label class="gf-folder-icon-option me-4 text-center" for="' . esc_attr($input_id) . '">';
            echo '<div class="mb-1"><img src="' . esc_url($file_url_esc) . '" alt="" width="36" /></div>';
            echo '<div><input type="radio" name="' . esc_attr($this->name) . '" value="' . esc_attr($filename_no_ext) . '" id="' . esc_attr($input_id) . '" ' . checked($is_checked, true, false) . ' /></div>';
            echo '</label>';
        }

        // Fallback: ensure first icon is selected if none matched
        if (!$match_found && $first_icon !== null) {
            echo '<input type="hidden" name="' . esc_attr($this->name) . '" value="' . esc_attr($first_icon) . '" />';
        }
    }
}