/*
Theme Name: TownHub Child
Theme URI: https://townhub.cththemes.com
Author: CTHthemes
Author URI: http://themeforest.net/user/cththemes/
Description: TownHub – Directory & Listing WordPress Theme is perfect if you like a clean and modern design. This theme will help you create, manage and monetize a local or global directory site.
Version: 1.0.0
Tags: custom-background, custom-menu, editor-style, featured-images, post-formats, sticky-post, theme-options, translation-ready
Template: townhub
Text Domain: townhub-child
License: GNU General Public License version 3.0
License URI: http://www.gnu.org/licenses/gpl-3.0.html
*/
/* =Theme customization starts here
----------------------<?php
/**
 * @package TownHub - Directory & Listing WordPress Theme
 * @author CTHthemes - http://themeforest.net/user/cththemes
 * @date 06-11-2019
 * @since 1.0.0
 * @version 1.0.0
 * @copyright Copyright ( C ) 2014 - 2019 cththemes.com . All rights reserved.
 * @license GNU General Public License version 3 or later; see LICENSE
 */
// Your php<?php
/**
 * FMX TownHub Child Theme Functions
 * 整合 TownHub AZP Elements, Listing 擴展, Schema.org SEO
 */

// 1. 載入父主題樣式
function fmx_enqueue_parent_styles() {
    wp_enqueue_style('fmx-parent-style', get_template_directory_uri() . '/style.css');
}
add_action('wp_enqueue_scripts', 'fmx_enqueue_parent_styles', 20);

// 2. [AZP] 註冊自訂分類法 (Listing Categories)
function fmx_register_townhub_taxonomy() {
    // A. 街頭藝人類別
    if (!taxonomy_exists('fmx_performer_cat')) {
        register_taxonomy('fmx_performer_cat', 'listing', [
            'label' => '街頭藝人分類',
            'hierarchical' => true,
            'show_ui' => true,
            'rewrite' => ['slug' => 'performer'],
        ]);
    }

    // B. 初始化預設項目
    $performer_terms = ['🎸 吉他彈唱', '🎭 表演藝術類', '🎨 視覺藝術類'];
    foreach ($performer_terms as $t) {
        if (!term_exists($t, 'fmx_performer_cat')) wp_insert_term($t, 'fmx_performer_cat');
    }
}
add_action('init', 'fmx_register_townhub_taxonomy');

// 3. [Meta Boxes] TownHub Listing 後台欄位擴展
function fmx_add_listing_meta_boxes() {
    $post_id = get_the_ID();
    // 取得當前 Listings 的分類
    $cat = get_post_meta($post_id, '_listing_category', true);

    // 市集活動專屬欄位
    if ($cat === 'market-event') {
        add_meta_box('fmx_market_box', '🎪 報名系統與配置圖', 'fmx_render_market_fields', 'listing', 'normal');
    }
    
    // 餐車聯繫方式專屬欄位
    if ($cat === 'food-truck') {
        add_meta_box('fmx_contact_box', '📞 社群與通訊連結', 'fmx_render_contact_fields', 'listing', 'normal');
    }

    // 街頭藝人演出時間
    $terms = wp_get_post_terms($post_id, 'fmx_performer_cat');
    if (!empty($terms)) {
        add_meta_box('fmx_perf_box', '🎸 表演者資訊', 'fmx_render_perf_fields', 'listing', 'normal');
    }
}
add_action('add_meta_boxes', 'fmx_add_listing_meta_boxes');

// Meta Box 渲染函數
function fmx_render_market_fields($post) {
    wp_nonce_field('fmx_save_action', 'fmx_nonce');
    echo '<div class="fmx-azp-meta"><h4>⏰ 報名資訊</h4>';
    echo '<label>開始時間:</label><input type="datetime-local" name="fmx_start" value="'. get_post_meta($post->ID, '_fmx_start', true) .'">';
    echo '<h4>🗺️ 攤位配置圖 URL</h4><input type="text" name="fmx_map" value="'. get_post_meta($post->ID, '_fmx_map', true) .'" style="width:100%">';
    echo '</div>';
}

function fmx_render_contact_fields($post) {
    wp_nonce_field('fmx_save_action', 'fmx_nonce');
    $c = get_post_meta($post->ID, '_fmx_contacts', true);
    echo '<div class="fmx-azp-meta"><label>LINE ID:</label><input type="text" name="line_id" value="' . (isset($c['line']) ? $c['line'] : '') . '"><br>';
    echo '<label>FB URL:</label><input type="url" name="fb_url" value="' . (isset($c['fb']) ? $c['fb'] : '') . '"></div>';
}

function fmx_render_perf_fields($post) {
    wp_nonce_field('fmx_save_action', 'fmx_nonce');
    echo '<div class="fmx-azp-meta"><label>演出時間表:</label><input type="text" name="fmx_sched" value="' . get_post_meta($post->ID, '_fmx_sched', true) . '"></div>';
}

// 儲存 Meta Data
function fmx_save_listing_data($post_id) {
    if (defined('DOING_AUTOSAVE') || !isset($_POST['fmx_nonce']) || !wp_verify_nonce($_POST['fmx_nonce'], 'fmx_save_action')) return;

    // 市集資料
    $cat = get_post_meta($post_id, '_listing_category', true);
    if ($cat === 'market-event') {
        update_post_meta($post_id, '_fmx_start', sanitize_text_field($_POST['fmx_start']));
        update_post_meta($post_id, '_fmx_map', esc_url_raw($_POST['fmx_map']));
    }
    // 藝術家資料
    if (!empty(wp_get_post_terms($post_id, 'fmx_performer_cat'))) {
        update_post_meta($post_id, '_fmx_sched', sanitize_text_field($_POST['fmx_sched']));
    }
    // 聯繫方式資料
    if (isset($_POST['line_id'])) {
        $c = get_post_meta($post_id, '_fmx_contacts', true); if (!is_array($c)) $c = [];
        $c['line'] = sanitize_text_field($_POST['line_id']); $c['fb'] = esc_url_raw($_POST['fb_url']);
        update_post_meta($post_id, '_fmx_contacts', $c);
    }
}
add_action('save_post_listing', 'fmx_save_listing_data');

// 4. [Schema.org] 自訂 SEO 結構化數據 (根據 docs.cththemes.org)
function fmx_add_custom_schema_values($schema, $listing) {
    $cat = get_post_meta($listing->ID, '_listing_category', true);
    
    if ($cat === 'food-truck') {
        $schema['@type'] = 'FoodTruck';
        // 假設您將地址放在內容或自訂欄位中
        $schema['priceRange'] = '$$';
    }

    if ($cat === 'market-event') {
        $start = get_post_meta($listing->ID, '_fmx_start', true);
        if ($start) {
            $schema['@type'] = 'Event';
            $schema['startDate'] = date('c', strtotime($start));
            $schema['endDate'] = date('c', strtotime($start . ' +6 hours')); // 預設活動長6小時
            $schema['eventAttendanceMode'] = 'https://schema.org/OfflineEventAttendanceMode';
        }
    }

    return $schema;
}
// 嘗試掛鉤到 TownHub 的 Schema 過濾器 (若 TownHub 使用不同 Hook，請調整)
add_filter('townhub_schema_values', 'fmx_add_custom_schema_values', 10, 2);

// 5. [Frontend] 覆蓋模板邏輯與分享按鈕
function fmx_add_social_share($content) {
    global $post;
    if (!$post || $post->post_type !== 'listing') return $content;
    
    $share = '<div class="fmx-share-bar"><h4>分享：</h4>';
    $share .= '<a href="https://www.facebook.com/sharer/sharer.php?u='.urlencode($post->permalink).'" target="_blank">FB</a>';
    $share .= '<a href="https://social-plugins.line.me/lineit/share?url='.$post->permalink.'" target="_blank">LINE</a></div>';
    
    return $content . $share;
}
add_filter('townhub_listing_item_content', 'fmx_add_social_share', 10);

// 6. [Admin] 儀表板整合
function fmx_admin_panel() {
    add_menu_page('FMX', '🚚 台灣餐車市集', 'manage_options', 'fmx-panel', 'fmx_render_dashboard', 'dashicons-cart');
}
add_action('admin_menu', 'fmx_admin_panel');

function fmx_render_dashboard() {
    echo '<div class="wrap"><h1>FMX 管理後台</h1>';
    echo '<p>歡迎使用 TownHub Child Theme 擴展版。</p>';
    echo '<a href="' . admin_url('edit.php?post_type=listing&tax_input[listing_category][]=food-truck') . '" class="button">餐車列表</a>';
    echo '<a href="' . admin_url('edit.php?post_type=listing&tax_input[fmx_performer_cat][]=吉他彈唱') . '" class="button">藝人列表</a>';
    echo '</div>';
} code goes here