<?php

namespace Storeplugin\PDFInvoice\Framework\Forms;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Contracts\SettingInterface;
use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractSetting;
use Storeplugin\PDFInvoice\Framework\Fields\FieldRenderer;
use Storeplugin\PDFInvoice\Config;

class Setting extends AbstractSetting
{
    /**
     * Create a new option panel instance
     *
     * @param string $pageTitle   Page title
     * @param string $menuTitle   Menu title
     * @param string $slug         Menu slug
     * @param string $optionName   Option key used for storage
     * @param string $capability   Capability required to access the page
     * @param string $icon         Icon for the menu item
     * @param int    $position     Position of the menu item
     *
     * @return SettingInterface
     */
    public static function create(
        string $pageTitle,
        string $menuTitle,
        string $slug,
        string $optionName,
        string $capability = 'manage_options',
        string $icon = 'dashicons-admin-generic',
        int $position = 2
    ): SettingInterface {
        return new self($pageTitle, $menuTitle, $slug, $optionName, $capability, $icon, $position);
    }

    /**
     * Render panels for a panel section
     */
    protected function renderPanels($panels, $options): void
    {
        foreach ($panels as $panel) {
            $panelIconClass = $this->getDashiconClass($panel['icon'] ?? '', 'admin-generic');

            $rawLayout      = $panel['layout'] ?? 'vertical';
            $layout         = in_array($rawLayout, ['horizontal', 'vertical'], true) ? $rawLayout : 'vertical';
            $rawColSpan     = $panel['default_col_span'] ?? 6;
            $defaultColSpan = is_numeric($rawColSpan) ? max(1, min(12, (int) $rawColSpan)) : 6;

            $containerClass = $layout === 'horizontal'
                ? 'nxtf-grid-layout'
                : 'nxtf-space-y-6';
        ?>
            <div class="nxtf-panel-form-group">
                <h3 class="nxtf-panel-form-group-title">
                    <span class="<?php echo \esc_attr($panelIconClass); ?> nxtf-panel-group-icon" aria-hidden="true"></span>
                    <?php echo \esc_html($panel['title']); ?>
                </h3>
                <div class="<?php echo \esc_attr($containerClass); ?>">
                    <?php
                        foreach ($panel['fields'] as $field) {
                            if ($layout === 'horizontal' && !isset($field['col_span'])) {
                                $fieldType = \sanitize_key($field['type'] ?? '');
                                if (in_array($fieldType, ['repeater', 'wysiwyg'], true)) {
                                    $field['col_span'] = 12;
                                } else {
                                    $field['col_span'] = $defaultColSpan;
                                }
                            }

                            $id = \sanitize_key((string) ($field['id'] ?? ''));
                            if ($id === '') { continue; }
                            $value = array_key_exists($id, $options) ? $options[$id] : null;
                            FieldRenderer::render($field, $value, $this->getOptionKey());
                        }
                    ?>
                </div>
            </div>
        <?php
        }
    }

    /**
     * Render the option panel page
     *
     * @internal WordPress callback method - do not call directly
     */
    public function renderPage(): void
    {
        $options = $this->loadOptionValues();
        $panelSlug = \sanitize_title($this->slug);
        $hasTabs = $this->hasTabs();
        $groups = $this->getAllGroups();
        $defaultActiveGroupId = '';
        if ($hasTabs && !empty($groups)) {
            $defaultActiveGroupId = isset($groups[0]['id']) ? (string) $groups[0]['id'] : '';
        }
        $sectionAction = $this->getSectionLoadAjaxAction();
        $sectionNonce = \wp_create_nonce($this->getSectionLoadNonceAction());
        $optionKey = $this->getOptionKey();
        $formId = 'nxtf-settings-form-' . $panelSlug;
        ?>
        <div class="nxtf-dashboard-wrapper">
            <div class="nxtf-dashboard-header">
                <div class="nxtf-header-left">
                    <div class="nxtf-header-container-left">
                        <h1 class="nxtf-header-title-left">
                            <span class="nxtf-header-icon-container-left">
                                <span class="dashicons <?php echo \esc_html($this->icon) ?> nxtf-header-icon-left" aria-hidden="true"></span>
                            </span>
                            <?php echo \esc_html($this->pageTitle); ?>
                        </h1>
                    </div>
                </div>
                <div class="nxtf-header-right">
                    <p></p>
                    <button type="submit" form="<?php echo \esc_attr($formId); ?>" name="<?php echo \esc_attr($optionKey); ?>_save" value="1" class="nxtf-header-btn">
                        <?php echo \esc_html__('Save Settings', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?>
                    </button>
                </div>
            </div>
            <div class="nxtf-dashboard-main">
                <form id="<?php echo \esc_attr($formId); ?>" method="post" action="" class="nxtf-dashboard-form setting-panel"
                    data-panel-id="<?php echo \esc_attr($panelSlug); ?>"
                    data-has-tabs="<?php echo $hasTabs ? '1' : '0'; ?>"
                    data-section-action="<?php echo \esc_attr($sectionAction); ?>"
                    data-section-nonce="<?php echo \esc_attr($sectionNonce); ?>">
                    <?php \wp_nonce_field($optionKey . '_action', $optionKey . '_nonce'); ?>

                    <?php if ($hasTabs) : ?>
                    <!-- Sidebar (only shown when tabs exist) -->
                    <aside class="nxtf-sidebar-left">
                        <nav class="nxtf-menu" data-panel-nav="1">
                            <?php foreach ($this->tabs as $tab) : ?>
                                <?php
                                $tabId = isset($tab['id']) ? $tab['id'] : '';
                                $tabTitle = isset($tab['title']) ? $tab['title'] : '';
                                $tabIcon = isset($tab['icon']) ? $tab['icon'] : 'admin-generic';
                                $tabIconClass = $this->getDashiconClass($tabIcon, 'admin-generic');
                                $sublinks = isset($tab['sublinks']) && is_array($tab['sublinks']) ? $tab['sublinks'] : [];
                                ?>
                                <div class="nxtf-menu__item" data-tab-id="<?php echo \esc_attr($tabId); ?>">
                                    <div class="nxtf-submenu__item">
                                        <a href="#" class="nxtf-sidebar-tab-link-left nav-item">
                                            <span class="<?php echo \esc_attr($tabIconClass); ?> nxtf-menu__item-icon" aria-hidden="true"></span>
                                             <?php echo \esc_html($tabTitle); ?>
                                            <?php if (!empty($sublinks)) : ?>
                                                <span class="dashicons dashicons-arrow-down-alt2 nxtf-menu__item-icon-angle" aria-hidden="true" data-nav-arrow></span>
                                            <?php endif; ?>
                                        </a>
                                    </div>

                                    <?php if (!empty($sublinks)) : ?>
                                        <ul class="sublinks nxtf-submenu" style="display: none;">
                                            <?php foreach ($sublinks as $sublink) : ?>
                                                <?php
                                                $sublinkId = isset($sublink['id']) ? $sublink['id'] : '';
                                                $sublinkTitle = isset($sublink['title']) ? $sublink['title'] : '';
                                                ?>
                                                <li class="nxtf-submenu__item ">
                                                    <a href="#<?php echo \esc_attr($panelSlug); ?>/<?php echo \esc_attr($tabId); ?>/<?php echo \esc_attr($sublinkId); ?>"
                                                        class="nxtf-sidebar-tab-link-left sublink-item"
                                                        data-id="<?php echo \esc_attr($sublinkId); ?>">
                                                        <?php echo \esc_html($sublinkTitle); ?>
                                                    </a>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </nav>
                    </aside>
                    <?php endif; ?>

                    <!-- Main Content -->
                    <main class="nxtf-content-wrapper">
                        <div class="nxtf-content">
                            <!-- Header Sticky Bar -->
                            <div class="nxtf-content-body">
                                <div class="<?php echo $hasTabs ? 'nxtf-content-inner' : 'nxtf-content-inner nxtf-content-inner--wide'; ?>" data-panel-content="1">
                                    <?php \settings_errors(Config::option('messages')); ?>

                                    <?php foreach ($groups as $group) : ?>
                                        <?php
                                        $groupId = isset($group['id']) ? (string) $group['id'] : '';
                                        $isDeferredSection = $hasTabs && $groupId !== $defaultActiveGroupId;
                                        $isVisibleSection = !$hasTabs;
                                        $sectionClasses = 'content-section nxtf-space-y-8 ' . ($hasTabs ? 'nxtf-section-animate' : 'nxtf-section-spacing');
                                        if ($isVisibleSection) {
                                            $sectionClasses .= ' active';
                                        }
                                        ?>
                                        <div id="section-<?php echo \esc_attr($panelSlug . '-' . $groupId); ?>"
                                            class="<?php echo \esc_attr($sectionClasses); ?>"
                                            data-section-id="<?php echo \esc_attr($groupId); ?>"
                                            data-group-id="<?php echo \esc_attr($groupId); ?>"
                                            data-section-loaded="<?php echo $isDeferredSection ? '0' : '1'; ?>"
                                            style="display: <?php echo $isVisibleSection ? 'block' : 'none'; ?>;">
                                            <header class="nxtf-settings-header">
                                                <h2 class="nxtf-settings-header-title"><?php echo \esc_html($group['title']); ?></h2>
                                                <?php if (!empty($group['description'])) : ?>
                                                    <p><?php echo \esc_html($group['description']); ?></p>
                                                <?php endif; ?>
                                            </header>
                                            <div class="nxtf-space-y-8" data-section-panels="1">
                                                <?php if ($isDeferredSection) : ?>
                                                    <p class="nxtf-text-loading" data-section-loading="1"><?php echo \esc_html__('Loading settings...', 'storeinvoice-print-pdf-invoices-and-packing-slips'); ?></p>
                                                <?php else : ?>
                                                    <?php $this->renderPanels($group['panels'], $options); ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </main>
                </form>

                <!-- Ads Column -->
                <?php $this->renderSidebarCallback(); ?>
            </div>
        </div>
    <?php
    }

}
