<?php

if ( ! defined( 'ABSPATH' ) ) exit;
/**
 * afdp_ Food Menu - Professional Ultimate Masterpiece (v4.2)
 * Features: WP Timezone Sync, Glassmorphism Popup, Sidebar Status Lock, Search, Extras.
 */

add_shortcode('afdp_food_items', 'afdp_food_items_ultimate_expanded');

function afdp_food_items_ultimate_expanded() {
    // --- 1. STATUS & TIMEZONE LOGIC ---
    $status       = get_afdp_restaurant_status(); 
    $is_closed    = !$status['is_open'];
    $display_time = isset($status['site_time']) ? $status['site_time'] : current_time('H:i');

    // --- 2. CONFIGURATION & GATEWAY LINKS ---
    $delivery_fee      = 5.00; 
    $checkout_page_url = site_url('/afdp-checkout/'); 
    $login_page_url    = site_url('/afdp-login/');    
    
    $currency_code = get_option('afdp_currency', 'USD');
    $currency_symbols = ['USD'=>'$','EUR'=>'€','GBP'=>'£','INR'=>'₹','BDT'=>'৳','AED'=>'د.إ','CAD'=>'C$','SAR'=>'SR'];
    $currency = isset($currency_symbols[$currency_code]) ? $currency_symbols[$currency_code] : '$';
    
    // --- 3. DATABASE FETCHING ---
    $extras_all = get_option('fd_extras', []);
    $items = get_posts([
        'post_type'      => 'afdp_food_item',
        'posts_per_page' => -1,
        'post_status'    => 'publish',
        'orderby'        => 'menu_order',
        'order'          => 'ASC'
    ]);

    if (!$items) return '<div style="padding:100px; text-align:center;"><h3>Menu is currently empty.</h3></div>';

    // Organize Categories
    $categories = [];
    $all_terms = get_terms(['taxonomy' => 'afdp_food_category', 'hide_empty' => false]);
    foreach ($all_terms as $term) {
        $img_id = get_term_meta($term->term_id, 'afdp_category_image', true);
        $image_url = $img_id ? wp_get_attachment_image_url($img_id, 'thumbnail') : 'https://ui-avatars.com/api/?name='.urlencode($term->name).'&background=f1f5f9';
        $categories[$term->slug] = ['name' => $term->name, 'slug' => $term->slug, 'img' => $image_url, 'items' => []];
    }
    foreach ($items as $item) {
        $terms = wp_get_post_terms($item->ID, 'afdp_food_category');
        $cat_slug = !empty($terms) ? $terms[0]->slug : 'other';
        if(isset($categories[$cat_slug])) $categories[$cat_slug]['items'][] = $item;
    }

    wp_enqueue_style('dashicons');
    ob_start(); ?>

    <style>
        :root {
            --primary: #FF385C;
            --primary-hover: #E31C5F;
            --dark: #0F172A;
            --slate: #64748B;
            --light: #F1F5F9;
            --white: #FFFFFF;
            --bg-body: #F8FAFC;
            --radius-lg: 24px;
            --radius-md: 16px;
            --shadow-subtle: 0 4px 6px -1px rgba(0,0,0,0.05);
            --shadow-heavy: 0 20px 25px -5px rgba(0,0,0,0.1);
        }

        .afdp-app-root { 
            font-family: 'Plus Jakarta Sans', sans-serif; 
            background: var(--bg-body); 
            display: flex; 
            min-height: 100vh; 
            margin: -20px; 
            color: var(--dark); 
            overflow: hidden; 
        }

        /* --- LEFT CONTENT: MENU --- */
        .afdp-menu-column { flex: 1; padding: 40px; height: 100vh; overflow-y: auto; scroll-behavior: smooth; }
        .afdp-inner-container { max-width: 900px; margin: 0 auto; }

        .afdp-search-wrapper { position: relative; margin-bottom: 40px; transform: translateZ(0); }
        .afdp-search-wrapper input { 
            width: 100%; padding: 22px 30px 22px 65px; border-radius: var(--radius-lg); border: 2px solid transparent;
            background: var(--white); box-shadow: var(--shadow-heavy); font-size: 16px; outline: none; 
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .afdp-search-wrapper input:focus { border-color: var(--primary); transform: translateY(-2px); }
        .afdp-search-wrapper .dashicons { 
            position: absolute; left: 25px; top: 50%; transform: translateY(-50%); 
            color: var(--primary); font-size: 28px; width: 28px; height: 28px;
        }

        .afdp-cat-strip { display: flex; gap: 15px; overflow-x: auto; padding-bottom: 25px; scrollbar-width: none; }
        .afdp-cat-strip::-webkit-scrollbar { display: none; }
        .afdp-cat-pill { 
            flex: 0 0 auto; background: var(--white); padding: 12px 24px; border-radius: 50px; 
            display: flex; align-items: center; gap: 12px; text-decoration: none; color: var(--slate); 
            font-weight: 700; font-size: 14px; box-shadow: var(--shadow-subtle); transition: 0.3s;
            border: 1px solid transparent;
        }
        .afdp-cat-pill img { width: 28px; height: 28px; border-radius: 50%; object-fit: cover; }
        .afdp-cat-pill:hover { border-color: var(--primary); color: var(--primary); }
        .afdp-cat-pill.active { background: var(--primary); color: var(--white); box-shadow: 0 10px 15px rgba(255, 56, 92, 0.2); }

        .afdp-food-card { 
            background: var(--white); border-radius: 30px; display: flex; margin-bottom: 30px; 
            box-shadow: var(--shadow-subtle); overflow: hidden; transition: 0.5s; position: relative;
            border: 1px solid rgba(0,0,0,0.03);
        }
        .afdp-food-card:hover { transform: translateY(-10px) scale(1.01); box-shadow: var(--shadow-heavy); }
        .afdp-card-img { width: 280px; background-size: cover; background-position: center; position: relative; }
        .afdp-card-content { padding: 35px; flex: 1; display: flex; flex-direction: column; }
        
        .afdp-card-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 15px; }
        .afdp-card-header h3 { margin: 0; font-size: 24px; font-weight: 800; letter-spacing: -0.5px; }
        .afdp-price-tag { 
            background: #FFF1F2; color: var(--primary); padding: 8px 16px; border-radius: 14px; 
            font-weight: 800; font-size: 18px; border: 1px solid rgba(255, 56, 92, 0.1); 
        }

        .afdp-extras-panel { background: #F8FAFC; padding: 20px; border-radius: var(--radius-md); margin: 20px 0; border: 1px solid #E2E8F0; }
        .afdp-extra-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px dashed #E2E8F0; }
        .afdp-extra-item:last-child { border-bottom: none; }
        .afdp-extra-info { font-size: 14px; font-weight: 600; color: var(--slate); }
        .afdp-extra-info span { color: var(--primary); margin-left: 5px; }

        .afdp-switch { position: relative; width: 44px; height: 24px; cursor: pointer; }
        .afdp-switch input { opacity: 0; width: 0; height: 0; }
        .afdp-slider { position: absolute; inset: 0; background: #CBD5E1; transition: .4s; border-radius: 24px; }
        .afdp-slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px; background: white; transition: .4s; border-radius: 50%; }
        input:checked + .afdp-slider { background: var(--primary); }
        input:checked + .afdp-slider:before { transform: translateX(20px); }

        .afdp-btn-add { 
            width: 100%; padding: 18px; background: var(--dark); color: white; border: none; 
            border-radius: var(--radius-md); font-weight: 800; font-size: 16px; cursor: pointer; 
            transition: 0.3s; margin-top: auto; 
        }
        .afdp-btn-add:hover { background: #000; transform: scale(0.98); }

        /* --- RIGHT CONTENT: SIDEBAR BASKET --- */
        .afdp-sidebar { 
            width: 440px; height: 100vh; position: sticky; top: 0; background: var(--white); 
            border-left: 1px solid #E2E8F0; display: flex; flex-direction: column; z-index: 100;
        }
        .afdp-sidebar-header { padding: 40px 40px 10px; }
        
        .afdp-type-toggle { 
            display: flex; background: #F1F5F9; padding: 6px; border-radius: 20px; margin-bottom: 20px; 
            position: relative;
        }
        .afdp-type-btn { 
            flex: 1; padding: 14px; border: none; background: transparent; border-radius: 16px; 
            font-weight: 800; font-size: 14px; cursor: pointer; transition: 0.3s; color: var(--slate);
        }
        .afdp-type-btn.active { background: var(--white); color: var(--primary); box-shadow: var(--shadow-subtle); }

        #afdp-cart-list { flex: 1; overflow-y: auto; padding: 0 40px; }
        .afdp-cart-item { padding: 25px 0; border-bottom: 1px solid #F1F5F9; animation: afdpSlideIn 0.4s ease forwards; }
        .afdp-cart-item-top { display: flex; justify-content: space-between; font-weight: 800; font-size: 17px; margin-bottom: 8px; }
        .afdp-cart-item-extras { list-style: none; padding: 0; margin: 10px 0; border-left: 3px solid var(--primary); padding-left: 15px; font-size: 13px; color: var(--slate); }

        .afdp-qty-wrap { display: flex; align-items: center; gap: 15px; margin-top: 15px; }
        .afdp-qty-circle { 
            width: 32px; height: 32px; border-radius: 50%; border: 1.5px solid #E2E8F0; 
            background: #fff; cursor: pointer; display: flex; align-items: center; justify-content: center;
            font-weight: 800; transition: 0.2s;
        }
        .afdp-qty-circle:hover { background: var(--primary); color: #fff; border-color: var(--primary); }

        .afdp-sidebar-footer { padding: 30px 40px 40px; border-top: 1px solid #F1F5F9; background: rgba(255,255,255,0.9); backdrop-filter: blur(10px); }
        .afdp-summary-line { display: flex; justify-content: space-between; color: var(--slate); font-weight: 600; font-size: 15px; margin-bottom: 12px; }
        .afdp-total-line { display: flex; justify-content: space-between; font-size: 30px; font-weight: 900; margin-top: 15px; margin-bottom: 25px; letter-spacing: -1px; }

        .afdp-btn-checkout { 
            width: 100%; padding: 22px; background: var(--primary); color: white; border: none; 
            border-radius: var(--radius-lg); font-weight: 800; font-size: 18px; cursor: pointer; 
            box-shadow: 0 15px 30px rgba(255, 56, 92, 0.25); transition: 0.3s;
        }
        .afdp-btn-checkout:hover { transform: translateY(-3px); box-shadow: 0 20px 40px rgba(255, 56, 92, 0.35); }
        .afdp-btn-checkout:disabled { opacity: 0.3; cursor: not-allowed; transform: none; box-shadow: none; }
        
        .afdp-sidebar-closed-msg { background: #FFF1F2; color: #E11D48; padding: 12px; border-radius: 12px; font-size: 13px; font-weight: 700; margin-bottom: 15px; text-align: center; border: 1px solid #FECACA; }

        @keyframes afdpSlideIn { from { opacity: 0; transform: translateX(20px); } to { opacity: 1; transform: translateX(0); } }

        @media (max-width: 1150px) {
            .afdp-app-root { flex-direction: column; }
            .afdp-sidebar { width: 100%; height: auto; position: static; }
            .afdp-food-card { flex-direction: column; }
            .afdp-card-img { width: 100%; height: 250px; }
        }
    </style>

    <div class="afdp-app-root">
        <div class="afdp-menu-column">
            <div class="afdp-inner-container">
                
                <div class="afdp-search-wrapper">
                    <span class="dashicons dashicons-search"></span>
                    <input type="text" id="afdp-live-search" placeholder="Search for your favorite dish...">
                </div>

                <div class="afdp-cat-strip">
                    <?php foreach ($categories as $cat) : if (!empty($cat['items'])) : ?>
                        <a href="#cat-<?php echo esc_attr($cat['slug']); ?>" class="afdp-cat-pill">
                            <img src="<?php echo esc_url($cat['img']); ?>">
                            <span><?php echo esc_html($cat['name']); ?></span>
                        </a>
                    <?php endif; endforeach; ?>
                </div>

                <div id="afdp-main-menu">
                    <?php foreach ($categories as $cat) : if (!empty($cat['items'])) : ?>
                        <div class="afdp-section" id="cat-<?php echo esc_attr($cat['slug']); ?>">
                            <h2 style="font-size: 32px; font-weight: 800; margin: 50px 0 25px; letter-spacing: -1px;"><?php echo esc_html($cat['name']); ?></h2>
                            
                            <?php foreach ($cat['items'] as $item) : 
                                $price = get_post_meta($item->ID, 'afdp_food_price', true) ?: '0.00';
                                $img = get_the_post_thumbnail_url($item->ID, 'large') ?: 'https://via.placeholder.com/600x400';
                                $ex_ids = get_post_meta($item->ID, 'afdp_item_extras', true) ?: [];
                            ?>
                            <div class="afdp-food-card" data-id="<?php echo esc_attr($item->ID); ?>" data-title="<?php echo esc_attr(strtolower($item->post_title)); ?>">
                                <div class="afdp-card-img" style="background-image: url('<?php echo esc_url($img); ?>');"></div>
                                <div class="afdp-card-content">
                                    <div class="afdp-card-header">
                                        <h3><?php echo esc_html($item->post_title); ?></h3>
                                        <div class="afdp-price-tag"><?php echo esc_html($currency . $price); ?></div>
                                    </div>
                                    <p style="color:var(--slate); line-height:1.6; font-size:15px; margin-bottom:10px;">
                                        <?php echo esc_attr(wp_trim_words($item->post_content, 22)); ?>
                                    </p>

                                    <?php if(!empty($ex_ids)): ?>
                                    <div class="afdp-extras-panel">
                                        <?php foreach ($ex_ids as $id) : if (isset($extras_all[$id])) : $ex = $extras_all[$id]; ?>
                                            <div class="afdp-extra-item">
                                                <div class="afdp-extra-info"><?php echo esc_html($ex['name']); ?> <span>(+<?php echo esc_attr($currency . $ex['price']); ?>)</span></div>
                                                <label class="afdp-switch">
                                                    <input type="checkbox" class="afdp-reactive-ex" data-name="<?php echo esc_attr($ex['name']); ?>" data-price="<?php echo esc_attr($ex['price']); ?>">
                                                    <span class="afdp-slider"></span>
                                                </label>
                                            </div>
                                        <?php endif; endforeach; ?>
                                    </div>
                                    <?php endif; ?>

                                    <button class="afdp-btn-add" data-id="<?php echo esc_attr($item->ID); ?>" data-title="<?php echo esc_attr($item->post_title); ?>" data-price="<?php echo esc_attr($price); ?>">Add to Basket</button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; endforeach; ?>
                </div>
            </div>
        </div>

        <div class="afdp-sidebar">
            <div class="afdp-sidebar-header">
                <div class="afdp-type-toggle">
                    <button class="afdp-type-btn active" data-val="Delivery">Delivery</button>
                    <button class="afdp-type-btn" data-val="Pickup">Pickup</button>
                </div>
            </div>

            <div id="afdp-cart-list"></div>

            <div class="afdp-sidebar-footer">
                <?php if ($is_closed) : ?>
                    <div class="afdp-sidebar-closed-msg">
                        <?php echo esc_html($status['message']); ?>
                    </div>
                <?php endif; ?>

                <div class="afdp-summary-line">
                    <span>Subtotal</span>
                    <span id="afdp-subtotal"><?php echo esc_html($currency); ?>0.00</span>
                </div>
                <div class="afdp-summary-line" id="afdp-del-fee-line">
                    <span>Delivery Fee</span>
                    <span><?php echo esc_attr($currency . number_format($delivery_fee, 2)); ?></span>
                </div>
                
                <div class="afdp-total-line">
                    <span>Total</span>
                    <span id="afdp-grand-total"><?php echo esc_html($currency); ?>0.00</span>
                </div>

                <button class="afdp-btn-checkout <?php echo $is_closed ? 'closed-lock' : ''; ?>" id="afdp-main-action" disabled>
                    <?php echo $is_closed ? 'Store is Closed' : 'Complete Order'; ?>
                </button>
            </div>
        </div>
    </div>

    <script>
    jQuery(document).ready(function($){
        // --- GLOBAL STATE ---
        let cart = [];
        let orderMethod = 'Delivery';
        const sym = <?php echo json_encode( esc_js( $currency ) ); ?>;
        const dFee = <?php echo (float) $delivery_fee; ?>;
        const loggedIn = <?php echo is_user_logged_in() ? 'true' : 'false'; ?>;
        const checkoutUrl = '<?php echo esc_url($checkout_page_url); ?>';
        const loginUrl = '<?php echo esc_url($login_page_url); ?>';
        const isClosed = <?php echo $is_closed ? 'true' : 'false'; ?>;

        updateOrder();

        // --- CORE FUNCTIONS ---
        function updateOrder() {
            const list = $('#afdp-cart-list');
            list.empty();
            let subtotal = 0;

            if(cart.length === 0) {
                list.html('<div style="text-align:center; padding-top:100px; color:#cbd5e1;"><span class="dashicons dashicons-cart" style="font-size:60px; width:60px; height:60px; margin-bottom:15px;"></span><p style="font-weight:700;">Your basket is empty</p></div>');
                $('#afdp-main-action').prop('disabled', true);
            } else {
                // Only enable button if store is OPEN
                if (!isClosed) {
                    $('#afdp-main-action').prop('disabled', false);
                }
                
                cart.forEach((it, idx) => {
                    let lineTotal = it.unitPrice * it.qty;
                    subtotal += lineTotal;
                    let exText = it.extras.map(e => `<li>${e.name} (+${sym}${e.price.toFixed(2)})</li>`).join('');
                    
                    list.append(`
                        <div class="afdp-cart-item">
                            <div class="afdp-cart-item-top">
                                <span>${it.title}</span>
                                <span>${sym}${lineTotal.toFixed(2)}</span>
                            </div>
                            <ul class="afdp-cart-item-extras">${exText}</ul>
                            <div class="afdp-qty-wrap">
                                <button class="afdp-qty-circle q-rem" data-idx="${idx}">-</button>
                                <strong style="font-size:16px;">${it.qty}</strong>
                                <button class="afdp-qty-circle q-add" data-idx="${idx}">+</button>
                                <span class="dashicons dashicons-trash q-del" style="margin-left:auto; cursor:pointer; color:#cbd5e1;" data-idx="${idx}"></span>
                            </div>
                        </div>
                    `);
                });
            }

            let currentDelFee = (orderMethod === 'Delivery' && cart.length > 0) ? dFee : 0;
            let grandTotal = subtotal + currentDelFee;

            if(orderMethod === 'Delivery' && cart.length > 0) $('#afdp-del-fee-line').show(); 
            else $('#afdp-del-fee-line').hide();

            $('#afdp-subtotal').text(sym + subtotal.toFixed(2));
            $('#afdp-grand-total').text(sym + grandTotal.toFixed(2));
        }

        // --- EVENT HANDLERS ---
        $('.afdp-btn-add').on('click', function(){
            const btn = $(this), id = btn.data('id'), base = parseFloat(btn.data('price')), title = btn.data('title'), card = btn.closest('.afdp-food-card');
            let item = cart.find(i => i.id === id);
            if(item) {
                item.qty++;
            } else {
                let selectedExtras = [];
                card.find('.afdp-reactive-ex:checked').each(function(){
                    selectedExtras.push({ name: $(this).data('name'), price: parseFloat($(this).data('price')) });
                });
                let unitPrice = base + selectedExtras.reduce((a, b) => a + b.price, 0);
                cart.push({ id, title, base, extras: selectedExtras, qty: 1, unitPrice });
            }
            updateOrder();
        });

        $(document).on('change', '.afdp-reactive-ex', function(){
            const card = $(this).closest('.afdp-food-card'), id = card.data('id'), item = cart.find(i => i.id === id);
            if(item) {
                let updatedEx = [];
                card.find('.afdp-reactive-ex:checked').each(function(){
                    updatedEx.push({ name: $(this).data('name'), price: parseFloat($(this).data('price')) });
                });
                item.extras = updatedEx;
                item.unitPrice = item.base + updatedEx.reduce((a, b) => a + b.price, 0);
                updateOrder();
            }
        });

        $(document).on('click', '.q-add', function(){ cart[$(this).data('idx')].qty++; updateOrder(); });
        $(document).on('click', '.q-rem', function(){
            let i = $(this).data('idx');
            if(cart[i].qty > 1) cart[i].qty--; else cart.splice(i, 1);
            updateOrder();
        });
        $(document).on('click', '.q-del', function(){ cart.splice($(this).data('idx'), 1); updateOrder(); });

        $('.afdp-type-btn').on('click', function(){
            $('.afdp-type-btn').removeClass('active');
            $(this).addClass('active');
            orderMethod = $(this).data('val');
            updateOrder();
        });

        $('#afdp-live-search').on('input', function() {
            let q = $(this).val().toLowerCase();
            $('.afdp-food-card').each(function() { 
                let match = $(this).data('title').includes(q);
                $(this).toggle(match);
            });
            $('.afdp-section').each(function(){
                $(this).toggle($(this).find('.afdp-food-card:visible').length > 0);
            });
        });

        $('.afdp-cat-pill').on('click', function(e){
            e.preventDefault();
            $('.afdp-cat-pill').removeClass('active'); $(this).addClass('active');
            let target = $($(this).attr('href'));
            $('.afdp-menu-column').animate({
                scrollTop: target.offset().top - $('.afdp-menu-column').offset().top + $('.afdp-menu-column').scrollTop() - 20
            }, 800);
        });

        $('#afdp-main-action').on('click', function(){
            if(!loggedIn) {
                window.location.href = loginUrl;
            } else {
                localStorage.setItem('afdp_final_cart', JSON.stringify(cart));
                localStorage.setItem('afdp_final_method', orderMethod);
                window.location.href = checkoutUrl;
            }
        });
    });
    </script>
    <?php return ob_get_clean();
}