<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.DirectDatabaseQuery.SchemaChange
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
/**
 * Admin view: Service Menu - Featured Items + Category Order
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

global $wpdb;
$services = $wpdb->get_results(
    "SELECT * FROM {$wpdb->prefix}yatoon_services WHERE is_active = 1 ORDER BY sort_order ASC, name ASC"
);

$all_cats = array();
foreach ( $services as $svc ) {
    $cat = $svc->category ?: 'Other';
    if ( ! in_array( $cat, $all_cats, true ) ) { $all_cats[] = $cat;
    }
}

// Apply saved order
$saved_order = get_option( 'yatoon_menu_cat_order', array() );
if ( ! empty( $saved_order ) ) {
    $ordered = array();
    foreach ( $saved_order as $c ) {
        if ( in_array( $c, $all_cats, true ) ) { $ordered[] = $c;
        }
    }
    foreach ( $all_cats as $c ) {
        if ( ! in_array( $c, $ordered, true ) ) { $ordered[] = $c;
        }
    }
    $all_cats = $ordered;
}

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

$nonce        = wp_create_nonce( 'yatoon_menu_nonce' );
$menu_page    = get_option( 'yatoon_menu_page_url', '' );
// 4.5.0: this used to ALTER TABLE from inside the page render when the column
// was missing. Schema changes now happen once in
// yatoon_services_featured_migration() on plugins_loaded. All that is left
// here is a read-only guard so a site whose migration has not run yet (or
// failed) renders an empty featured list instead of a fatal.
$col_check = $wpdb->get_results( "SHOW COLUMNS FROM {$wpdb->prefix}yatoon_services LIKE 'is_featured'" ); // phpcs:ignore
if ( $col_check ) {
    $featured_ids = array_map( 'intval', $wpdb->get_col( // phpcs:ignore
        "SELECT id FROM {$wpdb->prefix}yatoon_services WHERE is_featured = 1"
    ) );
} else {
    $featured_ids = array();
}
?>
<div class="wrap" id="ysm-admin-wrap">
    <style>
        #ysm-admin-wrap .ysm-table-wrap {
            width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        #ysm-admin-wrap .ysm-table-wrap .wp-list-table {
            min-width: 760px;
        }
    </style>
    <h1><?php esc_html_e( 'Service Menu - Featured Items', 'yatoon-booking-system' ); ?></h1>

    <p class="description" style="margin-bottom:16px;">
        <?php esc_html_e( 'Check services to show them in the Featured carousel. Drag categories to reorder.
        Use shortcode', 'yatoon-booking-system' ); ?> <code><?php esc_html_e( '[yatoon_service_menu]', 'yatoon-booking-system' ); ?></code> <?php esc_html_e( 'on any page.', 'yatoon-booking-system' ); ?>
    </p>

    <!-- Menu page URL -->
    <div style="background:#fff;border:1px solid #ddd;border-radius:6px;padding:16px 20px;margin-bottom:24px;max-width:600px;">
        <h3 style="margin:0 0 10px;"><?php esc_html_e( 'Service Menu Page URL', 'yatoon-booking-system' ); ?></h3>
        <div style="display:flex;gap:10px;align-items:center;">
            <input type="url" id="ysm-menu-page-url" value="<?php echo esc_attr( $menu_page ); ?>"
                   placeholder="https://yoursite.com/services" class="regular-text" style="flex:1;">
            <button id="ysm-save-url" class="button button-primary"><?php esc_html_e( 'Save', 'yatoon-booking-system' ); ?></button>
            <?php if ( $menu_page ) : ?>
            <a href="<?php echo esc_url( $menu_page ); ?>" target="_blank" class="button"><?php esc_html_e( 'View Page', 'yatoon-booking-system' ); ?></a>
            <?php endif; ?>
        </div>
        <span id="ysm-url-msg" class="yatoon-inline-status" style="display:none;"><span aria-hidden="true">&#10003;</span> <?php esc_html_e( 'Saved', 'yatoon-booking-system' ); ?></span>
    </div>

    <?php if ( empty( $services ) ) : ?>
        <div class="notice notice-warning"><p><?php esc_html_e( 'No active services found.', 'yatoon-booking-system' ); ?> <a href="<?php echo esc_url( admin_url('admin.php?page=yatoon-booking-system&tab=services') ); ?>"><?php esc_html_e( 'Go to Services', 'yatoon-booking-system' ); ?></a> <?php esc_html_e( 'to add your first service, then come back here to configure the Service Menu.', 'yatoon-booking-system' ); ?></p></div>
    <?php else : ?>

    <!-- Category order -->
    <div style="background:#fff;border:1px solid #ddd;border-radius:6px;padding:16px 20px;margin-bottom:24px;max-width:600px;">
        <h3 style="margin:0 0 8px;"><?php esc_html_e( 'Category Display Order', 'yatoon-booking-system' ); ?></h3>
        <p class="description" style="margin-bottom:12px;"><?php esc_html_e( 'Enter a number to set the display order (lower = first).', 'yatoon-booking-system' ); ?></p>
        <table style="width:100%;border-collapse:collapse;">
            <?php foreach ( $all_cats as $i => $cat ) : ?>
            <tr style="border-bottom:1px solid #f0f0f0;">
                <td style="padding:8px 12px;font-weight:600;"><?php echo esc_html( $cat ); ?></td>
                <td style="padding:8px 12px;width:80px;">
                    <input type="number" class="ysm-cat-order-input"
                           data-cat="<?php echo esc_attr( $cat ); ?>"
                           value="<?php echo esc_attr( $i + 1 ); ?>"
                           min="1" max="99"
                           style="width:60px;text-align:center;padding:4px;">
                </td>
            </tr>
            <?php endforeach; ?>
        </table>
        <button id="ysm-save-order" class="button button-primary" style="margin-top:12px;"><?php esc_html_e( 'Save Order', 'yatoon-booking-system' ); ?></button>
        <span id="ysm-order-msg" class="yatoon-inline-status" style="display:none;"><span aria-hidden="true">&#10003;</span> <?php esc_html_e( 'Saved', 'yatoon-booking-system' ); ?></span>
    </div>

    <div style="margin-bottom:12px;">
        <strong id="ysm-feat-count"><?php echo esc_html( count( $featured_ids ) ); ?></strong> <?php esc_html_e( 'service(s) featured', 'yatoon-booking-system' ); ?>
        <span style="color:#aaa;font-size:13px;"><?php esc_html_e( '(max 12 shown in carousel)', 'yatoon-booking-system' ); ?></span>
    </div>

    <!-- Services by category -->
    <?php foreach ( $categories as $cat => $items ) : ?>
    <div style="margin-bottom:24px;">
        <h3 style="margin:0 0 8px;font-size:15px;color:#555;text-transform:uppercase;letter-spacing:.5px;font-weight:700;">
            <?php echo esc_html( $cat ); ?>
        </h3>
        <div class="ysm-table-wrap">
        <table class="wp-list-table widefat fixed" style="max-width:800px;">
            <thead>
                <tr>
                    <th style="width:40px;"><?php esc_html_e( 'Featured', 'yatoon-booking-system' ); ?></th>
                    <th style="width:70px;"><?php esc_html_e( 'Image', 'yatoon-booking-system' ); ?></th>
                    <th><?php esc_html_e( 'Service Name', 'yatoon-booking-system' ); ?></th>
                    <th style="width:80px;"><?php esc_html_e( 'Price', 'yatoon-booking-system' ); ?></th>
                    <th style="width:80px;"><?php esc_html_e( 'Duration', 'yatoon-booking-system' ); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ( $items as $svc ) : ?>
                <tr>
                    <td style="text-align:center;">
                        <input type="checkbox" class="ysm-featured-cb"
                               data-id="<?php echo absint( $svc->id ); ?>"
                               <?php checked( in_array( (int) $svc->id, $featured_ids, true ) ); ?>
                               style="width:18px;height:18px;cursor:pointer;">
                    </td>
                    <td>
                        <?php if ( $svc->image_url ) : ?>
                        <img src="<?php echo esc_url( $svc->image_url ); ?>"
                             style="width:50px;height:50px;object-fit:cover;border-radius:6px;display:block;">
                        <?php else : ?>
                        <div style="width:50px;height:50px;background:#f5f5f5;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:22px;">💅</div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <strong><?php echo esc_html( $svc->name ); ?></strong>
                        <?php if ( $svc->description ) : ?>
                        <br><small style="color:#888;"><?php echo esc_html( wp_trim_words( $svc->description, 12 ) ); ?></small>
                        <?php endif; ?>
                    </td>
                    <td>$<?php echo esc_html( number_format( (float) $svc->price, 2 ) ); ?></td>
                    <td><?php echo esc_html( $svc->duration_minutes . ' min' ); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>
    </div>
    <?php endforeach; ?>

    <?php endif; ?>
</div>

<script>
(function($){
    var nonce   = <?php echo wp_json_encode( $nonce ); ?>;
    var ajaxUrl = <?php echo wp_json_encode( admin_url( 'admin-ajax.php' ) ); ?>;

    // Toggle featured
    $(document).on('change', '.ysm-featured-cb', function(){
        $.post(ajaxUrl, {
            action: 'yatoon_toggle_featured', nonce: nonce,
            service_id: $(this).data('id'), featured: $(this).is(':checked') ? 1 : 0
        }).done(function(){ $('#ysm-feat-count').text($('.ysm-featured-cb:checked').length); });
    });

    // Save menu URL
    $('#ysm-save-url').on('click', function(){
        $.post(ajaxUrl, { action: 'yatoon_save_menu_settings', nonce: nonce, menu_page_url: $('#ysm-menu-page-url').val() })
         .done(function(){ var $m=$('#ysm-url-msg'); $m.show(); setTimeout(function(){ $m.fadeOut(); }, 2000); });
    });

    // Save category order by number input
    $('#ysm-save-order').on('click', function(){
        var cats = [];
        $('.ysm-cat-order-input').each(function(){
            cats.push({ cat: $(this).data('cat'), num: parseInt($(this).val(), 10) || 99 });
        });
        cats.sort(function(a, b){ return a.num - b.num; });
        var order = cats.map(function(c){ return c.cat; });
        $.post(ajaxUrl, {
            action: 'yatoon_save_cat_order',
            nonce: nonce,
            order_json: JSON.stringify(order)
        }).done(function(res){
            if (res.success) {
                var $m = $('#ysm-order-msg');
                $m.show();
                setTimeout(function(){ $m.fadeOut(); }, 2000);
            }
        });
    });
}(jQuery));
</script>
