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

/**
 * v3.0.0 role and capability architecture.
 *
 * The capability map is deliberately independent from public labels so firms can
 * rename "Lawyers" to "People" without invalidating stored permissions.
 */
function lt_core_capability_types() {
    return array(
        'lawyer'      => array( 'lt_lawyer', 'lt_lawyers' ),
        'practice'    => array( 'lt_practice', 'lt_practices' ),
        'insight'     => array( 'lt_insight', 'lt_insights' ),
        'matter'      => array( 'lt_matter', 'lt_matters' ),
        'testimonial' => array( 'lt_testimonial', 'lt_testimonials' ),
        'award'       => array( 'lt_award', 'lt_awards' ),
        'office'      => array( 'lt_office', 'lt_offices' ),
        'career'      => array( 'lt_career', 'lt_careers' ),
        'lt_faq'      => array( 'lt_faq_item', 'lt_faq_items' ),
        'hero_slide'  => array( 'lt_hero_slide', 'lt_hero_slides' ),
        'lt_cta'      => array( 'lt_cta_item', 'lt_cta_items' ),
    );
}

function lt_core_capability_type_for_post_type( $post_type ) {
    $map = lt_core_capability_types();
    return $map[ $post_type ] ?? array( 'post', 'posts' );
}

/** All primitive capabilities generated by map_meta_cap for one CPT. */
function lt_core_content_capabilities( $post_type, $full = true ) {
    $types = lt_core_capability_type_for_post_type( $post_type );
    $singular = $types[0];
    $plural   = $types[1];
    $caps = array(
        'read',
        'edit_' . $plural,
        'edit_published_' . $plural,
        'publish_' . $plural,
        'delete_' . $plural,
        'delete_published_' . $plural,
    );
    if ( $full ) {
        $caps = array_merge( $caps, array(
            'edit_others_' . $plural,
            'edit_private_' . $plural,
            'read_private_' . $plural,
            'delete_others_' . $plural,
            'delete_private_' . $plural,
        ) );
    }
    return array_values( array_unique( $caps ) );
}

function lt_core_all_content_capabilities( $types = null, $full = true ) {
    $types = is_array( $types ) ? $types : array_keys( lt_core_capability_types() );
    $caps = array();
    foreach ( $types as $type ) { $caps = array_merge( $caps, lt_core_content_capabilities( $type, $full ) ); }
    return array_values( array_unique( $caps ) );
}

function lt_core_framework_capabilities() {
    return array(
        'lt_access_firm_dashboard',
        'lt_manage_firm_settings',
        'lt_manage_firm_roles',
        'lt_manage_enquiries',
        'lt_manage_content_order',
        'lt_manage_data_architecture',
        'lt_manage_site_health',
        'lt_run_setup',
        'lt_manage_taxonomies',
        'lt_edit_taxonomies',
        'lt_delete_taxonomies',
        'lt_assign_taxonomies',
    );
}

function lt_core_role_definitions() {
    $content_all = lt_core_all_content_capabilities();
    $editor_base = array( 'read','upload_files','edit_pages','edit_others_pages','edit_published_pages','publish_pages','delete_pages','delete_published_pages' );
    $taxonomy = array( 'lt_assign_taxonomies','lt_edit_taxonomies','lt_manage_taxonomies','lt_delete_taxonomies' );

    return array(
        'lt_firm_administrator' => array(
            'label' => __( 'Law Firm Administrator', 'law-temple-core' ),
            'caps'  => array_merge(
                $editor_base,
                array( 'read_private_pages','delete_others_pages','delete_private_pages','edit_theme_options' ),
                $content_all,
                lt_core_framework_capabilities()
            ),
        ),
        'lt_content_editor' => array(
            'label' => __( 'Law Firm Content Editor', 'law-temple-core' ),
            'caps'  => array_merge(
                $editor_base,
                $content_all,
                $taxonomy,
                array( 'lt_access_firm_dashboard','lt_manage_content_order' )
            ),
        ),
        'lt_insights_author' => array(
            'label' => __( 'Law Firm Insights Author', 'law-temple-core' ),
            'caps'  => array_merge(
                array( 'read','upload_files','lt_access_firm_dashboard','lt_assign_taxonomies' ),
                lt_core_content_capabilities( 'insight', false )
            ),
        ),
        'lt_people_manager' => array(
            'label' => __( 'Law Firm People Manager', 'law-temple-core' ),
            'caps'  => array_merge(
                array( 'read','upload_files','lt_access_firm_dashboard','lt_manage_content_order','lt_assign_taxonomies','lt_edit_taxonomies' ),
                lt_core_content_capabilities( 'lawyer', true ),
                lt_core_content_capabilities( 'office', true )
            ),
        ),
        'lt_enquiry_manager' => array(
            'label' => __( 'Law Firm Enquiry Manager', 'law-temple-core' ),
            'caps'  => array( 'read','lt_access_firm_dashboard','lt_manage_enquiries' ),
        ),
    );
}

function lt_core_grant_caps_to_role( $role, $caps ) {
    if ( ! $role instanceof WP_Role ) { return; }
    foreach ( array_unique( $caps ) as $cap ) { $role->add_cap( $cap ); }
}

function lt_core_sync_roles_and_capabilities() {
    foreach ( lt_core_role_definitions() as $slug => $cfg ) {
        $role = get_role( $slug );
        if ( ! $role ) { $role = add_role( $slug, $cfg['label'], array( 'read'=>true ) ); }
        lt_core_grant_caps_to_role( $role, $cfg['caps'] );
    }

    // Administrators keep complete access after an in-place plugin update.
    $administrator = get_role( 'administrator' );
    if ( $administrator ) {
        lt_core_grant_caps_to_role( $administrator, array_merge( lt_core_all_content_capabilities(), lt_core_framework_capabilities() ) );
    }

    // Preserve the broad editorial access that WordPress Editors had before v3.0.0.
    $editor = get_role( 'editor' );
    if ( $editor ) {
        lt_core_grant_caps_to_role( $editor, array_merge( lt_core_all_content_capabilities(), array( 'lt_access_firm_dashboard','lt_manage_content_order','lt_assign_taxonomies','lt_edit_taxonomies','lt_manage_taxonomies','lt_delete_taxonomies' ) ) );
    }

    // Preserve a sensible authoring path for existing WordPress Authors.
    $author = get_role( 'author' );
    if ( $author ) {
        lt_core_grant_caps_to_role( $author, array_merge( lt_core_content_capabilities( 'insight', false ), array( 'lt_access_firm_dashboard','lt_assign_taxonomies' ) ) );
    }

    update_option( 'lt_core_roles_version', LT_CORE_VERSION, false );
}

function lt_core_maybe_sync_roles() {
    if ( LT_CORE_VERSION !== (string) get_option( 'lt_core_roles_version', '' ) ) { lt_core_sync_roles_and_capabilities(); }
}
add_action( 'init', 'lt_core_maybe_sync_roles', 4 );

function lt_core_current_user_can( $capability ) {
    return current_user_can( $capability ) || current_user_can( 'manage_options' );
}

/** Allow the dedicated Firm Administrator to submit the Core Settings API form. */
function lt_core_settings_page_capability() { return 'lt_manage_firm_settings'; }
add_filter( 'option_page_capability_lt_core_settings', 'lt_core_settings_page_capability' );

function lt_core_roles_menu() {
    add_submenu_page(
        'lt-core-dashboard',
        __( 'Roles & Permissions', 'law-temple-core' ),
        __( 'Roles & Permissions', 'law-temple-core' ),
        'lt_manage_firm_roles',
        'lt-core-roles',
        'lt_core_roles_page'
    );
}
add_action( 'admin_menu', 'lt_core_roles_menu', 37 );

function lt_core_roles_page() {
    if ( ! lt_core_current_user_can( 'lt_manage_firm_roles' ) ) { return; }
    if ( isset( $_POST['lt_sync_roles'] ) ) {
        check_admin_referer( 'lt_sync_roles', 'lt_sync_roles_nonce' );
        lt_core_sync_roles_and_capabilities();
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Law Firm roles and capabilities synchronized.', 'law-temple-core' ) . '</p></div>';
    }
    echo '<div class="wrap"><h1>' . esc_html__( 'Roles & Permissions', 'law-temple-core' ) . '</h1>';
    echo '<p>' . esc_html__( 'Use WordPress Users to assign these roles. The framework uses capabilities rather than hard-coded role names, so developers can extend the permission model safely.', 'law-temple-core' ) . '</p>';
    echo '<table class="widefat striped" style="max-width:1100px"><thead><tr><th>' . esc_html__( 'Role', 'law-temple-core' ) . '</th><th>' . esc_html__( 'Intended use', 'law-temple-core' ) . '</th><th>' . esc_html__( 'Key access', 'law-temple-core' ) . '</th></tr></thead><tbody>';
    $rows = array(
        'lt_firm_administrator' => array( __( 'Senior website/firm administrator without full WordPress plugin-install privileges.', 'law-temple-core' ), __( 'Theme Options, firm settings, all legal content, setup, health and data tools.', 'law-temple-core' ) ),
        'lt_content_editor'      => array( __( 'Editorial manager responsible for day-to-day public website content.', 'law-temple-core' ), __( 'Pages and all Law Firm content, but not global firm/security settings.', 'law-temple-core' ) ),
        'lt_insights_author'     => array( __( 'Lawyer or communications author focused on knowledge content.', 'law-temple-core' ), __( 'Create, publish and maintain their Insight content and assign taxonomies.', 'law-temple-core' ) ),
        'lt_people_manager'      => array( __( 'HR/communications user responsible for professional profiles and offices.', 'law-temple-core' ), __( 'People and Office records plus relevant taxonomy assignment.', 'law-temple-core' ) ),
        'lt_enquiry_manager'     => array( __( 'User responsible for intake operations without general editing access.', 'law-temple-core' ), __( 'Enquiry Operations diagnostics and delivery testing.', 'law-temple-core' ) ),
    );
    foreach ( lt_core_role_definitions() as $slug => $cfg ) {
        $row = $rows[ $slug ] ?? array( '', '' );
        echo '<tr><td><strong>' . esc_html( $cfg['label'] ) . '</strong><br><code>' . esc_html( $slug ) . '</code></td><td>' . esc_html( $row[0] ) . '</td><td>' . esc_html( $row[1] ) . '</td></tr>';
    }
    echo '</tbody></table><form method="post" style="margin-top:18px">'; wp_nonce_field( 'lt_sync_roles', 'lt_sync_roles_nonce' ); submit_button( __( 'Synchronize role capabilities', 'law-temple-core' ), 'secondary', 'lt_sync_roles', false ); echo '</form>';
    echo '<p class="description">' . esc_html__( 'Administrators retain all framework capabilities. Existing WordPress Editors retain broad content access for upgrade compatibility, and Authors retain an Insight-authoring path.', 'law-temple-core' ) . '</p></div>';
}
