<?php
/**
 * Hooks that schedule chatbot re-index when indexed content changes.
 *
 * @package Maca_Menu_List
 */

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

/**
 * Notify that indexed chat content may have changed.
 *
 * @return void
 */
function maca_menulist_site_chat_notify_content_changed() {
    if (!function_exists('maca_menulist_site_chat_schedule_reindex')) {
        return;
    }

    maca_menulist_site_chat_schedule_reindex();
}

add_action('maca_menulist_site_chat_content_changed', 'maca_menulist_site_chat_notify_content_changed');

/**
 * Whether an option update should trigger chat re-index.
 *
 * @param string $option Option name.
 * @return bool
 */
function maca_menulist_site_chat_option_triggers_reindex($option) {
    $option = (string) $option;

    $exact = array(
        'maca_menulist_table_booking_hours',
        'maca_menulist_table_booking',
        'maca_menulist_table_booking_waitlist',
        'maca_menulist_table_booking_arrival_notice',
        'maca_menulist_table_booking_arrival_notice_en',
        'maca_menulist_table_booking_button_text',
        'maca_menulist_table_booking_button_text_en',
        'maca_menulist_table_booking_title_text',
        'maca_menulist_table_booking_title_text_en',
        'maca_menulist_table_booking_guest_cancel',
        'maca_menulist_info_hub_enabled',
    );

    if (in_array($option, $exact, true)) {
        return true;
    }

    $prefixes = array(
        'maca_menulist_menu_footer_',
        'maca_menulist_table_booking_',
    );

    foreach ($prefixes as $prefix) {
        if (strpos($option, $prefix) === 0) {
            return true;
        }
    }

    return false;
}

/**
 * Re-index when relevant plugin options change.
 *
 * @param string $option    Option name.
 * @param mixed  $old_value Old value.
 * @param mixed  $value     New value.
 * @return void
 */
function maca_menulist_site_chat_on_option_updated($option, $old_value, $value) {
    unset($old_value, $value);

    if (!maca_menulist_site_chat_option_triggers_reindex($option)) {
        return;
    }

    maca_menulist_site_chat_notify_content_changed();
}

add_action('updated_option', 'maca_menulist_site_chat_on_option_updated', 10, 3);

/**
 * Re-index when an indexed WordPress page is updated.
 *
 * @param int $post_id Post ID.
 * @return void
 */
function maca_menulist_site_chat_on_save_post($post_id) {
    if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) {
        return;
    }

    $post = get_post($post_id);

    if (!$post instanceof WP_Post || $post->post_type !== 'page') {
        return;
    }

    $selected = maca_menulist_site_chat_get_wp_page_ids();

    if (empty($selected) || !in_array((int) $post_id, $selected, true)) {
        return;
    }

    maca_menulist_site_chat_notify_content_changed();
}

add_action('save_post', 'maca_menulist_site_chat_on_save_post', 20, 1);
