<?php
/**
 * Opening hours fields for settings.
 *
 * @package Maca_MenuList
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Render weekly opening hours fields (embedded in the main settings form or wizard).
 *
 * @param array<string, mixed> $args {
 *     @type array|null $hours           Override hours (closed/windows per weekday).
 *     @type bool       $for_onboarding  Wizard mode (same fields; booking note hidden).
 *     @type bool       $show_booking_note Show table-booking slot note when Pro booking is licensed.
 * }
 */
function maca_menulist_render_opening_hours_fields($args = array()) {
    $args = wp_parse_args(
        is_array($args) ? $args : array(),
        array(
            'hours'             => null,
            'for_onboarding'    => false,
            'show_booking_note' => true,
        )
    );

    $hours = is_array($args['hours']) ? $args['hours'] : maca_menulist_get_booking_hours();
    $labels = maca_menulist_weekday_labels();
    $open_label = __('Open', 'maca-restu-pro');

    if (
        $args['show_booking_note']
        && !$args['for_onboarding']
        && maca_menulist_pro_has_feature('table_bookings')
    ) {
        $slot_duration = maca_menulist_table_booking_slot_duration();
        ?>
        <p class="description">
            <?php
            printf(
                /* translators: %d: slot duration in minutes */
                esc_html__('Each table booking lasts %d minutes when table reservations are enabled. Guests choose from 30-minute slots within these hours. Booking duration is set under maca Restu → Table Reservations → Table settings.', 'maca-restu-pro'),
                (int) $slot_duration
            );
            ?>
        </p>
        <?php
    }
    ?>
    <p class="description"><?php esc_html_e('Add one or more time windows per day — for example lunch 11:00–14:00 and dinner 17:00–22:00.', 'maca-restu-pro'); ?></p>

    <table class="form-table widefat maca-opening-hours-table" role="presentation">
        <thead>
            <tr>
                <th scope="col"><?php esc_html_e('Day', 'maca-restu-pro'); ?></th>
                <th scope="col"><?php echo esc_html($open_label); ?></th>
                <th scope="col"><?php esc_html_e('Time windows', 'maca-restu-pro'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php foreach (maca_menulist_get_opening_hours_day_order(true) as $day) : ?>
                <?php
                $day_hours = isset($hours[ $day ])
                    ? maca_menulist_normalize_stored_day_hours($hours[ $day ])
                    : maca_menulist_normalize_stored_day_hours(array('closed' => false));
                $windows = $day_hours['windows'];
                ?>
                <tr class="maca-opening-hours-day-row" data-day="<?php echo esc_attr((string) $day); ?>">
                    <th scope="row"><strong><?php echo esc_html($labels[ $day ]); ?></strong></th>
                    <td>
                        <label>
                            <input type="checkbox" class="maca-opening-hours-is-open" name="hours[<?php echo esc_attr((string) $day); ?>][is_open]" value="1" <?php checked(empty($day_hours['closed'])); ?>>
                            <?php echo esc_html($open_label); ?>
                        </label>
                    </td>
                    <td>
                        <div class="maca-opening-hours-windows" data-day="<?php echo esc_attr((string) $day); ?>">
                            <?php foreach ($windows as $index => $window) : ?>
                                <div class="maca-opening-hours-window-row">
                                    <label class="screen-reader-text" for="hours-<?php echo esc_attr((string) $day); ?>-open-<?php echo esc_attr((string) $index); ?>"><?php esc_html_e('From', 'maca-restu-pro'); ?></label>
                                    <input type="time" id="hours-<?php echo esc_attr((string) $day); ?>-open-<?php echo esc_attr((string) $index); ?>" name="hours[<?php echo esc_attr((string) $day); ?>][windows][<?php echo esc_attr((string) $index); ?>][open]" value="<?php echo esc_attr($window['open']); ?>">
                                    <span aria-hidden="true">–</span>
                                    <label class="screen-reader-text" for="hours-<?php echo esc_attr((string) $day); ?>-close-<?php echo esc_attr((string) $index); ?>"><?php esc_html_e('To', 'maca-restu-pro'); ?></label>
                                    <input type="time" id="hours-<?php echo esc_attr((string) $day); ?>-close-<?php echo esc_attr((string) $index); ?>" name="hours[<?php echo esc_attr((string) $day); ?>][windows][<?php echo esc_attr((string) $index); ?>][close]" value="<?php echo esc_attr($window['close']); ?>">
                                    <button type="button" class="button-link maca-opening-hours-remove-window" <?php echo count($windows) <= 1 ? 'hidden' : ''; ?>><?php esc_html_e('Remove', 'maca-restu-pro'); ?></button>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="button button-small maca-opening-hours-add-window" data-day="<?php echo esc_attr((string) $day); ?>"><?php esc_html_e('Add time window', 'maca-restu-pro'); ?></button>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <template id="maca-opening-hours-window-template">
        <div class="maca-opening-hours-window-row">
            <label class="screen-reader-text maca-opening-hours-open-label"><?php esc_html_e('From', 'maca-restu-pro'); ?></label>
            <input type="time" class="maca-opening-hours-open-input" value="11:00">
            <span aria-hidden="true">–</span>
            <label class="screen-reader-text maca-opening-hours-close-label"><?php esc_html_e('To', 'maca-restu-pro'); ?></label>
            <input type="time" class="maca-opening-hours-close-input" value="22:00">
            <button type="button" class="button-link maca-opening-hours-remove-window"><?php esc_html_e('Remove', 'maca-restu-pro'); ?></button>
        </div>
    </template>

    <script>
        (function () {
            var template = document.getElementById('maca-opening-hours-window-template');
            if (!template) {
                return;
            }

            function reindexWindows(container, day) {
                var rows = container.querySelectorAll('.maca-opening-hours-window-row');
                rows.forEach(function (row, index) {
                    var openInput = row.querySelector('.maca-opening-hours-open-input, input[type="time"]:first-of-type');
                    var closeInput = row.querySelector('.maca-opening-hours-close-input, input[type="time"]:last-of-type');
                    var removeBtn = row.querySelector('.maca-opening-hours-remove-window');

                    if (openInput) {
                        openInput.name = 'hours[' + day + '][windows][' + index + '][open]';
                        openInput.id = 'hours-' + day + '-open-' + index;
                    }
                    if (closeInput) {
                        closeInput.name = 'hours[' + day + '][windows][' + index + '][close]';
                        closeInput.id = 'hours-' + day + '-close-' + index;
                    }
                    if (removeBtn) {
                        removeBtn.hidden = rows.length <= 1;
                    }
                });
            }

            document.querySelectorAll('.maca-opening-hours-add-window').forEach(function (button) {
                button.addEventListener('click', function () {
                    var day = button.getAttribute('data-day');
                    var container = document.querySelector('.maca-opening-hours-windows[data-day="' + day + '"]');
                    if (!container) {
                        return;
                    }

                    var clone = template.content.firstElementChild.cloneNode(true);
                    container.appendChild(clone);
                    reindexWindows(container, day);
                });
            });

            document.addEventListener('click', function (event) {
                var removeBtn = event.target.closest('.maca-opening-hours-remove-window');
                if (!removeBtn) {
                    return;
                }

                var row = removeBtn.closest('.maca-opening-hours-window-row');
                var container = removeBtn.closest('.maca-opening-hours-windows');
                if (!row || !container) {
                    return;
                }

                if (container.querySelectorAll('.maca-opening-hours-window-row').length <= 1) {
                    return;
                }

                row.remove();
                reindexWindows(container, container.getAttribute('data-day'));
            });
        })();
    </script>
    <?php
}
