<?php
/**
 * Frontend site chatbot widget and AJAX.
 *
 * @package Maca_Menu_List
 */

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

require_once MACA_MENULIST_PLUGIN_DIR . 'includes/site-chat-index.php';

/**
 * Frontend chatbot controller.
 */
class Maca_MenuList_Site_Chat_Frontend {

    /**
     * Whether assets were enqueued.
     *
     * @var bool
     */
    private static $assets_enqueued = false;

    /**
     * Constructor.
     */
    public function __construct() {
        add_shortcode('maca_site_chat', array($this, 'render_shortcode'));
        add_action('wp_enqueue_scripts', array($this, 'maybe_enqueue_floating'));
        add_action('wp_footer', array($this, 'maybe_render_floating'));
        add_action('wp_ajax_maca_site_chat_ask', array($this, 'ajax_ask'));
        add_action('wp_ajax_nopriv_maca_site_chat_ask', array($this, 'ajax_ask'));
    }

    /**
     * Whether chatbot should render on the frontend.
     *
     * @return bool
     */
    private function is_available() {
        return maca_menulist_site_chat_enabled() && maca_menulist_site_chat_has_api_key();
    }

    /**
     * Enqueue chat assets once.
     *
     * @return void
     */
    private function enqueue_assets() {
        if (self::$assets_enqueued) {
            return;
        }

        self::$assets_enqueued = true;

        wp_enqueue_style(
            'maca-menulist-site-chat',
            MACA_MENULIST_PLUGIN_URL . 'assets/css/site-chat.css',
            array(),
            MACA_MENULIST_VERSION
        );

        wp_enqueue_script(
            'maca-menulist-site-chat',
            MACA_MENULIST_PLUGIN_URL . 'assets/js/site-chat.js',
            array(),
            MACA_MENULIST_VERSION,
            true
        );

        wp_localize_script(
            'maca-menulist-site-chat',
            'macaSiteChat',
            array_merge(
                array(
                    'ajaxUrl' => admin_url('admin-ajax.php'),
                    'nonce' => wp_create_nonce('maca_site_chat_ask'),
                ),
                maca_menulist_site_chat_get_guest_ui_strings(),
                array(
                    'assistantName' => maca_menulist_site_chat_get_display_name(),
                    'avatarUrl' => maca_menulist_site_chat_get_avatar_url(),
                    'booking' => maca_menulist_site_chat_get_booking_cta_config(),
                )
            )
        );
    }

    /**
     * Render chat widget markup.
     *
     * @param bool $floating Floating layout.
     * @return string
     */
    private function render_widget($floating = false) {
        if (!$this->is_available()) {
            return '';
        }

        $this->enqueue_assets();

        $classes = 'maca-site-chat';
        if ($floating) {
            $classes .= ' maca-site-chat--floating';
        }

        $display_name = maca_menulist_site_chat_get_display_name();
        $avatar_url = maca_menulist_site_chat_get_avatar_url();
        $strings = maca_menulist_site_chat_get_guest_ui_strings();

        ob_start();
        ?>
        <div class="<?php echo esc_attr($classes); ?>" data-maca-site-chat="1">
            <?php if ($floating) : ?>
                <button type="button" class="maca-site-chat-toggle" aria-expanded="false" aria-controls="maca-site-chat-panel">
                    <?php if ($avatar_url !== '') : ?>
                        <img class="maca-site-chat-toggle-avatar" src="<?php echo esc_url($avatar_url); ?>" alt="" width="40" height="40">
                    <?php else : ?>
                        <span class="maca-site-chat-toggle-label"><?php echo esc_html($strings['chatLabel']); ?></span>
                    <?php endif; ?>
                </button>
            <?php endif; ?>
            <div class="maca-site-chat-panel" id="maca-site-chat-panel" <?php echo $floating ? 'hidden' : ''; ?>>
                <div class="maca-site-chat-header">
                    <div class="maca-site-chat-header-main">
                        <?php if ($avatar_url !== '') : ?>
                            <img class="maca-site-chat-avatar" src="<?php echo esc_url($avatar_url); ?>" alt="" width="36" height="36">
                        <?php endif; ?>
                        <strong class="maca-site-chat-title"><?php echo esc_html($display_name); ?></strong>
                    </div>
                    <?php if ($floating) : ?>
                        <button type="button" class="maca-site-chat-close" aria-label="<?php echo esc_attr($strings['close']); ?>">&times;</button>
                    <?php endif; ?>
                </div>
                <div class="maca-site-chat-messages" role="log" aria-live="polite"></div>
                <form class="maca-site-chat-form">
                    <label class="screen-reader-text" for="maca-site-chat-input"><?php echo esc_html($strings['yourQuestion']); ?></label>
                    <textarea id="maca-site-chat-input" class="maca-site-chat-input" rows="2" placeholder="<?php echo esc_attr($strings['placeholder']); ?>"></textarea>
                    <button type="submit" class="maca-site-chat-send"><?php echo esc_html($strings['send']); ?></button>
                </form>
            </div>
        </div>
        <?php
        return (string) ob_get_clean();
    }

    /**
     * Shortcode handler.
     *
     * @return string
     */
    public function render_shortcode() {
        return $this->render_widget(false);
    }

    /**
     * Enqueue assets when floating mode is on.
     *
     * @return void
     */
    public function maybe_enqueue_floating() {
        if (!$this->is_available() || is_admin()) {
            return;
        }

        if (get_option('maca_menulist_site_chat_floating', '0') !== '1') {
            return;
        }

        $this->enqueue_assets();
    }

    /**
     * Output floating widget in footer.
     *
     * @return void
     */
    public function maybe_render_floating() {
        if (!$this->is_available() || is_admin()) {
            return;
        }

        if (get_option('maca_menulist_site_chat_floating', '0') !== '1') {
            return;
        }

        echo $this->render_widget(true); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }

    /**
     * AJAX: ask the chatbot.
     *
     * @return void
     */
    public function ajax_ask() {
        check_ajax_referer('maca_site_chat_ask', 'nonce');

        $question = isset($_POST['question']) ? sanitize_text_field(wp_unslash($_POST['question'])) : '';
        $history = array();
        $booking_on_page = isset($_POST['booking_on_page']) && wp_unslash($_POST['booking_on_page']) === '1';

        if (isset($_POST['history']) && is_string($_POST['history'])) {
            $decoded = json_decode(wp_unslash($_POST['history']), true);

            if (is_array($decoded)) {
                $history = $decoded;
            }
        }

        $result = maca_menulist_site_chat_ask(
            $question,
            $history,
            array(
                'booking_on_page' => $booking_on_page,
            )
        );

        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }

        wp_send_json_success($result);
    }
}

new Maca_MenuList_Site_Chat_Frontend();
