<?php

namespace IMATHUZH\Qfq\Core\Renderer\FormElement\Bootstrap3;

use IMATHUZH\Qfq\Core\Form\FormElement\AbstractFormElement;
use IMATHUZH\Qfq\Core\Helper\HelperFormElement;
use IMATHUZH\Qfq\Core\Helper\Support;
use IMATHUZH\Qfq\Core\Renderer\BaseRenderer;

class Bootstrap3DatetimeRenderer extends \IMATHUZH\Qfq\Core\Renderer\FormElement\Base\DatetimeRenderer {

    /**
     * @param AbstractFormElement $fe
     * @param string $renderMode
     * @return string
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    public function renderInput(AbstractFormElement $fe, string $renderMode = RENDER_MODE_HTML): string {


        $attributesWithExtraBtn = HelperFormElement::prepareExtraButton($fe->attributes, true);


        $input = "<input " . Support::arrayToXMLAttributes($fe->htmlAttributes)
            . Support::doAttribute(CSS_CLASS, implode(' ', $fe->cssClasses)) . "/>"
            . $attributesWithExtraBtn[FE_TMP_EXTRA_BUTTON_HTML];

        if ($attributesWithExtraBtn[FE_TMP_EXTRA_BUTTON_HTML] !== '') {
            $input = Support::wrapTag('<div class="input-group">', $input) . HelperFormElement::getHelpBlock();
        }

        return $input . $attributesWithExtraBtn[FE_INPUT_EXTRA_BUTTON_INFO];

    }

    /**
     * Render the form element as a JSON structure with optional placeholder replacement for date/time values.
     *
     * This method prepares the JSON response for a single form element. If both a date string and a placeholder
     * are provided, the method replaces placeholder tokens (e.g., `dd`, `mm`, `yyyy`, `hh`, `ss`) with values
     * extracted from the date string.
     *
     * @param AbstractFormElement $fe The form element to be rendered.
     * @return array JSON-compatible array containing the updated form element information.
     */
    public function renderJson(AbstractFormElement $fe): array {
        $wrap = BaseRenderer::getInstance()->wrap[WRAP_SETUP_ELEMENT][WRAP_SETUP_CLASS];
        $json = HelperFormElement::getFormElementForJson($fe, $wrap);
        $placeholder = $fe->attributes[FE_ATTRIBUTES_PLACEHOLDER];
        $date = $fe->value;


        // If both placeholder and value exist, try to substitute placeholders with actual date/time parts
        if (!empty($placeholder) && !empty($date)) {
            // Match full date and optional time string (e.g., "23.06.2025 14:30" or "23.06.2025 14:30:00")
            if (preg_match('/^(\d{2})\.(\d{2})\.(\d{4})\s+(\d{2}):(\d{2})(?::(\d{2}))?$/', $date, $m)) {
                // Create a key-value map for placeholder substitution
                $map = [
                    FE_DATEPICKER_DAY           => $m[1],             // e.g., '23'
                    FE_DATEPICKER_MONTH         => $m[2],             // e.g., '06'
                    FE_DATEPICKER_YEAR          => $m[3],             // e.g., '2025'
                    FE_DATEPICKER_HH            => $m[4],             // e.g., '14'
                    FE_DATEPICKER_MONTH_LOWER   => $m[5],             // e.g., '30'
                    FE_DATEPICKER_SS_LOWER      => $m[6] ?? '',       // e.g., '00' (optional)
                ];

                // Replace placeholders in the template with actual values
                $date = $placeholder;
                foreach ($map as $key => $val) {
                    $date = str_replace($key, $val, $date);
                }
            }
        }
        // Construct the final JSON payload to return
        $formJson = array();
        $formJson[API_FORM_UPDATE_DISABLED] = $json[API_FORM_UPDATE_DISABLED];
        $formJson[API_FORM_UPDATE_REQUIRED] = $json[API_FORM_UPDATE_REQUIRED];
        $formJson[API_FORM_UPDATE_FORM_ELEMENT] = $json[API_FORM_UPDATE_FORM_ELEMENT];
        $formJson[API_FORM_UPDATE_VALUE] =  $date;
        $formJson[API_ELEMENT_UPDATE] = $json[API_ELEMENT_UPDATE];
        return $formJson;
    }
}