<?php
/**
 * Automated translation and menu mapping for Polylang.
 */

// Load WordPress
require_once dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/wp-load.php';

if ( ! function_exists( 'pll_languages_list' ) ) {
    die( "Error: Polylang is not active.\n" );
}

echo "Starting automated Polylang English page creation and menu linking...\n";

// 1. Page mapping dictionary for Titles and Slugs
$page_maps = array(
    'canh-giac-duoc' => array(
        'title' => 'Pharmacovigilance',
        'slug'  => 'pharmacovigilance',
    ),
    'cua-hang' => array(
        'title' => 'Shop',
        'slug'  => 'shop',
    ),
    'doi-tac' => array(
        'title' => 'Partners',
        'slug'  => 'partners',
    ),
    'gio-hang' => array(
        'title' => 'Cart',
        'slug'  => 'cart',
    ),
    'gioi-thieu' => array(
        'title' => 'About Us',
        'slug'  => 'about-us',
    ),
    'he-thong-phan-phoi' => array(
        'title' => 'Distribution Network',
        'slug'  => 'distribution-network',
    ),
    'he-thong-to-chuc' => array(
        'title' => 'Organizational Structure',
        'slug'  => 'organizational-structure',
    ),
    'hinh-thanh-va-phat-trien' => array(
        'title' => 'History & Development',
        'slug'  => 'history-development',
    ),
    'tam-nhin-su-menh' => array(
        'title' => 'Vision & Mission',
        'slug'  => 'vision-mission',
    ),
    've-an-phat' => array(
        'title' => 'About An Phat',
        'slug'  => 'about-an-phat',
    ),
    'lien-he' => array(
        'title' => 'Contact Us',
        'slug'  => 'contact-us',
    ),
    'san-pham' => array(
        'title' => 'Products',
        'slug'  => 'products',
    ),
    'tai-khoan' => array(
        'title' => 'My Account',
        'slug'  => 'my-account',
    ),
    'thanh-toan' => array(
        'title' => 'Checkout',
        'slug'  => 'checkout',
    ),
    'tin-tuc' => array(
        'title' => 'News',
        'slug'  => 'news',
    ),
    'trang-chu' => array(
        'title' => 'Home',
        'slug'  => 'home',
    ),
    'tuyen-dung' => array(
        'title' => 'Careers',
        'slug'  => 'careers',
    ),
);

// Get all pages in the system
$all_pages = get_pages( array( 'sort_column' => 'ID' ) );

echo "Processing pages...\n";

// Function to translate or update a page
function process_page_translation( $vi_page, $en_parent_id = 0 ) {
    global $page_maps;
    
    $vi_id = $vi_page->ID;
    $vi_slug = $vi_page->post_name;
    
    // Check if translation already exists
    $en_id = pll_get_post( $vi_id, 'en' );
    
    // Get English mapping or fallback
    $en_title = isset( $page_maps[ $vi_slug ] ) ? $page_maps[ $vi_slug ]['title'] : $vi_page->post_title . ' (EN)';
    $en_slug  = isset( $page_maps[ $vi_slug ] ) ? $page_maps[ $vi_slug ]['slug'] : $vi_slug . '-en';
    
    $template = get_post_meta( $vi_id, '_wp_page_template', true );
    
    $post_data = array(
        'post_title'    => $en_title,
        'post_name'     => $en_slug,
        'post_content'  => $vi_page->post_content,
        'post_status'   => 'publish',
        'post_type'     => 'page',
        'menu_order'    => $vi_page->menu_order,
        'post_parent'   => $en_parent_id,
    );
    
    if ( ! $en_id ) {
        // Create new English page
        $en_id = wp_insert_post( $post_data );
        if ( is_wp_error( $en_id ) ) {
            echo "  Error creating page: {$en_title}\n";
            return 0;
        }
        // Set language of the new page to 'en'
        pll_set_post_language( $en_id, 'en' );
        // Map translations link
        pll_save_post_translations( array( 'vi' => $vi_id, 'en' => $en_id ) );
        echo "  Created EN page: {$en_title} (ID: {$en_id}) linked to VI page (ID: {$vi_id})\n";
    } else {
        // Update existing English page
        $post_data['ID'] = $en_id;
        wp_update_post( $post_data );
        echo "  Updated existing EN page: {$en_title} (ID: {$en_id})\n";
    }
    
    // Set page template
    if ( $template ) {
        update_post_meta( $en_id, '_wp_page_template', $template );
    }
    
    return $en_id;
}

// Pass 1: Translate top-level pages (post_parent == 0)
echo "Pass 1: Top-level pages...\n";
foreach ( $all_pages as $page ) {
    if ( $page->post_parent == 0 ) {
        // Force the Vietnamese page's language to be 'vi' in Polylang if not set
        if ( ! pll_get_post_language( $page->ID ) ) {
            pll_set_post_language( $page->ID, 'vi' );
        }
        process_page_translation( $page, 0 );
    }
}

// Pass 2: Translate child pages (post_parent != 0)
echo "Pass 2: Child pages...\n";
foreach ( $all_pages as $page ) {
    if ( $page->post_parent != 0 ) {
        // Force the Vietnamese page's language to be 'vi' in Polylang if not set
        if ( ! pll_get_post_language( $page->ID ) ) {
            pll_set_post_language( $page->ID, 'vi' );
        }
        
        $vi_parent_id = $page->post_parent;
        $en_parent_id = pll_get_post( $vi_parent_id, 'en' );
        
        process_page_translation( $page, $en_parent_id );
    }
}

echo "Page translations completed.\n\n";

// 3. Rebuild English Navigation Menu
echo "Processing navigation menu...\n";

$en_menu_id = 30; // 'Primary Menu' (English menu)
$vi_menu_id = 2;  // 'An Phat Primary Menu' (Vietnamese menu)

// Clear existing items in English menu to avoid duplicates
echo "Clearing existing menu items in English menu (ID: {$en_menu_id})...\n";
$existing_en_items = wp_get_nav_menu_items( $en_menu_id );
if ( $existing_en_items ) {
    foreach ( $existing_en_items as $item ) {
        wp_delete_post( $item->ID, true );
    }
}

// Map of Vietnamese Menu Item Title to English Menu Item Title
$menu_title_maps = array(
    'trang chủ' => 'Home',
    'giới thiệu' => 'About Us',
    'về an phát' => 'About An Phat',
    'hệ thống phân phối' => 'Distribution Network',
    'hệ thống tổ chức' => 'Organizational Structure',
    'tầm nhìn & sứ mệnh' => 'Vision & Mission',
    'tầm nhìn &amp; sứ mệnh' => 'Vision & Mission',
    'hình thành và phát triển' => 'History & Development',
    'sản phẩm' => 'Products',
    'đối tác' => 'Partners',
    'tin tức' => 'News',
    'tuyển dụng' => 'Careers',
    'cảnh giác dược' => 'Pharmacovigilance',
    'liên hệ' => 'Contact',
);

// Get Vietnamese menu items
$vi_menu_items = wp_get_nav_menu_items( $vi_menu_id );

if ( ! $vi_menu_items ) {
    die( "Error: No items found in Vietnamese menu (ID: {$vi_menu_id}).\n" );
}

$menu_item_mapping = array(); // Mapping from vi_menu_item_id => en_menu_item_id

// Pass 1: Top-level menu items
echo "Pass 1: Creating top-level menu items...\n";
foreach ( $vi_menu_items as $item ) {
    if ( $item->menu_item_parent == 0 ) {
        $vi_page_id = $item->object_id;
        $en_page_id = pll_get_post( $vi_page_id, 'en' );
        
        $item_title_lower = mb_strtolower( trim( html_entity_decode( $item->title ) ) );
        $en_item_title = isset( $menu_title_maps[ $item_title_lower ] ) ? $menu_title_maps[ $item_title_lower ] : $item->title;
        
        $en_item_id = wp_update_nav_menu_item( $en_menu_id, 0, array(
            'menu-item-object-id' => $en_page_id,
            'menu-item-object'    => 'page',
            'menu-item-parent-id' => 0,
            'menu-item-type'      => 'post_type',
            'menu-item-title'     => $en_item_title,
            'menu-item-status'    => 'publish',
        ) );
        
        $menu_item_mapping[ $item->ID ] = $en_item_id;
        echo "  Created Menu Item: '{$en_item_title}' (linked to Page ID: {$en_page_id})\n";
    }
}

// Pass 2: Child menu items
echo "Pass 2: Creating child menu items...\n";
foreach ( $vi_menu_items as $item ) {
    if ( $item->menu_item_parent != 0 ) {
        $vi_page_id = $item->object_id;
        $en_page_id = pll_get_post( $vi_page_id, 'en' );
        
        $item_title_lower = mb_strtolower( trim( html_entity_decode( $item->title ) ) );
        $en_item_title = isset( $menu_title_maps[ $item_title_lower ] ) ? $menu_title_maps[ $item_title_lower ] : $item->title;
        
        // Find English parent menu item ID
        $vi_parent_menu_item_id = $item->menu_item_parent;
        $en_parent_menu_item_id = isset( $menu_item_mapping[ $vi_parent_menu_item_id ] ) ? $menu_item_mapping[ $vi_parent_menu_item_id ] : 0;
        
        $en_item_id = wp_update_nav_menu_item( $en_menu_id, 0, array(
            'menu-item-object-id' => $en_page_id,
            'menu-item-object'    => 'page',
            'menu-item-parent-id' => $en_parent_menu_item_id,
            'menu-item-type'      => 'post_type',
            'menu-item-title'     => $en_item_title,
            'menu-item-status'    => 'publish',
        ) );
        
        $menu_item_mapping[ $item->ID ] = $en_item_id;
        echo "  Created Submenu Item: '{$en_item_title}' (linked to Page ID: {$en_page_id}, Parent Menu Item ID: {$en_parent_menu_item_id})\n";
    }
}

echo "Menu items rebuilt successfully.\n";
echo "Automated translation & menu setup complete!\n";
