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

function lt_core_page_builder_menu() {
    add_submenu_page(
        'lt-core-dashboard',
        __( 'Page Builder', 'law-temple-core' ),
        __( 'Page Builder', 'law-temple-core' ),
        'edit_pages',
        'lt-page-builder',
        'lt_core_page_builder_page'
    );
}
add_action( 'admin_menu', 'lt_core_page_builder_menu', 18 );

function lt_core_page_builder_page() {
    if ( ! current_user_can( 'edit_pages' ) ) { return; }
    $notice = get_transient( 'lt_page_builder_notice_' . get_current_user_id() );
    if ( $notice ) { delete_transient( 'lt_page_builder_notice_' . get_current_user_id() ); }
    $layouts = array(
        'about'        => array( __( 'About the Firm', 'law-temple-core' ), __( 'Firm overview, values, expertise, people and CTA.', 'law-temple-core' ) ),
        'contact'      => array( __( 'Contact', 'law-temple-core' ), __( 'Contact introduction, offices and enquiry form.', 'law-temple-core' ) ),
        'landing'      => array( __( 'Professional Landing Page', 'law-temple-core' ), __( 'Hero, introduction, services, proof points and CTA.', 'law-temple-core' ) ),
        'jurisdiction' => array( __( 'Jurisdiction / Doing Business Guide', 'law-temple-core' ), __( 'Editorial guide layout with services, people and insights.', 'law-temple-core' ) ),
        'careers'      => array( __( 'Careers', 'law-temple-core' ), __( 'Employer introduction, values, vacancies and CTA.', 'law-temple-core' ) ),
        'team'         => array( __( 'People Landing Page', 'law-temple-core' ), __( 'Introduction, people directory and contact CTA.', 'law-temple-core' ) ),
        'expertise'    => array( __( 'Expertise Landing Page', 'law-temple-core' ), __( 'Practice Areas, sectors and representative matters.', 'law-temple-core' ) ),
        'insights'     => array( __( 'Knowledge / Insights Landing Page', 'law-temple-core' ), __( 'Editorial introduction and dynamic insights.', 'law-temple-core' ) ),
        'faq'          => array( __( 'FAQ Page', 'law-temple-core' ), __( 'Introduction, reusable FAQs and enquiry CTA.', 'law-temple-core' ) ),
        'basic'        => array( __( 'Editorial Content Page', 'law-temple-core' ), __( 'Flexible long-form page for policies, guides or firm information.', 'law-temple-core' ) ),
    );
    $blocks = array(
        'Practice Areas','People / Lawyers','Insights','Sectors / Industries','Representative Matters','Testimonials','Offices','Awards & Recognition','Careers / Vacancies','FAQs','Global CTA','Enquiry Form'
    );
    echo '<div class="wrap"><h1>' . esc_html__( 'Law Firm Page Builder', 'law-temple-core' ) . '</h1>';
    echo '<p>' . esc_html__( 'Build any internal page with the native WordPress Block Editor. Use Law Firm page patterns as complete starting layouts, then drag, duplicate, remove and reorder sections like ordinary Gutenberg blocks.', 'law-temple-core' ) . '</p>';
    if ( $notice ) { echo '<div class="notice notice-' . esc_attr( $notice['type'] ) . ' is-dismissible"><p>' . esc_html( $notice['message'] ) . '</p></div>'; }
    $blank_builder = wp_nonce_url( admin_url( 'admin-post.php?action=lt_create_builder_page' ), 'lt_create_builder_page' );
    echo '<p><a class="button button-primary" href="' . esc_url( $blank_builder ) . '">' . esc_html__( 'Create Blank Builder Page', 'law-temple-core' ) . '</a> <a class="button" href="' . esc_url( admin_url( 'post-new.php?post_type=page' ) ) . '">' . esc_html__( 'Create Standard Page', 'law-temple-core' ) . '</a> <a class="button" href="' . esc_url( admin_url( 'edit.php?post_type=page' ) ) . '">' . esc_html__( 'Manage Pages', 'law-temple-core' ) . '</a></p>';
    echo '<div style="display:grid;grid-template-columns:minmax(0,1.35fr) minmax(280px,.65fr);gap:24px;max-width:1200px">';
    echo '<div><h2>' . esc_html__( 'Full-page starter layouts', 'law-temple-core' ) . '</h2><p>' . esc_html__( 'In the page editor open the Inserter (+), choose Patterns, then Law Firm Pages. Insert a complete layout and edit it visually.', 'law-temple-core' ) . '</p><div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:14px">';
    foreach ( $layouts as $key=>$row ) {
        echo '<div style="background:#fff;border:1px solid #dcdcde;padding:18px"><h3 style="margin-top:0">' . esc_html( $row[0] ) . '</h3><p>' . esc_html( $row[1] ) . '</p>';
        $page = get_page_by_path( 'about' === $key ? 'about' : ( 'contact' === $key ? 'contact' : '' ) );
        if ( $page && in_array( $key, array('about','contact'), true ) ) {
            $url = wp_nonce_url( admin_url( 'admin-post.php?action=lt_apply_page_starter&page_id=' . absint( $page->ID ) . '&starter=' . $key ), 'lt_apply_page_starter_' . absint( $page->ID ) );
            if ( '' === trim( (string) $page->post_content ) ) {
                echo '<p><a class="button" href="' . esc_url( $url ) . '">' . esc_html( sprintf( __( 'Apply to empty %s page', 'law-temple-core' ), $row[0] ) ) . '</a></p>';
            } elseif ( get_post_meta( $page->ID, 'lt_demo_content', true ) ) {
                $refresh = add_query_arg( 'refresh_demo', 1, $url );
                echo '<p><a class="button" href="' . esc_url( $refresh ) . '" onclick="return confirm(\'' . esc_js( __( 'Replace the current demo page content with the v3.0.0 starter layout? WordPress revisions will preserve the previous version.', 'law-temple-core' ) ) . '\')">' . esc_html( sprintf( __( 'Refresh demo %s layout', 'law-temple-core' ), $row[0] ) ) . '</a></p>';
            }
        }
        echo '</div>';
    }
    echo '</div></div>';
    echo '<aside><h2>' . esc_html__( 'Law Firm dynamic blocks', 'law-temple-core' ) . '</h2><p>' . esc_html__( 'These blocks query structured Core content automatically and can be dropped anywhere on a page.', 'law-temple-core' ) . '</p><ul style="background:#fff;border:1px solid #dcdcde;padding:18px 18px 18px 36px">';
    foreach ( $blocks as $block ) { echo '<li>' . esc_html( $block ) . '</li>'; }
    echo '</ul><h3>' . esc_html__( 'Builder Canvas', 'law-temple-core' ) . '</h3><p>' . esc_html__( 'For full-width compositions select “Builder Canvas” in Law Firm Page Options or choose the “Law Firm Block Builder” page template. Standard pages can keep the restrained editorial layout.', 'law-temple-core' ) . '</p></aside></div></div>';
}

function lt_core_apply_page_starter() {
    if ( ! current_user_can( 'edit_pages' ) ) { wp_die( esc_html__( 'You are not allowed to edit pages.', 'law-temple-core' ) ); }
    $page_id = absint( $_GET['page_id'] ?? 0 );
    $starter = sanitize_key( $_GET['starter'] ?? '' );
    check_admin_referer( 'lt_apply_page_starter_' . $page_id );
    $post = get_post( $page_id );
    $notice = array( 'type'=>'error', 'message'=>__( 'The starter layout could not be applied.', 'law-temple-core' ) );
    if ( $post && 'page' === $post->post_type && current_user_can( 'edit_post', $page_id ) ) {
        $refresh_demo = ! empty( $_GET['refresh_demo'] ) && get_post_meta( $page_id, 'lt_demo_content', true );
        if ( '' !== trim( (string) $post->post_content ) && ! $refresh_demo ) {
            $notice = array( 'type'=>'warning', 'message'=>__( 'The page already contains content, so nothing was overwritten.', 'law-temple-core' ) );
        } else {
            $content = '';
            if ( $refresh_demo && function_exists( 'lt_core_get_demo_manifest' ) ) {
                $manifest = lt_core_get_demo_manifest();
                if ( is_array( $manifest ) ) {
                    foreach ( (array) ( $manifest['pages'] ?? array() ) as $demo_page ) {
                        if ( $starter === sanitize_title( $demo_page['slug'] ?? '' ) ) { $content = (string) ( $demo_page['content'] ?? '' ); break; }
                    }
                }
            }
            if ( ! $content ) { $content = apply_filters( 'lt_core_starter_page_content', '', $starter, $page_id ); }
            if ( $content ) {
                wp_update_post( array( 'ID'=>$page_id, 'post_content'=>$content ) );
                update_post_meta( $page_id, 'lt_page_layout', 'builder' );
                update_post_meta( $page_id, 'lt_page_hero_layout', 'none' );
                $notice = array( 'type'=>'success', 'message'=>__( 'Starter layout applied. Open the page editor to customize the blocks.', 'law-temple-core' ) );
            }
        }
    }
    set_transient( 'lt_page_builder_notice_' . get_current_user_id(), $notice, 60 );
    wp_safe_redirect( admin_url( 'admin.php?page=lt-page-builder' ) ); exit;
}
add_action( 'admin_post_lt_apply_page_starter', 'lt_core_apply_page_starter' );

function lt_core_create_builder_page() {
    if ( ! current_user_can( 'edit_pages' ) ) { wp_die( esc_html__( 'You are not allowed to create pages.', 'law-temple-core' ) ); }
    check_admin_referer( 'lt_create_builder_page' );
    $id = wp_insert_post( array( 'post_type'=>'page', 'post_status'=>'draft', 'post_title'=>__( 'Untitled Builder Page', 'law-temple-core' ), 'post_content'=>'' ), true );
    if ( is_wp_error( $id ) ) { wp_die( esc_html( $id->get_error_message() ) ); }
    update_post_meta( $id, 'lt_page_layout', 'builder' );
    update_post_meta( $id, 'lt_page_hero_layout', 'none' );
    wp_safe_redirect( get_edit_post_link( $id, 'raw' ) ); exit;
}
add_action( 'admin_post_lt_create_builder_page', 'lt_core_create_builder_page' );
