<?php
// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.InputNotValidated
/**
 * Yatoon Service Menu - shortcode [sbs_service_menu]
 * Displays booking services like a restaurant menu with Featured carousel
 * and sticky category navigation. Service cards link into the booking flow.
 */

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

class YATOON_Service_Menu {

    public function __construct() {
        add_shortcode( 'yatoon_service_menu', array( $this, 'render' ) );

        add_action( 'wp_ajax_yatoon_toggle_featured',    array( $this, 'ajax_toggle_featured' ) );
        add_action( 'wp_ajax_yatoon_save_menu_settings', array( $this, 'ajax_save_menu_settings' ) );
        add_action( 'wp_ajax_yatoon_save_cat_order',     array( $this, 'ajax_save_cat_order' ) );
    }

    /* -- Enqueue assets only when the shortcode is rendered ---------- */
    public function enqueue() {
        if ( is_admin() ) { return;
        }
        wp_enqueue_style(
            'yatoon-service-menu',
            SBS_PLUGIN_URL . 'assets/css/service-menu' . YATOON_ASSET_SUFFIX . '.css',
            array(),
            SBS_VERSION
        );
        wp_enqueue_style(
            'yatoon-apple-polish',
            SBS_PLUGIN_URL . 'assets/css/apple-polish' . YATOON_ASSET_SUFFIX . '.css',
            array( 'yatoon-service-menu' ),
            SBS_VERSION
        );
        wp_enqueue_style(
            'yatoon-design-system',
            SBS_PLUGIN_URL . 'assets/css/yatoon-design-system' . YATOON_ASSET_SUFFIX . '.css',
            array( 'yatoon-apple-polish' ),
            SBS_VERSION
        );
        wp_add_inline_style( 'yatoon-apple-polish', yatoon_apple_polish_inline_css() );
        wp_enqueue_script(
            'yatoon-service-menu',
            SBS_PLUGIN_URL . 'assets/js/service-menu' . YATOON_ASSET_SUFFIX . '.js',
            array( 'jquery' ),
            SBS_VERSION,
            true
        );
        yatoon_set_script_i18n( 'yatoon-service-menu' );
        wp_localize_script( 'yatoon-service-menu', 'yatoonMenuData', array(
            'headerOffset' => (int) get_option( 'yatoon_header_offset', 0 ),
            'strings'      => array(
                'noServices' => __( 'No services found', 'yatoon-booking-system' ),
            ),
        ) );

        // Inject background color settings as inline CSS
        $page_bg = get_option( 'yatoon_page_bg_color', '' );
        $card_bg = get_option( 'yatoon_card_bg_color', '' );
        $inline  = '';
        if ( $page_bg ) {
            $inline .= '#yatoon-svc-wrap { background: ' . sanitize_hex_color( $page_bg ) . ' !important; }';
        }
        if ( $card_bg ) {
            $c = sanitize_hex_color( $card_bg );
            $inline .= ':root { --sbs-card-bg: ' . $c . '; }';
            $inline .= '#yatoon-svc-wrap .ysm-inner,';
            $inline .= '#yatoon-svc-wrap .ysm-cat-nav,';
            $inline .= '#yatoon-svc-wrap .ysm-cat-dropdown,';
            $inline .= '#yatoon-svc-wrap .ysm-item,';
            $inline .= '#yatoon-svc-wrap .ysm-search-box,';
            $inline .= '#yatoon-svc-wrap .ysm-feat-card';
            $inline .= ' { background: ' . $c . ' !important; }';
        }
        if ( $inline ) {
            wp_add_inline_style( 'yatoon-service-menu', $inline );
        }
    }

    /* -- Fetch data ------------------------------------------------- */
    private function get_services() {
        global $wpdb;
        return $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            "SELECT * FROM {$wpdb->prefix}yatoon_services WHERE is_active = 1 ORDER BY sort_order ASC, name ASC"
        );
    }

    private function get_featured() {
        global $wpdb;
        return $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            "SELECT * FROM {$wpdb->prefix}yatoon_services WHERE is_active = 1 AND is_featured = 1 ORDER BY sort_order ASC LIMIT 12"
        );
    }

    private function get_booking_url( $service_id ) {
        $base_url = get_option( 'yatoon_book_new_url', '' );
        if ( ! $base_url ) {
            $base_url = get_option( 'yatoon_booking_page_url', '' );
        }
        if ( ! $base_url ) {
            $base_url = get_option( 'yatoon_onboarding_booking_page_url', '' );
        }
        if ( ! $base_url ) {
            $base_url = home_url( '/' );
        }

        return add_query_arg( 'yatoon_service', absint( $service_id ), $base_url );
    }

    /* -- Shortcode render ------------------------------------------- */
    public function render( $atts ) {
        $this->enqueue();
        $atts = shortcode_atts( array( 'title' => '', 'category' => '' ), $atts, 'yatoon_service_menu' );

        $services  = $this->get_services();
        $featured  = $this->get_featured();

        $category_filter = sanitize_text_field( $atts['category'] );
        if ( '' !== $category_filter ) {
            $services = array_values( array_filter( $services, static function ( $service ) use ( $category_filter ) {
                return 0 === strcasecmp( trim( (string) $service->category ), trim( $category_filter ) );
            } ) );
            $featured = array_values( array_filter( $featured, static function ( $service ) use ( $category_filter ) {
                return 0 === strcasecmp( trim( (string) $service->category ), trim( $category_filter ) );
            } ) );
        }

        $categories = array();
        foreach ( $services as $svc ) {
            $cat = $svc->category ? $svc->category : 'Other';
            $categories[ $cat ][] = $svc;
        }

        // Apply saved category order
        $saved_order = get_option( 'yatoon_menu_cat_order', array() );
        if ( ! empty( $saved_order ) ) {
            $ordered = array();
            foreach ( $saved_order as $cat ) {
                if ( isset( $categories[ $cat ] ) ) {
                    $ordered[ $cat ] = $categories[ $cat ];
                    unset( $categories[ $cat ] );
                }
            }
            $categories = array_merge( $ordered, $categories );
        }

        ob_start();
        ?>
        <div id="yatoon-svc-wrap">
        <div class="ysm-inner">

            <?php if ( ! empty( $featured ) ) : ?>
            <div class="ysm-featured-wrap">
                <div class="ysm-featured-header">
                    <h2 class="ysm-featured-title"><?php esc_html_e( 'Featured Services', 'yatoon-booking-system' ); ?></h2>
                    <div class="ysm-featured-arrows">
                        <button type="button" class="ysm-feat-arrow ysm-feat-prev" aria-label="<?php esc_attr_e( 'Previous service', 'yatoon-booking-system' ); ?>">&#8249;</button>
                        <button type="button" class="ysm-feat-arrow ysm-feat-next" aria-label="<?php esc_attr_e( 'Next service', 'yatoon-booking-system' ); ?>">&#8250;</button>
                    </div>
                </div>
                <div class="ysm-featured-track">
                    <?php foreach ( $featured as $svc ) : ?>
                    <?php
                    // translators: %s is the name of the service being booked (e.g. "Book Haircut").
                    $ysm_feat_book_label = sprintf( __( 'Book %s', 'yatoon-booking-system' ), $svc->name );
                    ?>
                    <a class="ysm-feat-card" href="<?php echo esc_url( $this->get_booking_url( $svc->id ) ); ?>" aria-label="<?php echo esc_attr( $ysm_feat_book_label ); ?>">
                        <div class="ysm-feat-img-wrap">
                            <?php if ( $svc->image_url ) : ?>
                                <img class="ysm-feat-img" src="<?php echo esc_url( $svc->image_url ); ?>" alt="<?php echo esc_attr( $svc->name ); ?>" loading="lazy">
                            <?php else : ?>
                                <div class="ysm-feat-no-img" aria-hidden="true">&#10022;</div>
                            <?php endif; ?>
                        </div>
                        <div class="ysm-feat-name"><?php echo esc_html( $svc->name ); ?></div>
                        <div class="ysm-feat-price"><?php echo esc_html__( 'From', 'yatoon-booking-system' ); ?> $<?php echo esc_html( number_format( (float) $svc->price, 2 ) ); ?></div>
                    </a>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="ysm-search-wrap">
                <div class="ysm-search-box">
                    <span class="ysm-search-icon" aria-hidden="true">&#128269;</span>
                    <input type="search" class="ysm-search-input" aria-label="<?php esc_attr_e( 'Search services', 'yatoon-booking-system' ); ?>" placeholder="<?php esc_attr_e( 'Search services...', 'yatoon-booking-system' ); ?>">
                    <button type="button" class="ysm-search-clear" aria-label="<?php esc_attr_e( 'Clear service search', 'yatoon-booking-system' ); ?>">&times;</button>
                </div>
            </div>

            <?php if ( ! empty( $categories ) ) :
                $cat_count = count( $categories );
            ?>
            <nav class="ysm-cat-nav" aria-label="<?php esc_attr_e( 'Service categories', 'yatoon-booking-system' ); ?>" data-cat-count="<?php echo esc_attr( $cat_count ); ?>">
                <div class="ysm-cat-nav-row">
                    <ul class="ysm-cat-nav-inner">
                        <?php foreach ( array_keys( $categories ) as $i => $cat ) : ?>
                        <li>
                            <button type="button" class="ysm-cat-tab<?php echo $i === 0 ? ' active' : ''; ?>"
                                    aria-pressed="<?php echo $i === 0 ? 'true' : 'false'; ?>"
                                    data-cat="<?php echo esc_attr( sanitize_title( $cat ) ); ?>">
                                <?php echo esc_html( $cat ); ?>
                            </button>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <ul class="ysm-cat-dropdown" hidden>
                    <?php foreach ( array_keys( $categories ) as $i => $cat ) : ?>
                    <li>
                        <button type="button" class="ysm-cat-dropdown-item<?php echo $i === 0 ? ' active' : ''; ?>"
                                data-cat="<?php echo esc_attr( sanitize_title( $cat ) ); ?>">
                            <?php echo esc_html( $cat ); ?>
                        </button>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </nav>

            <div class="ysm-menu-body">
                <div class="ysm-search-results" hidden>
                    <p class="ysm-section-label"><?php esc_html_e( 'Search Results', 'yatoon-booking-system' ); ?></p>
                    <ul class="ysm-items-list ysm-search-list"></ul>
                </div>

                <?php foreach ( $categories as $cat => $items ) :
                    $cat_slug = sanitize_title( $cat );
                ?>
                <section class="ysm-section" id="ysm-cat-<?php echo esc_attr( $cat_slug ); ?>" data-cat="<?php echo esc_attr( $cat_slug ); ?>">
                    <h3 class="ysm-section-title" style="border:none!important;box-shadow:none!important;"><?php echo esc_html( $cat ); ?></h3>
                    <ul class="ysm-items-list" style="border:none!important;border-left:none!important;box-shadow:none!important;padding-left:0!important;margin-left:0!important;">
                        <?php foreach ( $items as $svc ) : ?>
                        <?php
                        // translators: %s is the name of the service being booked (e.g. "Book Haircut").
                        $ysm_item_book_label = sprintf( __( 'Book %s', 'yatoon-booking-system' ), $svc->name );
                        ?>
                        <li class="ysm-item"
                            style="border-top:none!important;border-left:none!important;border-right:none!important;border-bottom:1px solid #f0f0f0!important;box-shadow:none!important;"
                            data-name="<?php echo esc_attr( strtolower( $svc->name ) ); ?>"
                            data-desc="<?php echo esc_attr( strtolower( $svc->description ?? '' ) ); ?>">
                            <a class="ysm-item-link" href="<?php echo esc_url( $this->get_booking_url( $svc->id ) ); ?>" aria-label="<?php echo esc_attr( $ysm_item_book_label ); ?>">
                            <div class="ysm-item-info" style="border:none!important;border-left:none!important;box-shadow:none!important;">
                                <p class="ysm-item-name"><?php echo esc_html( $svc->name ); ?></p>
                                <?php if ( $svc->duration_minutes ) : ?>
                                <p class="ysm-item-duration"><?php echo esc_html( $svc->duration_minutes . ' min' ); ?></p>
                                <?php endif; ?>
                                <?php if ( $svc->description ) : ?>
                                <p class="ysm-item-desc"><?php echo esc_html( $svc->description ); ?></p>
                                <?php endif; ?>
                                <p class="ysm-item-meta">
                                    <span class="ysm-item-price"><?php echo esc_html__( 'From', 'yatoon-booking-system' ); ?> $<?php echo esc_html( number_format( (float) $svc->price, 2 ) ); ?></span>
                                </p>
                            </div>
                            <?php if ( $svc->image_url ) : ?>
                            <div class="ysm-item-img-wrap">
                                <img class="ysm-item-img" src="<?php echo esc_url( $svc->image_url ); ?>" alt="<?php echo esc_attr( $svc->name ); ?>" loading="lazy">
                            </div>
                            <?php else : ?>
                            <div class="ysm-item-img-wrap ysm-item-no-img"></div>
                            <?php endif; ?>
                            </a>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </section>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

        </div><!-- /.ysm-inner -->
        </div><!-- /#yatoon-svc-wrap -->
        <?php
        return ob_get_clean();
    }

    /* -- AJAX: toggle featured -------------------------------------- */
    public function ajax_toggle_featured() {
        check_ajax_referer( 'yatoon_menu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error(); }
        global $wpdb;
        $id  = absint( $_POST['service_id'] ?? 0 );
        $val = absint( $_POST['featured'] ?? 0 );
        $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            $wpdb->prefix . 'yatoon_services',
            array( 'is_featured' => $val ? 1 : 0 ),
            array( 'id' => $id ),
            array( '%d' ), array( '%d' )
        );
        wp_send_json_success();
    }

    /* -- AJAX: save category order ---------------------------------- */
    public function ajax_save_cat_order() {
        check_ajax_referer( 'yatoon_menu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error(); }
        $json  = isset( $_POST['order_json'] ) ? wp_unslash( $_POST['order_json'] ) : '[]';
        $order = json_decode( $json, true );
        if ( ! is_array( $order ) ) { wp_send_json_error( __( 'Invalid order data', 'yatoon-booking-system' ) ); }
        $order = array_map( 'sanitize_text_field', $order );
        update_option( 'yatoon_menu_cat_order', $order );
        wp_send_json_success();
    }

    /* -- AJAX: save menu page URL ----------------------------------- */
    public function ajax_save_menu_settings() {
        check_ajax_referer( 'yatoon_menu_nonce', 'nonce' );
        if ( ! current_user_can( 'manage_options' ) ) { wp_send_json_error(); }
        update_option( 'yatoon_menu_page_url', esc_url_raw( $_POST['menu_page_url'] ?? '' ) );
        wp_send_json_success();
    }
}
