<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }
function lt_core_admin_menu(){
    add_menu_page(__('Law Firm','law-temple-core'),__('Law Firm','law-temple-core'),'lt_access_firm_dashboard','lt-core-dashboard','lt_core_dashboard_page','dashicons-building',24);
    add_submenu_page('lt-core-dashboard',__('Dashboard','law-temple-core'),__('Dashboard','law-temple-core'),'lt_access_firm_dashboard','lt-core-dashboard','lt_core_dashboard_page');
    add_submenu_page('lt-core-dashboard',__('Firm Settings','law-temple-core'),__('Firm Settings','law-temple-core'),'lt_manage_firm_settings','lt-core-settings','lt_core_render_settings_page');
    add_submenu_page('lt-core-dashboard',__('Hero Manager','law-temple-core'),__('Hero Manager','law-temple-core'),'edit_lt_hero_slides','lt-hero-manager','lt_core_hero_manager_page');
    add_submenu_page('lt-core-dashboard',__('Setup & Migration','law-temple-core'),__('Setup & Migration','law-temple-core'),'lt_run_setup','lt-core-setup','lt_core_setup_page');
}
function lt_core_admin_assets($hook){
    $screen=get_current_screen();
    $types=array_keys(lt_core_meta_schema());
    $is_framework=str_contains((string)$hook,'lt-')||($screen&&in_array($screen->post_type,$types,true));
    if(!$is_framework)return;
    wp_enqueue_media();
    wp_enqueue_style('lt-core-admin',LT_CORE_URL.'assets/admin/admin.css',array(),LT_CORE_VERSION);
    wp_enqueue_script('lt-core-admin',LT_CORE_URL.'assets/admin/admin.js',array(),LT_CORE_VERSION,true);
    wp_localize_script('lt-core-admin','ltCoreAdmin',array(
        'ajaxUrl'=>admin_url('admin-ajax.php'),
        'relationNonce'=>wp_create_nonce('lt_relation_search'),
        'relationError'=>__('Unable to search relationships.','law-temple-core'),
        'noResults'=>__('No matching records found.','law-temple-core')
    ));
}
function lt_core_dashboard_page(){
    if(!lt_core_current_user_can('lt_access_firm_dashboard'))return;
    $cards=array(
        array(__('People','law-temple-core'),'lawyer'),
        array(__('Practice Areas','law-temple-core'),'practice'),
        array(__('Insights','law-temple-core'),'insight'),
        array(__('Hero Slides','law-temple-core'),'hero_slide'),
        array(__('Offices','law-temple-core'),'office'),
        array(__('Representative Matters','law-temple-core'),'matter')
    );
    echo '<div class="wrap"><h1>'.esc_html__('Law Firm','law-temple-core').'</h1><p>'.esc_html__('Manage reusable legal content and firm business data independently from presentation.','law-temple-core').'</p>';
    if(function_exists('lt_theme_options_admin_url')){
        echo '<section class="card" style="max-width:1000px;padding:20px;margin:20px 0;border-left:4px solid #bb8031"><div style="display:flex;justify-content:space-between;gap:20px;align-items:center;flex-wrap:wrap"><div><h2 style="margin:0 0 5px">'.esc_html__('Presentation & page building','law-temple-core').'</h2><p style="margin:0;max-width:720px">'.esc_html__('Use Theme Options for global presentation and Page Builder for drag-and-drop internal pages built with native WordPress blocks and Law Firm content blocks.','law-temple-core').'</p></div><div style="display:flex;gap:8px;flex-wrap:wrap"><a class="button" href="'.esc_url(admin_url('admin.php?page=lt-page-builder')).'">'.esc_html__('Open Page Builder','law-temple-core').'</a><a class="button button-primary" href="'.esc_url(lt_theme_options_admin_url('overview')).'">'.esc_html__('Open Theme Options','law-temple-core').'</a></div></div></section>';
    }
    echo '<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px;max-width:1000px">';
    foreach($cards as $c){$obj=get_post_type_object($c[1]);if(!$obj||!current_user_can($obj->cap->edit_posts))continue;$count=wp_count_posts($c[1]);echo '<a class="card" style="text-decoration:none;padding:18px" href="'.esc_url(admin_url('edit.php?post_type='.$c[1])).'"><strong>'.esc_html($c[0]).'</strong><br><span style="font-size:28px">'.esc_html($count->publish??0).'</span> '.esc_html__('published','law-temple-core').'</a>';}
    echo '</div></div>';
}
function lt_core_hero_manager_page(){
    if(!current_user_can('edit_lt_hero_slides')&&!current_user_can('manage_options'))return;
    if(isset($_POST['lt_save_hero_order'])){
        check_admin_referer('lt_hero_order','lt_hero_order_nonce');
        $ids=isset($_POST['hero_ids'])?lt_core_csv_ids(wp_unslash($_POST['hero_ids'])):array();
        foreach($ids as $i=>$id){if('hero_slide'===get_post_type($id)&&current_user_can('edit_post',$id))wp_update_post(array('ID'=>$id,'menu_order'=>$i));}
        echo '<div class="notice notice-success is-dismissible"><p>'.esc_html__('Hero order saved.','law-temple-core').'</p></div>';
    }
    $slides=get_posts(array('post_type'=>'hero_slide','post_status'=>array('publish','draft','private'),'posts_per_page'=>-1,'orderby'=>'menu_order date','order'=>'ASC'));
    echo '<div class="wrap lt-hero-manager"><div class="lt-admin-page-head"><div><h1>'.esc_html__('Hero Manager','law-temple-core').'</h1><p>'.esc_html__('Create, preview, duplicate, enable, schedule and reorder hero slides. Each slide retains independent desktop/mobile imagery and presentation settings.','law-temple-core').'</p></div><div style="display:flex;gap:8px;flex-wrap:wrap">';
    if(function_exists('lt_theme_options_admin_url'))echo '<a class="button" href="'.esc_url(lt_theme_options_admin_url('hero')).'">'.esc_html__('Global Hero Settings','law-temple-core').'</a>';
    echo '<a class="button button-primary" href="'.esc_url(admin_url('post-new.php?post_type=hero_slide')).'">'.esc_html__('Add Hero Slide','law-temple-core').'</a></div></div><form method="post">';
    wp_nonce_field('lt_hero_order','lt_hero_order_nonce');
    echo '<div class="lt-sortable-list lt-hero-card-grid">';
    foreach($slides as $slide){
        $layout=get_post_meta($slide->ID,'lt_hero_layout',true)?:'split';
        $enabled=(bool)get_post_meta($slide->ID,'lt_enabled',true);
        $start=get_post_meta($slide->ID,'lt_start_date',true);$end=get_post_meta($slide->ID,'lt_end_date',true);
        $eyebrow=get_post_meta($slide->ID,'lt_eyebrow',true);$heading=get_post_meta($slide->ID,'lt_heading',true)?:$slide->post_title;
        $thumb=get_the_post_thumbnail($slide->ID,'medium_large',array('class'=>'lt-hero-card-image'));
        $dup=wp_nonce_url(admin_url('admin-post.php?action=lt_duplicate_hero&slide='.$slide->ID),'lt_duplicate_hero_'.$slide->ID);
        $toggle=wp_nonce_url(admin_url('admin-post.php?action=lt_toggle_hero&slide='.$slide->ID),'lt_toggle_hero_'.$slide->ID);
        echo '<article class="lt-sortable-item lt-hero-card" draggable="true">';
        echo '<div class="lt-hero-card-handle"><span class="dashicons dashicons-move" aria-hidden="true"></span><span class="screen-reader-text">'.esc_html__('Drag to reorder','law-temple-core').'</span></div>';
        echo '<div class="lt-hero-card-media">'.($thumb?:'<div class="lt-hero-card-placeholder"><span class="dashicons dashicons-format-image"></span></div>').'</div>';
        echo '<div class="lt-hero-card-body"><div class="lt-hero-card-badges"><span>'.esc_html($layout).'</span><span class="'.($enabled?'is-enabled':'is-disabled').'">'.esc_html($enabled?__('Enabled','law-temple-core'):__('Disabled','law-temple-core')).'</span><span>'.esc_html(ucfirst($slide->post_status)).'</span></div>';
        if($eyebrow)echo '<div class="lt-hero-card-eyebrow">'.esc_html($eyebrow).'</div>';
        echo '<h2>'.esc_html($heading).'</h2><p class="description">'.esc_html(wp_trim_words($slide->post_excerpt,18)).'</p>';
        if($start||$end)echo '<p class="lt-hero-card-schedule">'.esc_html(trim(sprintf(__('Schedule: %1$s to %2$s','law-temple-core'),$start?:__('now','law-temple-core'),$end?:__('open','law-temple-core')))).'</p>';
        echo '<div class="lt-hero-card-actions"><a class="button button-primary button-small" href="'.esc_url(get_edit_post_link($slide)).'">'.esc_html__('Edit / Preview','law-temple-core').'</a><a class="button button-small" href="'.esc_url($dup).'">'.esc_html__('Duplicate','law-temple-core').'</a><a class="button button-small" href="'.esc_url($toggle).'">'.esc_html($enabled?__('Disable','law-temple-core'):__('Enable','law-temple-core')).'</a></div></div><input type="hidden" name="hero_ids[]" value="'.esc_attr($slide->ID).'"></article>';
    }
    echo '</div>';
    if($slides)submit_button(__('Save hero order','law-temple-core'),'primary','lt_save_hero_order');else echo '<div class="lt-empty-state"><h2>'.esc_html__('No hero slides yet','law-temple-core').'</h2><p>'.esc_html__('Add a slide to start building the homepage hero.','law-temple-core').'</p></div>';
    echo '</form></div>';
}
function lt_core_setup_page(){
    if(!lt_core_current_user_can('lt_run_setup'))return;

    if(isset($_POST['lt_run_setup'])){
        check_admin_referer('lt_run_setup','lt_setup_nonce');
        $demo=!empty($_POST['include_demo']);
        $result=lt_core_run_setup($demo);
        if(is_wp_error($result)){
            echo '<div class="notice notice-error"><p>'.esc_html($result->get_error_message()).'</p></div>';
        }else{
            echo '<div class="notice notice-success is-dismissible"><p>'.esc_html__('Safe setup completed. Existing matching content was not overwritten.','law-temple-core').'</p></div>';
        }
    }

    if(isset($_POST['lt_install_full_demo'])){
        check_admin_referer('lt_install_full_demo','lt_full_demo_nonce');
        if(empty($_POST['confirm_full_demo'])){
            echo '<div class="notice notice-error"><p>'.esc_html__('Confirm that you understand the demo import behaviour before continuing.','law-temple-core').'</p></div>';
        }else{
            $report=lt_core_install_full_law_temple_demo();
            if(is_wp_error($report)){
                echo '<div class="notice notice-error"><p>'.esc_html($report->get_error_message()).'</p></div>';
            }else{
                $created=count((array)($report['created']??array()));
                $skipped=count((array)($report['skipped']??array()));
                $errors=count((array)($report['errors']??array()));
                echo '<div class="notice notice-success is-dismissible"><p>'.esc_html(sprintf(__('Full Law Temple demo import finished. Created: %1$d · Existing/skipped: %2$d · Errors: %3$d','law-temple-core'),$created,$skipped,$errors)).'</p></div>';
                if($errors){
                    echo '<div class="notice notice-warning"><p>'.esc_html__('Review the latest demo import report before relying on the imported configuration.','law-temple-core').'</p></div>';
                }
            }
        }
    }

    $summary=lt_core_demo_summary();
    echo '<div class="wrap lt-core-setup"><h1>'.esc_html__('Setup, Migration & Demo Content','law-temple-core').'</h1>';
    echo '<p class="description">'.esc_html__('Use safe setup for a generic law-firm installation. Use the full Law Temple demo only when you want the supplied Law Temple identity and demonstration content. Existing posts with matching slugs are left in place.','law-temple-core').'</p>';

    echo '<div class="lt-admin-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:20px;max-width:1180px;margin-top:24px">';

    echo '<section class="card" style="padding:22px;max-width:none"><h2>'.esc_html__('1. Safe framework setup','law-temple-core').'</h2>';
    echo '<p>'.esc_html__('Creates missing essential pages, preserves existing v2 content and URLs, and can optionally add a very small starter dataset as drafts.','law-temple-core').'</p>';
    echo '<form method="post">';wp_nonce_field('lt_run_setup','lt_setup_nonce');
    echo '<p><label><input type="checkbox" name="include_demo" value="1"> '.esc_html__('Add minimal starter professionals, practices, sectors and one draft hero','law-temple-core').'</label></p>';
    echo '<p><button class="button button-primary" name="lt_run_setup" value="1">'.esc_html__('Run safe setup','law-temple-core').'</button></p></form></section>';

    echo '<section class="card" style="padding:22px;max-width:none"><h2>'.esc_html__('2. Full Law Temple demo','law-temple-core').'</h2>';
    echo '<p>'.esc_html__('Imports the supplied Law Temple brand assets and a complete demonstration site configuration. Publicly supportable firm/profile/practice information is published. Illustrative matters, testimonials, awards, careers, Insights and legal/editorial examples remain drafts until the firm reviews them.','law-temple-core').'</p>';
    if($summary){
        $labels=array('pages'=>__('Pages','law-temple-core'),'sectors'=>__('Sectors','law-temple-core'),'practices'=>__('Practice Areas','law-temple-core'),'offices'=>__('Offices','law-temple-core'),'lawyers'=>__('People','law-temple-core'),'hero_slides'=>__('Hero Slides','law-temple-core'),'faqs'=>__('FAQs','law-temple-core'),'ctas'=>__('CTAs','law-temple-core'),'insights'=>__('Insights','law-temple-core'),'matters'=>__('Matters','law-temple-core'),'testimonials'=>__('Testimonials','law-temple-core'),'awards'=>__('Awards','law-temple-core'),'careers'=>__('Careers','law-temple-core'));
        echo '<div style="display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px 14px;margin:18px 0">';
        foreach($labels as $key=>$label){if(isset($summary[$key]))echo '<div><strong>'.esc_html((string)$summary[$key]).'</strong> '.esc_html($label).'</div>';}
        echo '</div>';
    }
    echo '<ul style="list-style:disc;padding-left:20px"><li>'.esc_html__('Imports the Law Temple logo, favicon and four supplied lawyer portraits into the Media Library.','law-temple-core').'</li><li>'.esc_html__('Creates the Law Temple homepage configuration, navigation, hero slides, seven Practice Areas and ten Sector terms.','law-temple-core').'</li><li>'.esc_html__('Does not overwrite an existing post that already uses the same slug.','law-temple-core').'</li><li>'.esc_html__('Demo records that could imply client outcomes, endorsements, awards or professional credentials are kept as drafts.','law-temple-core').'</li></ul>';
    echo '<form method="post">';wp_nonce_field('lt_install_full_demo','lt_full_demo_nonce');
    echo '<p><label><input type="checkbox" name="confirm_full_demo" value="1" required> <strong>'.esc_html__('I understand that this imports Law Temple demonstration content and that draft legal/professional claims must be reviewed before publication.','law-temple-core').'</strong></label></p>';
    echo '<p><button class="button button-primary" name="lt_install_full_demo" value="1">'.esc_html__('Install full Law Temple demo','law-temple-core').'</button></p></form></section>';

    echo '</div>';

    $last=get_option('lt_core_demo_last_import');$last_report=get_option('lt_core_demo_import_report');
    if($last){
        echo '<section class="card" style="padding:22px;max-width:1180px;margin-top:20px"><h2>'.esc_html__('Latest full-demo import','law-temple-core').'</h2><p>'.esc_html(sprintf(__('Last run: %s','law-temple-core'),$last)).'</p>';
        if(is_array($last_report))echo '<p>'.esc_html(sprintf(__('Created: %1$d · Skipped: %2$d · Errors: %3$d','law-temple-core'),count((array)($last_report['created']??array())),count((array)($last_report['skipped']??array())),count((array)($last_report['errors']??array())))).'</p>';
        echo '</section>';
    }
    echo '</div>';
}
