<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Law Temple demo importer.
 *
 * Demo data is optional and idempotent. Existing non-demo content with the
 * same slug is left untouched. Sensitive showcase records (matters, awards,
 * testimonials, careers and editorial examples) remain drafts in the manifest.
 */

function lt_core_demo_manifest_path() {
    return LT_CORE_DIR . 'demo/full-law-temple-demo.json';
}

function lt_core_get_demo_manifest() {
    $path = lt_core_demo_manifest_path();
    if ( ! file_exists( $path ) ) { return new WP_Error( 'lt_demo_missing', __( 'Law Temple demo manifest is missing.', 'law-temple-core' ) ); }
    $data = json_decode( (string) file_get_contents( $path ), true );
    if ( ! is_array( $data ) ) { return new WP_Error( 'lt_demo_invalid', __( 'Law Temple demo manifest is invalid.', 'law-temple-core' ) ); }
    return $data;
}

function lt_core_demo_find_post( $post_type, $slug ) {
    $posts = get_posts( array(
        'post_type'      => $post_type,
        'post_status'    => array( 'publish', 'draft', 'private', 'pending' ),
        'name'           => sanitize_title( $slug ),
        'posts_per_page' => 1,
        'fields'         => 'ids',
        'no_found_rows'  => true,
    ) );
    return $posts ? absint( $posts[0] ) : 0;
}

function lt_core_demo_find_page( $slug ) {
    $page = get_page_by_path( sanitize_title( $slug ), OBJECT, 'page' );
    return $page ? absint( $page->ID ) : 0;
}

function lt_core_demo_import_post( $post_type, array $item, array &$report ) {
    $slug = sanitize_title( $item['slug'] ?? '' );
    if ( ! $slug ) { return 0; }

    $existing = 'page' === $post_type ? lt_core_demo_find_page( $slug ) : lt_core_demo_find_post( $post_type, $slug );
    if ( $existing ) {
        if ( 'page' === $post_type ) {
            $existing_post = get_post( $existing );
            if ( $existing_post && '' === trim( (string) $existing_post->post_content ) && ! empty( $item['content'] ) ) {
                wp_update_post( array( 'ID'=>$existing, 'post_content'=>wp_kses_post( $item['content'] ) ) );
                update_post_meta( $existing, 'lt_demo_content', 1 );
                foreach ( (array) ( $item['meta'] ?? array() ) as $key=>$value ) {
                    if ( str_ends_with( (string) $key, '_refs' ) || str_ends_with( (string) $key, '_ref' ) ) { continue; }
                    update_post_meta( $existing, sanitize_key( $key ), is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : wp_kses_post( $value ) );
                }
                $report['created'][] = $post_type . ':' . $slug . ':filled-empty-existing-page';
                return $existing;
            }
        }
        $report['skipped'][] = $post_type . ':' . $slug;
        return $existing;
    }

    $status = sanitize_key( $item['status'] ?? 'draft' );
    if ( ! in_array( $status, array( 'publish', 'draft', 'private', 'pending' ), true ) ) { $status = 'draft'; }

    $postarr = array(
        'post_type'    => $post_type,
        'post_status'  => $status,
        'post_title'   => sanitize_text_field( $item['title'] ?? $slug ),
        'post_name'    => $slug,
        'post_excerpt' => wp_kses_post( $item['excerpt'] ?? '' ),
        'post_content' => wp_kses_post( $item['content'] ?? '' ),
        'menu_order'   => absint( $item['order'] ?? 0 ),
    );
    $id = wp_insert_post( $postarr, true );
    if ( is_wp_error( $id ) ) {
        $report['errors'][] = $post_type . ':' . $slug . ' - ' . $id->get_error_message();
        return 0;
    }

    update_post_meta( $id, 'lt_demo_content', 1 );
    if ( ! empty( $item['notice'] ) ) { update_post_meta( $id, 'lt_demo_notice', sanitize_text_field( $item['notice'] ) ); }

    foreach ( (array) ( $item['meta'] ?? array() ) as $key => $value ) {
        if ( str_ends_with( (string) $key, '_refs' ) || str_ends_with( (string) $key, '_ref' ) ) { continue; }
        update_post_meta( $id, sanitize_key( $key ), is_array( $value ) ? array_map( 'sanitize_text_field', $value ) : wp_kses_post( $value ) );
    }

    if ( ! empty( $item['asset'] ) ) {
        $attachment = lt_core_import_demo_asset( sanitize_file_name( $item['asset'] ), $id );
        if ( $attachment ) { update_post_meta( $id, 'lt_demo_asset_id', $attachment ); }
    }

    if ( taxonomy_exists( 'sector' ) && ! empty( $item['sectors'] ) ) {
        $term_ids = array();
        foreach ( (array) $item['sectors'] as $sector_slug ) {
            $term = get_term_by( 'slug', sanitize_title( $sector_slug ), 'sector' );
            if ( $term ) { $term_ids[] = absint( $term->term_id ); }
        }
        if ( $term_ids ) { wp_set_object_terms( $id, $term_ids, 'sector', false ); }
    }

    $report['created'][] = $post_type . ':' . $slug;
    return absint( $id );
}

function lt_core_demo_resolve_refs( $post_id, $post_type, array $meta ) {
    $maps = array(
        'lt_practice_refs' => array( 'key'=>'lt_practice_ids', 'type'=>'practice', 'multi'=>true ),
        'lt_lawyer_refs'   => array( 'key'=>'lt_lawyer_ids', 'type'=>'lawyer', 'multi'=>true ),
        'lt_office_refs'   => array( 'key'=>'lt_office_ids', 'type'=>'office', 'multi'=>true ),
        'lt_insight_refs'  => array( 'key'=>'lt_insight_ids', 'type'=>'insight', 'multi'=>true ),
        'lt_matter_refs'   => array( 'key'=>'lt_matter_ids', 'type'=>'matter', 'multi'=>true ),
        'lt_faq_refs'      => array( 'key'=>'lt_faq_ids', 'type'=>'lt_faq', 'multi'=>true ),
        'lt_lawyer_ref'    => array( 'key'=>'lt_lawyer_id', 'type'=>'lawyer', 'multi'=>false ),
        'lt_practice_ref'  => array( 'key'=>'lt_practice_id', 'type'=>'practice', 'multi'=>false ),
        'lt_insight_ref'   => array( 'key'=>'lt_insight_id', 'type'=>'insight', 'multi'=>false ),
    );
    foreach ( $maps as $ref_key => $cfg ) {
        if ( ! array_key_exists( $ref_key, $meta ) ) { continue; }
        $slugs = is_array( $meta[ $ref_key ] ) ? $meta[ $ref_key ] : array( $meta[ $ref_key ] );
        $ids = array();
        foreach ( $slugs as $slug ) {
            $id = lt_core_demo_find_post( $cfg['type'], sanitize_title( $slug ) );
            if ( $id ) { $ids[] = $id; }
        }
        if ( $cfg['multi'] ) { update_post_meta( $post_id, $cfg['key'], implode( ',', array_unique( array_map( 'absint', $ids ) ) ) ); }
        else { update_post_meta( $post_id, $cfg['key'], $ids ? absint( $ids[0] ) : 0 ); }
    }
}

function lt_core_demo_create_sectors( array $sectors, array &$report ) {
    foreach ( $sectors as $sector ) {
        $slug = sanitize_title( $sector['slug'] ?? '' );
        if ( ! $slug ) { continue; }
        $existing = get_term_by( 'slug', $slug, 'sector' );
        if ( $existing ) { $report['skipped'][] = 'sector:' . $slug; continue; }
        $term = wp_insert_term( sanitize_text_field( $sector['name'] ?? $slug ), 'sector', array(
            'slug'        => $slug,
            'description' => sanitize_textarea_field( $sector['description'] ?? '' ),
        ) );
        if ( is_wp_error( $term ) ) { $report['errors'][] = 'sector:' . $slug . ' - ' . $term->get_error_message(); }
        else { $report['created'][] = 'sector:' . $slug; }
    }
}

function lt_core_demo_apply_firm_settings( array $settings, $office_id = 0, $page_ids = array() ) {
    $current = lt_core_options();
    foreach ( $settings as $key => $value ) {
        if ( '' === (string) ( $current[ $key ] ?? '' ) || in_array( $key, array( 'firm_name','short_name','tagline','description','label_practice','label_people','label_insights','label_sectors','label_matters' ), true ) ) {
            $current[ $key ] = $value;
        }
    }
    if ( $office_id ) { $current['main_office_id'] = absint( $office_id ); }
    if ( ! empty( $page_ids['privacy'] ) ) { $current['privacy_page_id'] = absint( $page_ids['privacy'] ); }
    if ( ! empty( $page_ids['disclaimer'] ) ) { $current['disclaimer_page_id'] = absint( $page_ids['disclaimer'] ); }
    update_option( 'lt_core_options', lt_core_sanitize_options( $current ), false );
}

function lt_core_demo_import_brand_assets( array &$report ) {
    $ids = array();
    foreach ( array( 'logo'=>'law-temple-logo.png', 'favicon'=>'favicon.png' ) as $key => $file ) {
        $existing = get_posts( array( 'post_type'=>'attachment', 'post_status'=>'inherit', 'posts_per_page'=>1, 'meta_key'=>'lt_demo_asset_name', 'meta_value'=>$file, 'fields'=>'ids' ) );
        if ( $existing ) { $ids[ $key ] = absint( $existing[0] ); continue; }
        $id = lt_core_import_demo_asset( $file, 0 );
        if ( $id ) { update_post_meta( $id, 'lt_demo_asset_name', $file ); $ids[ $key ] = $id; $report['created'][] = 'media:' . $file; }
    }
    if ( ! empty( $ids['favicon'] ) && ! get_option( 'site_icon' ) ) { update_option( 'site_icon', absint( $ids['favicon'] ) ); }
    if ( ! empty( $ids['logo'] ) ) {
        $mods = get_theme_mods();
        if ( empty( $mods['custom_logo'] ) ) { set_theme_mod( 'custom_logo', absint( $ids['logo'] ) ); }
    }
    return $ids;
}

function lt_core_demo_apply_theme_settings( array $ids, array $post_ids ) {
    $current = get_option( 'lt_theme_options_v3', array() );
    if ( ! is_array( $current ) ) { $current = array(); }
    $settings = array(
        'preset'=>'classic',
        'primary'=>'#064559','secondary'=>'#102B3A','accent'=>'#BB8031','gold'=>'#BB8031','heading'=>'#064559','text'=>'#20272B','muted'=>'#667078','background'=>'#FFFFFF','alternate'=>'#FAF8F4','dark'=>'#102B3A','border'=>'#E6E1D8','footer'=>'#102B3A','footer_text'=>'#DCE4E7',
        'logo_primary'=>absint( $ids['logo'] ?? 0 ),'logo_alt'=>absint( $ids['logo'] ?? 0 ),'logo_dark'=>absint( $ids['logo'] ?? 0 ),'logo_sticky'=>absint( $ids['logo'] ?? 0 ),'logo_mobile'=>absint( $ids['logo'] ?? 0 ),'logo_footer'=>absint( $ids['logo'] ?? 0 ),'favicon'=>absint( $ids['favicon'] ?? 0 ),
        'intro_heading'=>'Professional counsel. Practical judgment.',
        'intro_text'=>'Law Temple provides legal advisory and representation services from Accra, combining careful legal analysis with practical communication and a clear understanding of the client’s objective.',
        'values_heading'=>'What guides our work',
        'values_items'=>"Integrity|Professional independence and ethical responsibility.\nClarity|Complex issues explained in practical terms.\nResponsiveness|Timely support when timing matters.\nJudgment|Advice shaped by law, context and consequence.",
        'home_practice_count'=>7,'home_people_count'=>4,'home_insight_count'=>3,
        'home_order'=>'hero,intro,practices,people,values,insights,contact,sectors,matters,testimonials,awards,offices,careers,faq,custom','home_disabled'=>'sectors,matters,testimonials,awards,offices,careers,faq,custom',
        'practice_archive_heading'=>'Our Expertise','practice_archive_intro'=>'Explore Law Temple’s legal services and the areas in which the firm supports businesses, institutions, investors and individuals.',
        'people_archive_heading'=>'Our People','people_archive_intro'=>'Meet the professionals of Law Temple. Individual qualifications and detailed biographies should be maintained directly in each profile.',
        'insight_archive_heading'=>'Insights','insight_archive_intro'=>'Legal updates, commentary and publications from Law Temple. Demo editorial entries are installed as drafts pending legal review.',
        'global_cta_id'=>absint( $post_ids['cta:contact-the-firm'] ?? 0 ),
        'header_layout'=>'logo-left','header_height'=>80,'show_home_menu_item'=>0,'show_search'=>1,'logo_mobile_width'=>154,'mobile_menu_layout'=>'drawer','mobile_drawer_width'=>92,'mobile_sticky_header'=>1,'mobile_show_topbar'=>0,'mobile_show_announcement'=>1,'mobile_show_header_cta'=>0,'mobile_breadcrumbs'=>1,'mobile_profile_nav'=>'scroll','mobile_filters_layout'=>'stack','mobile_footer_align'=>'left',
        'nav_size'=>14,'nav_weight'=>600,'nav_letter'=>0.25,'nav_transform'=>'none',
        'h1_size'=>64,'h2_size'=>46,'h3_size'=>28,'heading_weight'=>500,'section_y'=>78,'grid_gap'=>32,
        'tablet_h1'=>54,'tablet_h2'=>40,'tablet_body'=>16,'mobile_h1'=>40,'mobile_h2'=>32,'mobile_body'=>16,
        'tablet_section_y'=>62,'mobile_section_y'=>46,'tablet_grid_gap'=>24,'mobile_grid_gap'=>18,'tablet_gutter'=>24,'mobile_gutter'=>18,
        'hero_desktop_height'=>600,'hero_tablet_height'=>540,'hero_mobile_height'=>520,'mobile_hero_media_height'=>320,'mobile_hero_media_position'=>'below','mobile_hero_hide_media'=>0,'mobile_hero_stack_buttons'=>1,
        'archive_hero_style'=>'surface','archive_show_filters'=>1,'archive_show_images'=>1,'archive_show_excerpts'=>1,
        'archive_columns'=>3,'archive_columns_tablet'=>2,'archive_columns_mobile'=>1,'archive_per_page'=>12,
        'profile_layout'=>'split','profile_nav_sticky'=>1,'profile_show_photo'=>1,'profile_contact_rail'=>0,'profile_content_width'=>'standard',
        'practice_single_layout'=>'editorial','practice_show_image'=>1,'practice_sticky_summary'=>0,'practice_content_width'=>'standard',
        'mega_menu'=>1,'mega_menu_target'=>'expertise','mega_menu_show_practices'=>1,'mega_menu_show_sectors'=>1,'mega_menu_practice_count'=>7,'mega_menu_sector_count'=>8,
        'mega_menu_practice_heading'=>'Practice Areas','mega_menu_sector_heading'=>'Sectors','mega_menu_cta_label'=>'View all expertise',
        'page_default_hero_layout'=>'minimal','page_default_layout'=>'full','page_default_breadcrumbs'=>'inherit','page_default_header_style'=>'standard','page_default_footer_style'=>'standard','page_default_cta'=>'inherit',
    );
    $practice_ids = array(); $lawyer_ids = array();
    foreach ( $post_ids as $key => $id ) {
        if ( str_starts_with( $key, 'practice:' ) ) { $practice_ids[] = absint( $id ); }
        if ( str_starts_with( $key, 'lawyer:' ) ) { $lawyer_ids[] = absint( $id ); }
    }
    if ( $practice_ids ) { $settings['home_practice_ids'] = implode( ',', $practice_ids ); }
    if ( $lawyer_ids ) { $settings['home_lawyer_ids'] = implode( ',', $lawyer_ids ); }
    update_option( 'lt_theme_options_v3', array_merge( $current, $settings ), false );
}

function lt_core_demo_build_navigation( array $page_ids ) {
    $name = __( 'Primary Navigation', 'law-temple-core' );
    $menu = wp_get_nav_menu_object( $name );
    $menu_id = $menu ? absint( $menu->term_id ) : wp_create_nav_menu( $name );
    if ( is_wp_error( $menu_id ) ) { return; }
    $items = wp_get_nav_menu_items( $menu_id );
    $existing_urls = array();
    foreach ( (array) $items as $item ) { $existing_urls[] = untrailingslashit( $item->url ); }
    $targets = array(
        array( 'title'=>__( 'About', 'law-temple-core' ), 'url'=>!empty($page_ids['about'])?get_permalink($page_ids['about']):home_url('/about/') ),
        array( 'title'=>__( 'Expertise', 'law-temple-core' ), 'url'=>get_post_type_archive_link( 'practice' ) ?: home_url('/expertise/') ),
        array( 'title'=>__( 'Our People', 'law-temple-core' ), 'url'=>get_post_type_archive_link( 'lawyer' ) ?: home_url('/people/') ),
        array( 'title'=>__( 'Insights', 'law-temple-core' ), 'url'=>get_post_type_archive_link( 'insight' ) ?: home_url('/insights/') ),
        array( 'title'=>__( 'Contact', 'law-temple-core' ), 'url'=>!empty($page_ids['contact'])?get_permalink($page_ids['contact']):home_url('/contact/') ),
    );
    foreach ( $targets as $target ) {
        if ( in_array( untrailingslashit( $target['url'] ), $existing_urls, true ) ) { continue; }
        wp_update_nav_menu_item( $menu_id, 0, array(
            'menu-item-title'=>$target['title'], 'menu-item-url'=>$target['url'], 'menu-item-status'=>'publish', 'menu-item-type'=>'custom'
        ) );
    }
    $locations = get_theme_mod( 'nav_menu_locations', array() );
    if ( empty( $locations['primary'] ) ) { $locations['primary'] = $menu_id; set_theme_mod( 'nav_menu_locations', $locations ); }
}

function lt_core_install_full_law_temple_demo() {
    if ( ! lt_core_current_user_can( 'lt_run_setup' ) ) { return new WP_Error( 'lt_demo_forbidden', __( 'You do not have permission to install demo content.', 'law-temple-core' ) ); }
    $manifest = lt_core_get_demo_manifest();
    if ( is_wp_error( $manifest ) ) { return $manifest; }

    $report = array( 'created'=>array(), 'skipped'=>array(), 'errors'=>array(), 'posts'=>array() );
    lt_core_demo_create_sectors( (array) ( $manifest['sectors'] ?? array() ), $report );

    $page_ids = array();
    foreach ( (array) ( $manifest['pages'] ?? array() ) as $item ) {
        $id = lt_core_demo_import_post( 'page', $item, $report );
        if ( $id ) { $page_ids[ sanitize_title( $item['slug'] ) ] = $id; $report['posts']['page:' . sanitize_title($item['slug'])] = $id; }
    }
    if ( ! empty( $page_ids['home'] ) ) { update_option( 'show_on_front', 'page' ); update_option( 'page_on_front', absint( $page_ids['home'] ) ); }
    if ( ! empty( $page_ids['privacy'] ) && ! get_option( 'wp_page_for_privacy_policy' ) ) { update_option( 'wp_page_for_privacy_policy', absint( $page_ids['privacy'] ) ); }

    $groups = array(
        'practices'=>'practice','offices'=>'office','lawyers'=>'lawyer','hero_slides'=>'hero_slide','faqs'=>'lt_faq','ctas'=>'lt_cta','insights'=>'insight','matters'=>'matter','testimonials'=>'testimonial','awards'=>'award','careers'=>'career'
    );
    $post_ids = array();
    foreach ( $groups as $manifest_key => $post_type ) {
        foreach ( (array) ( $manifest[ $manifest_key ] ?? array() ) as $item ) {
            $id = lt_core_demo_import_post( $post_type, $item, $report );
            if ( $id ) { $post_ids[ $post_type . ':' . sanitize_title( $item['slug'] ) ] = $id; $report['posts'][ $post_type . ':' . sanitize_title($item['slug']) ] = $id; }
        }
    }

    // Resolve post relationships after all records exist.
    foreach ( $groups as $manifest_key => $post_type ) {
        foreach ( (array) ( $manifest[ $manifest_key ] ?? array() ) as $item ) {
            $slug = sanitize_title( $item['slug'] ?? '' );
            $id = $post_ids[ $post_type . ':' . $slug ] ?? lt_core_demo_find_post( $post_type, $slug );
            if ( $id ) { lt_core_demo_resolve_refs( $id, $post_type, (array) ( $item['meta'] ?? array() ) ); }
        }
    }

    // Mirror lawyer/practice relationships when supplied on lawyer profiles.
    foreach ( (array) ( $manifest['lawyers'] ?? array() ) as $lawyer ) {
        $lawyer_id = lt_core_demo_find_post( 'lawyer', $lawyer['slug'] ?? '' );
        if ( ! $lawyer_id ) { continue; }
        foreach ( (array) ( $lawyer['meta']['lt_practice_refs'] ?? array() ) as $practice_slug ) {
            $practice_id = lt_core_demo_find_post( 'practice', $practice_slug );
            if ( ! $practice_id ) { continue; }
            $ids = lt_core_csv_ids( get_post_meta( $practice_id, 'lt_lawyer_ids', true ) );
            if ( ! in_array( $lawyer_id, $ids, true ) ) { $ids[] = $lawyer_id; update_post_meta( $practice_id, 'lt_lawyer_ids', implode( ',', $ids ) ); }
        }
    }

    $office_id = lt_core_demo_find_post( 'office', 'accra-office' );
    lt_core_demo_apply_firm_settings( (array) ( $manifest['firm_settings'] ?? array() ), $office_id, $page_ids );
    $assets = lt_core_demo_import_brand_assets( $report );
    lt_core_demo_apply_theme_settings( $assets, $post_ids );
    lt_core_demo_build_navigation( $page_ids );

    update_option( 'lt_core_demo_version', (string) ( $manifest['schema_version'] ?? 1 ), false );
    update_option( 'lt_core_demo_last_import', gmdate( 'c' ), false );
    update_option( 'lt_core_demo_import_report', $report, false );
    flush_rewrite_rules();
    return $report;
}

function lt_core_demo_summary() {
    $manifest = lt_core_get_demo_manifest();
    if ( is_wp_error( $manifest ) ) { return array(); }
    $counts = array();
    foreach ( array( 'pages','sectors','practices','offices','lawyers','hero_slides','faqs','ctas','insights','matters','testimonials','awards','careers' ) as $key ) {
        $counts[ $key ] = count( (array) ( $manifest[ $key ] ?? array() ) );
    }
    return $counts;
}
