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

function lt_core_structured_content_schema() {
    return array(
        'practice' => array(
            'lt_services_structured' => array(
                'label'=>__( 'Structured services', 'law-temple-core' ), 'legacy'=>'lt_services',
                'columns'=>array( 'title'=>__( 'Service', 'law-temple-core' ), 'description'=>__( 'Description', 'law-temple-core' ) ),
            ),
            'lt_capabilities_structured' => array(
                'label'=>__( 'Structured capabilities', 'law-temple-core' ), 'legacy'=>'lt_capabilities',
                'columns'=>array( 'title'=>__( 'Capability', 'law-temple-core' ), 'description'=>__( 'Description', 'law-temple-core' ) ),
            ),
        ),
        'matter' => array(
            'lt_work_structured' => array(
                'label'=>__( 'Structured legal work', 'law-temple-core' ), 'legacy'=>'lt_legal_work',
                'columns'=>array( 'title'=>__( 'Workstream / heading', 'law-temple-core' ), 'description'=>__( 'Description', 'law-temple-core' ) ),
            ),
            'lt_outcomes_structured' => array(
                'label'=>__( 'Structured outcomes', 'law-temple-core' ), 'legacy'=>'lt_outcome',
                'columns'=>array( 'title'=>__( 'Outcome / heading', 'law-temple-core' ), 'description'=>__( 'Description', 'law-temple-core' ) ),
            ),
        ),
    );
}

function lt_core_get_structured_records( $post_id, $key ) {
    $records = get_post_meta( $post_id, $key, true );
    return is_array( $records ) ? $records : array();
}

function lt_core_register_structured_content_meta() {
    foreach ( lt_core_structured_content_schema() as $post_type => $fields ) {
        foreach ( $fields as $key => $cfg ) {
            $properties=array(); foreach($cfg['columns'] as $column=>$label)$properties[$column]=array('type'=>'string');
            register_post_meta( $post_type, $key, array(
                'type'=>'array','single'=>true,'default'=>array(),
                'show_in_rest'=>array('schema'=>array('type'=>'array','items'=>array('type'=>'object','properties'=>$properties,'additionalProperties'=>false))),
                'sanitize_callback'=>function($value)use($cfg){return lt_core_sanitize_professional_records($value,$cfg['columns']);},
                'auth_callback'=>function($allowed,$meta_key,$post_id){return current_user_can('edit_post',$post_id);},
            ) );
        }
    }
}
add_action( 'init', 'lt_core_register_structured_content_meta', 8 );

function lt_core_structured_content_meta_boxes() {
    add_meta_box( 'lt-core-practice-structured', __( 'Structured Services & Capabilities', 'law-temple-core' ), 'lt_core_render_structured_content_box', 'practice', 'normal', 'default' );
    add_meta_box( 'lt-core-matter-structured', __( 'Structured Matter Detail', 'law-temple-core' ), 'lt_core_render_structured_content_box', 'matter', 'normal', 'default' );
}
add_action( 'add_meta_boxes', 'lt_core_structured_content_meta_boxes' );

function lt_core_render_structured_content_box( $post ) {
    $all=lt_core_structured_content_schema(); $schema=$all[$post->post_type]??array();
    if(!$schema)return; wp_nonce_field('lt_core_structured_content','lt_core_structured_content_nonce');
    echo '<p class="description">'.esc_html__('Use structured records when individual items need their own headings/descriptions. Existing legacy text remains a fallback until structured records are added.','law-temple-core').'</p>';
    foreach($schema as $key=>$cfg){$records=lt_core_get_structured_records($post->ID,$key);$legacy=trim((string)get_post_meta($post->ID,$cfg['legacy'],true));
        echo '<section class="lt-repeatable-section" data-repeatable-key="'.esc_attr($key).'"><div class="lt-repeatable-section__head"><div><h3>'.esc_html($cfg['label']).'</h3></div><span class="lt-record-count"><strong>'.esc_html((string)count($records)).'</strong> '.esc_html__('records','law-temple-core').'</span></div><div class="lt-repeatable-rows">';
        foreach($records as $index=>$row)lt_core_render_professional_row($key,$cfg,$index,$row);
        echo '</div><div class="lt-repeatable-actions"><button type="button" class="button button-primary lt-repeatable-add">'.esc_html__('Add record','law-temple-core').'</button></div><template class="lt-repeatable-template">';lt_core_render_professional_row($key,$cfg,'__INDEX__',array(),true);echo '</template>';
        if($legacy)echo '<details class="lt-legacy-fallback"><summary>'.esc_html__('Legacy text fallback','law-temple-core').'</summary><pre>'.esc_html($legacy).'</pre></details>';
        echo '</section>';
    }
}

function lt_core_save_structured_content( $post_id, $post ) {
    $all=lt_core_structured_content_schema(); if(empty($all[$post->post_type]))return;
    if(!isset($_POST['lt_core_structured_content_nonce'])||!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['lt_core_structured_content_nonce'])),'lt_core_structured_content'))return;
    if(defined('DOING_AUTOSAVE')&&DOING_AUTOSAVE)return; if(!current_user_can('edit_post',$post_id))return;
    $raw=isset($_POST['lt_professional'])&&is_array($_POST['lt_professional'])?wp_unslash($_POST['lt_professional']):array();
    foreach($all[$post->post_type] as $key=>$cfg)update_post_meta($post_id,$key,lt_core_sanitize_professional_records($raw[$key]??array(),$cfg['columns']));
}
add_action( 'save_post_practice', 'lt_core_save_structured_content', 25, 2 );
add_action( 'save_post_matter', 'lt_core_save_structured_content', 25, 2 );
