add_action('wp_head', function () {

    if (!is_page('bali-eco-deli-menu-nusa-lembongan')) return;

    $cache_key = 'bali_eco_deli_menu_schema_v2'; // Updated key to force refresh
    $cache_ttl = 12 * HOUR_IN_SECONDS;

    $cache_enabled = get_option('menu_schema_cache_enabled', '1') === '1';

    if ($cache_enabled) {
        $cached = get_transient($cache_key);
        if ($cached) {
            echo $cached;
            return;
        }
    }

    $sheet_id = '1PeRiJk05I2MTqy5QPUE1jocGlqysM7M-WOBzz6LmE3U';

    // ---- STEP 1: Read category list from __categories tab ----
    $index_url = 'https://docs.google.com/spreadsheets/d/' . $sheet_id .
                 '/gviz/tq?tqx=out:json&sheet=' . urlencode('__categories');

    $index_response = wp_remote_get($index_url, ['timeout' => 8]);
    if (is_wp_error($index_response)) return;

    $index_body = wp_remote_retrieve_body($index_response);
    $index_json = trim(substr($index_body, strpos($index_body, '{'), strrpos($index_body, '}') - strpos($index_body, '{') + 1));
    $index_data = json_decode($index_json, true);

    if (!$index_data || empty($index_data['table']['rows'])) return;

    $sections = [];

    foreach ($index_data['table']['rows'] as $row) {

        if (empty($row['c'][0]['v'])) continue;
        $tab = trim($row['c'][0]['v']);
        if (!$tab) continue;

        // ---- STEP 2: Fetch A1 for section description ----
        $desc_url = 'https://docs.google.com/spreadsheets/d/' . $sheet_id .
                    '/gviz/tq?tqx=out:json&sheet=' . urlencode($tab) .
                    '&range=A1';

        $section_desc = '';
        $desc_response = wp_remote_get($desc_url, ['timeout' => 8]);

        if (!is_wp_error($desc_response)) {
            $desc_body = wp_remote_retrieve_body($desc_response);
            $desc_json = trim(substr($desc_body, strpos($desc_body, '{'), strrpos($desc_body, '}') - strpos($desc_body, '{') + 1));
            $desc_data = json_decode($desc_json, true);

            if (!empty($desc_data['table']['rows'][0]['c'][0]['v'])) {
                $section_desc = trim($desc_data['table']['rows'][0]['c'][0]['v']);
            }
        }

        // ---- STEP 3: Fetch full sheet for menu items ----
        $url = 'https://docs.google.com/spreadsheets/d/' . $sheet_id .
               '/gviz/tq?tqx=out:json&sheet=' . urlencode($tab);

        $response = wp_remote_get($url, ['timeout' => 8]);
        if (is_wp_error($response)) continue;

        $body = wp_remote_retrieve_body($response);
        $json = trim(substr($body, strpos($body, '{'), strrpos($body, '}') - strpos($body, '{') + 1));
        $data = json_decode($json, true);

        if (!$data || empty($data['table']['rows'])) continue;

        $items = [];

        foreach ($data['table']['rows'] as $item_row) {

            // Column A = Name
            if (empty($item_row['c'][0]['v'])) continue;
            $name = trim($item_row['c'][0]['v']);
            if (!$name) continue;
            
            // Skip section header rows
            if (strcasecmp($name, $tab) === 0) continue;
            
            $has_description = !empty($item_row['c'][1]['v']);
            $has_price = !empty($item_row['c'][2]['v']);

            // Skip rows that are just section headers (no dish data)
            if (!$has_description && !$has_price) {
                continue;
            }

            // Initialize the item structure
            $item = [
                "@type" => "MenuItem",
                "name" => $name
            ];

            // --- DIETARY LOGIC (Vegan 🌱) ---
            if (strpos($name, '🌱') !== false) {
                $item['suitableForDiet'] = "https://schema.org/VeganDiet";
            }

            // --- DESCRIPTION LOGIC (Column B) ---
            if (!empty($item_row['c'][1]['v'])) {
                $item['description'] = trim($item_row['c'][1]['v']);
            }

            // --- PRICE LOGIC (Column C) ---
            if (!empty($item_row['c'][2]['v'])) {
                $price = preg_replace('/[^0-9.]/', '', $item_row['c'][2]['v']);
                if ($price) {
                    $item['offers'] = [
                        "@type" => "Offer",
                        "priceCurrency" => "IDR",
                        "price" => $price
                    ];
                }
            }

            // --- POPULARITY LOGIC (Column D) ---
            $is_popular = !empty($item_row['c'][3]['v']) &&
                          strtoupper(trim($item_row['c'][3]['v'])) === 'YES';

            if ($is_popular) {
                $item['additionalProperty'] = [
                    "@type" => "PropertyValue",
                    "name" => "Popularity",
                    "value" => "Best Seller"
                ];
                $item['keywords'] = "popular, best seller, signature dish, healthy food Lembongan";
            }

            $items[] = $item;
        }

        if (!empty($items)) {
            $section = [
                "@type" => "MenuSection",
                "name" => $tab,
                "hasMenuItem" => $items
            ];

            if ($section_desc) {
                $section['description'] = $section_desc;
            }

            $sections[] = $section;
        }
    }

    if (empty($sections)) return;

// --- FINAL SCHEMA ASSEMBLY ---
    $schema = [
        "@context" => "https://schema.org",
        "@type" => "Menu",
        "@id" => "https://baliecodeli.net/bali-eco-deli-menu-nusa-lembongan/#menu",
        "name" => "Bali ECO Deli Menu",
        "url" => get_permalink(),
        "provider" => [
            "@id" => "https://baliecodeli.net/#restaurant"
        ],  
        "inLanguage" => "en",
        "audience" => [
            "@type" => "Audience",
            "audienceType" => "Tourists and travelers in Nusa Lembongan"
        ],
        "hasMenuSection" => $sections
    ];

    // Encode and wrap in a single set of tags
    $output = '<script type="application/ld+json">' . 
              wp_json_encode($schema, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . 
              '</script>';

    if ($cache_enabled) {
        set_transient($cache_key, $output, $cache_ttl);
    }

    echo $output;
});