<?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', '' );
// Check column exists before querying (handles fresh installs before migration)
$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 {
    // Column not yet created - run migration then retry
    $wpdb->query( "ALTER TABLE {$wpdb->prefix}yatoon_services ADD COLUMN is_featured tinyint(1) DEFAULT 0" ); // phpcs:ignore
    $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>Service Menu - Featured Items</h1>

    <p class="description" style="margin-bottom:16px;">
        Check services to show them in the Featured carousel. Drag categories to reorder.
        Use shortcode <code>[yatoon_service_menu]</code> on any page.
    </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;">Service Menu Page URL</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">Save</button>
            <?php if ( $menu_page ) : ?>
            <a href="<?php echo esc_url( $menu_page ); ?>" target="_blank" class="button">View Page</a>
            <?php endif; ?>
        </div>
        <span id="ysm-url-msg" style="display:none;margin-top:8px;color:green;font-weight:600;">Yes Saved</span>
    </div>

    <?php if ( empty( $services ) ) : ?>
        <div class="notice notice-warning"><p>No active services found. <a href="<?php echo esc_url( admin_url('admin.php?page=yatoon-booking-system&tab=services') ); ?>">Go to Services</a> to add your first service, then come back here to configure the Service Menu.</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;">Category Display Order</h3>
        <p class="description" style="margin-bottom:12px;">Enter a number to set the display order (lower = first).</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;">Save Order</button>
        <span id="ysm-order-msg" style="display:none;margin-left:10px;color:green;font-weight:600;">Yes Saved</span>
    </div>

    <div style="margin-bottom:12px;">
        <strong id="ysm-feat-count"><?php echo esc_html( count( $featured_ids ) ); ?></strong> service(s) featured
        <span style="color:#aaa;font-size:13px;">(max 12 shown in carousel)</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;">Featured</th>
                    <th style="width:70px;">Image</th>
                    <th>Service Name</th>
                    <th style="width:80px;">Price</th>
                    <th style="width:80px;">Duration</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>
