<?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_enqueue_scripts', array( $this, 'enqueue' ) );
        add_action( 'plugins_loaded', array( $this, 'maybe_migrate' ), 6 );

        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' ) );
    }

    /* -- DB migration: add is_featured column ----------------------- */
    public function maybe_migrate() {
        global $wpdb;
        $col = $wpdb->get_var( "SHOW COLUMNS FROM {$wpdb->prefix}yatoon_services LIKE 'is_featured'" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        if ( ! $col ) {
            $wpdb->query( "ALTER TABLE {$wpdb->prefix}yatoon_services ADD COLUMN is_featured TINYINT(1) DEFAULT 0 AFTER is_active" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        }
    }

    /* -- Enqueue assets (load on all frontend pages) ----------------- */
    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
        );
        wp_localize_script( 'yatoon-service-menu', 'yatoonMenuData', array(
            'headerOffset' => (int) get_option( 'yatoon_header_offset', 0 ),
        ) );

        // 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 ) {
        $atts = shortcode_atts( array( 'title' => '' ), $atts, 'yatoon_service_menu' );

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

        $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" style="padding:30px 40px!important;border:none!important;box-shadow:none!important;">

            <?php if ( ! empty( $featured ) ) : ?>
            <div class="ysm-featured-wrap">
                <div class="ysm-featured-header">
                    <h2 class="ysm-featured-title">Featured Services</h2>
                    <div class="ysm-featured-arrows">
                        <button class="ysm-feat-arrow ysm-feat-prev" aria-label="Previous">&#8249;</button>
                        <button class="ysm-feat-arrow ysm-feat-next" aria-label="Next">&#8250;</button>
                    </div>
                </div>
                <div class="ysm-featured-track">
                    <?php foreach ( $featured as $svc ) : ?>
                    <a class="ysm-feat-card" href="<?php echo esc_url( $this->get_booking_url( $svc->id ) ); ?>" aria-label="<?php echo esc_attr( sprintf( __( 'Book %s', 'yatoon-booking-system' ), $svc->name ) ); ?>">
                        <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">💅</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">🔍</span>
                    <input type="text" class="ysm-search-input" placeholder="Search services...">
                    <button class="ysm-search-clear">✕</button>
                </div>
            </div>

            <?php if ( ! empty( $categories ) ) :
                $cat_count = count( $categories );
            ?>
            <nav class="ysm-cat-nav" style="border:none!important;box-shadow:none!important;" 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 class="ysm-cat-tab<?php echo $i === 0 ? ' active' : ''; ?>"
                                    style="color:<?php echo $i === 0 ? '#fff' : '#374151'; ?>!important;background:<?php echo $i === 0 ? '#050505' : '#fff'; ?>!important;border:1px solid <?php echo $i === 0 ? '#050505' : '#e5e7eb'; ?>!important;border-radius:999px!important;box-shadow:none!important;"
                                    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 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">Search Results</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 ) : ?>
                        <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( sprintf( __( 'Book %s', 'yatoon-booking-system' ), $svc->name ) ); ?>">
                            <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' ); }
        $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();
    }
}
