<?php

namespace App\Components;

class Modal
{
    protected $id;
    protected $title;
    protected $body;
    protected $footer;
    protected $size;
    protected $scrollable;
    protected $fullWidth;
    protected $headerActions = [];

    // Unique identifier for modal instances
    protected static int $modalCounter = 0;
    protected string $uniqueKey;

    public static function make($id)
    {
        $instance = new static;
        $instance->id = $id;
        $instance->uniqueKey = 'modal_' . (++self::$modalCounter);
        return $instance;
    }

    public function title($title)
    {
        $this->title = $title;
        return $this;
    }

    public function body($body)
    {
        $this->body = $body;
        return $this;
    }

    public function footer($footer)
    {
        $this->footer = $footer;
        return $this;
    }

    public function size($size = '')
    {
        $this->size = $size;
        return $this;
    }

    public function scrollable($enable = true)
    {
        $this->scrollable = $enable;
        return $this;
    }

    public function fullWidth($enable = true)
    {
        $this->fullWidth = $enable;
        return $this;
    }

    public function addHeaderAction($html)
    {
        $this->headerActions[] = $html;
        return $this;
    }

    /**
     * Render a placeholder that will be dynamically populated from trigger button JSON
     */
    public static function Output(string $key, bool $display = true, $default = ''): string
    {
        $display = $display ? 'style = "display:block;"' : 'style = "display:none;"';
        return "<span class='modal-output' {$display} data-key='{$key}'>{$default}</span>";
    }

    public static function OutputArray(string $varName = 'modalData'): string
    {
        // This will render a span with a unique data attribute that JS can populate with the full JSON
        return "<span class='modal-output-array' data-var='{$varName}'></span>";
    }

    public static function dataAttr(string $attrKey, string $jsonKey): string
    {
        // Generate a unique placeholder
        $unique = uniqid();
        // Store the JSON key and the desired data-* name in the element
        return "data-modal-attr='{$unique}' data-modal-key='{$jsonKey}' data-target-attr='{$attrKey}'";
    }


    public function render()
    {
        $dialogClasses = [];
        if ($this->size) $dialogClasses[] = $this->size;
        if ($this->scrollable) $dialogClasses[] = 'modal-dialog-scrollable';
        if ($this->fullWidth) $dialogClasses[] = 'modal-full-width';

        $dialogClass = implode(' ', $dialogClasses);

        // default close button
        $headerActionsHtml = '<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>';
        if (!empty($this->headerActions)) {
            $headerActionsHtml .= implode("\n", $this->headerActions);
        }

        // Generate a unique JS variable to avoid conflicts in multiple modals
        $uniqueJsVar = $this->uniqueKey;

        return <<<HTML
    <div id="{$this->id}" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog {$dialogClass}">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">{$this->title}</h4>
                    {$headerActionsHtml}
                </div>
                <div class="modal-body">
                    {$this->body}
                </div>
                <div class="modal-footer">
                    {$this->footer}
                </div>
            </div>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        var modal = document.getElementById('{$this->id}');
        modal.addEventListener('show.bs.modal', function(event) {
            var button = event.relatedTarget; // button that triggered the modal
            var jsonData = button.getAttribute('data-modal-data');
            if (!jsonData) return;

            try {
                var {$uniqueJsVar} = JSON.parse(jsonData);
            } catch (e) {
                console.error('Invalid JSON in data-modal-data', e);
                return;
            }

            // Populate .modal-output spans
            modal.querySelectorAll('.modal-output').forEach(function(span) {
                var key = span.getAttribute('data-key');
                if (key in {$uniqueJsVar}) {
                    span.textContent = {$uniqueJsVar}[key];
                }
            });

            // Populate hidden inputs if IDs match keys
            Object.keys({$uniqueJsVar}).forEach(function(key) {
                var input = modal.querySelector('#' + key);
                if (input) input.value = {$uniqueJsVar}[key];
            });

            // NEW: Populate elements with data-modal-attr
            modal.querySelectorAll('[data-modal-attr]').forEach(function(el) {
                var key = el.getAttribute('data-modal-key');       // key in JSON
                var targetAttr = el.getAttribute('data-target-attr'); // final data-* name
                if (key && targetAttr && key in {$uniqueJsVar}) {
                    el.setAttribute('data-' + targetAttr, {$uniqueJsVar}[key]);
                }
            });
        });
    });
    </script>
    HTML;
    }

}
