<?php
/**
 * Plugin Name: MBSM Static HTML Export
 * Plugin URI: https://www.mbsmpro.com/
 * Description: Version 2.1.3: Restored Tags, Related Posts, Recent 50, Bulk Tools, Table Fix, Single Page Export, and PDF Embedder.
 * Version: 2.1.3
 * Author: MBSM Group
 * Author URI: https://www.mbsmgroup.tn/
 * License: GPLv2 or later
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/*
 * =========================================================
 * CONSTANTS & SETTINGS
 * =========================================================
 */

define( 'MBSM_SH_SLUG', 'mbsm-static-html' );
define( 'MBSM_SH_OPTION_KEY', 'mbsm_static_html_options' );

add_action( 'admin_init', 'mbsm_sh_register_settings' );
function mbsm_sh_register_settings() {
    register_setting( MBSM_SH_OPTION_KEY . '_group', MBSM_SH_OPTION_KEY, 'mbsm_sh_sanitize_options' );
}

function mbsm_sh_get_default_options() {
    return array(
        'enabled'        => 1,
        'file_prefix'    => 'mbsmpro-',
        'folder_url'     => home_url('/html/'),
        'htm_menu_links' => "Home|/\nBlog|/blog/\nContact|/contact/",
        'adsense_code'   => '',
        'htm_custom_css' => '',
    );
}

function mbsm_sh_get_options() {
    $defaults = mbsm_sh_get_default_options();
    $options  = get_option( MBSM_SH_OPTION_KEY, array() );
    return wp_parse_args( $options, $defaults );
}

function mbsm_sh_sanitize_options( $input ) {
    $output = array();
    $input = is_array( $input ) ? $input : array();
    $output['enabled']        = isset( $input['enabled'] ) ? 1 : 0;
    $output['file_prefix']    = sanitize_text_field( $input['file_prefix'] );
    $output['folder_url']     = esc_url_raw( trailingslashit( trim( $input['folder_url'] ) ) );
    $output['htm_menu_links'] = sanitize_textarea_field( $input['htm_menu_links'] );
    $output['adsense_code']   = $input['adsense_code']; 
    $output['htm_custom_css'] = wp_strip_all_tags( $input['htm_custom_css'] );
    return $output;
}

/*
 * =========================================================
 * ADMIN SETTINGS & BULK INTERFACE
 * =========================================================
 */

add_action( 'admin_menu', 'mbsm_sh_add_menus' );
function mbsm_sh_add_menus() {
    add_menu_page( 'Mbsmpro Html', 'Mbsmpro Html', 'manage_options', MBSM_SH_SLUG, 'mbsm_sh_settings_page', 'dashicons-media-code', 58 );
}

function mbsm_sh_settings_page() {
    $options    = mbsm_sh_get_options();
    $active_tab = isset( $_GET['tab'] ) ? $_GET['tab'] : 'general';
    
    $message = '';
    if ( isset( $_POST['mbsm_bulk_generate'] ) && check_admin_referer( 'mbsm_bulk_action', 'mbsm_bulk_nonce' ) ) {
        if ( ! empty( $_POST['post_ids'] ) ) {
            $count = 0;
            foreach ( $_POST['post_ids'] as $post_id ) {
                $post = get_post( $post_id );
                if ( $post ) {
                    mbsm_sh_generate_files( $post_id, $post, $options );
                    $count++;
                }
            }
            $message = '<div class="updated"><p>Successfully generated ' . intval( $count ) . ' static pages.</p></div>';
        }
    }

    ?>
    <div class="wrap">
        <h1>Mbsmpro Static Tools - V 2.1.3</h1>
        <?php echo $message; ?>

        <h2 class="nav-tab-wrapper">
            <a href="?page=<?php echo esc_attr( MBSM_SH_SLUG ); ?>&tab=general" class="nav-tab <?php echo $active_tab == 'general' ? 'nav-tab-active' : ''; ?>">General Settings</a>
            <a href="?page=<?php echo esc_attr( MBSM_SH_SLUG ); ?>&tab=bulk" class="nav-tab <?php echo $active_tab == 'bulk' ? 'nav-tab-active' : ''; ?>">Bulk Export</a>
        </h2>

        <?php if ( $active_tab == 'general' ) : ?>
            <form method="post" action="options.php">
                <?php settings_fields( MBSM_SH_OPTION_KEY . '_group' ); ?>
                <table class="form-table">
                    <tr>
                        <th scope="row">Enable Plugin Logic</th>
                        <td><input type="checkbox" name="<?php echo esc_attr( MBSM_SH_OPTION_KEY ); ?>[enabled]" value="1" <?php checked( $options['enabled'], 1 ); ?> /></td>
                    </tr>
                    <tr>
                        <th scope="row">File Prefix</th>
                        <td><input type="text" name="<?php echo esc_attr( MBSM_SH_OPTION_KEY ); ?>[file_prefix]" value="<?php echo esc_attr( $options['file_prefix'] ); ?>" class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th scope="row">Folder URL</th>
                        <td><input type="text" name="<?php echo esc_attr( MBSM_SH_OPTION_KEY ); ?>[folder_url]" value="<?php echo esc_attr( $options['folder_url'] ); ?>" class="regular-text" /></td>
                    </tr>
                    <tr>
                        <th scope="row">Scripts (AdSense/Header)</th>
                        <td><textarea name="<?php echo esc_attr( MBSM_SH_OPTION_KEY ); ?>[adsense_code]" rows="6" class="large-text"><?php echo esc_textarea( $options['adsense_code'] ); ?></textarea></td>
                    </tr>
                    <tr>
                        <th scope="row">Custom CSS</th>
                        <td><textarea name="<?php echo esc_attr( MBSM_SH_OPTION_KEY ); ?>[htm_custom_css]" rows="5" class="large-text"><?php echo esc_textarea( $options['htm_custom_css'] ); ?></textarea></td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>

        <?php else : ?>
            <form method="post">
                <?php wp_nonce_field( 'mbsm_bulk_action', 'mbsm_bulk_nonce' ); ?>
                <div style="margin: 20px 0;">
                    <input type="submit" name="mbsm_bulk_generate" class="button button-primary" value="Generate Selected Pages">
                </div>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <td class="manage-column column-cb check-column"><input id="cb-select-all-1" type="checkbox"></td>
                            <th>Post Title</th>
                            <th>Status</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $posts = get_posts( array( 'numberposts' => -1, 'post_status' => 'publish' ) );
                        $dir   = ABSPATH . 'html/';
                        foreach ( $posts as $p ) {
                            $file_name = $options['file_prefix'] . $p->post_name . '.htm';
                            $exists    = file_exists( $dir . $file_name );
                            ?>
                            <tr>
                                <th scope="row" class="check-column"><input type="checkbox" name="post_ids[]" value="<?php echo esc_attr( $p->ID ); ?>"></th>
                                <td><strong><?php echo esc_html( $p->post_title ); ?></strong></td>
                                <td><?php echo $exists ? '<span style="color:green; font-weight:bold;">✅ Online</span>' : '<span style="color:#ccc;">❌ Missing</span>'; ?></td>
                                <td><?php echo esc_html( get_the_date( '', $p->ID ) ); ?></td>
                            </tr>
                            <?php
                        }
                        ?>
                    </tbody>
                </table>
            </form>
            <script>
                jQuery('#cb-select-all-1').on('click', function() {
                    jQuery('input[name="post_ids[]"]').prop('checked', this.checked);
                });
            </script>
        <?php endif; ?>
    </div>
    <?php
}

/*
 * =========================================================
 * POST EDIT METABOX (SIDEBAR LINKS)
 * =========================================================
 */

add_action( 'add_meta_boxes', function() {
    add_meta_box( 'mbsm_static_html_box', 'Static HTML Export', 'mbsm_sh_metabox_cb', 'post', 'side' );
});

function mbsm_sh_metabox_cb( $post ) {
    $options   = mbsm_sh_get_options();
    $dir_url   = trailingslashit( $options['folder_url'] );
    $file_base = $options['file_prefix'] . $post->post_name;
    
    if ( $post->post_status === 'publish' ) {
        echo '<div style="background:#f9f9f9; padding:10px; border:1px solid #ddd; border-radius:4px;">';
        echo '<p style="margin-top:0;"><strong>Live Static Links:</strong></p>';
        echo '<p>📄 <a href="' . esc_url( $dir_url . $file_base . '.html' ) . '" target="_blank">Full HTML</a></p>';
        echo '<p>📄 <a href="' . esc_url( $dir_url . $file_base . '.htm' ) . '" target="_blank">Static HTM</a></p>';
        echo '</div>';
    } else {
        echo '<p>Publish post to see links.</p>';
    }
}

/*
 * =========================================================
 * CORE GENERATOR LOGIC
 * =========================================================
 */

add_action( 'save_post', 'mbsm_sh_save_handler', 10, 3 );
function mbsm_sh_save_handler( $post_id, $post, $update ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
    if ( $post->post_status !== 'publish' || $post->post_type !== 'post' ) return;
    $options = mbsm_sh_get_options();
    if ( empty( $options['enabled'] ) ) return;
    mbsm_sh_generate_files( $post_id, $post, $options );
}

function mbsm_sh_generate_files( $post_id, $post, $options ) {
    $dir = ABSPATH . 'html/';
    if ( ! file_exists( $dir ) ) {
        wp_mkdir_p( $dir );
    }

    $slug      = $post->post_name;
    $file_base = $options['file_prefix'] . $slug;

    // 1. Full HTML
    $response = wp_remote_get( get_permalink( $post_id ) );
    if ( ! is_wp_error( $res ) ) {
        file_put_contents( $dir . $file_base . '.html', wp_remote_retrieve_body( $response ) );
    }

    // 2. Static HTM
    $static_content = mbsm_sh_build_static_htm( $post_id, $post, $options );
    file_put_contents( $dir . $file_base . '.htm', $static_content );
}

/*
 * =========================================================
 * STATIC HTM BUILDER (RESTORED & IMPROVED)
 * =========================================================
 */

function mbsm_sh_build_static_htm( $post_id, $post, $options ) {
    $site_url   = get_site_url();
    $post_url   = get_permalink( $post_id ); 
    $site_name  = get_bloginfo( 'name' );
    $site_desc  = get_bloginfo( 'description' );
    $content    = apply_filters( 'the_content', $post->post_content );
    $logo_url   = get_site_icon_url();
    $banner_url = "https://mbsmpro.com/wp-content/themes/Mbsmpro/assets/images/Lorem-Ipsum-is-simply-dummy-1.png";

    // Statistics
    $total_posts = wp_count_posts()->publish;
    $total_cats  = count( get_categories() );

    // Pages Menu
    $pages_menu_html = '<nav class="top-pages-menu">';
    foreach ( get_pages( array( 'number' => 8 ) ) as $page ) {
        $pages_menu_html .= '<a href="' . esc_url( get_permalink( $page->ID ) ) . '" target="_blank">' . esc_html( $page->post_title ) . '</a>';
    }
    $pages_menu_html .= '</nav>';

    // Related Posts
    $related_html = '';
    $categories   = wp_get_post_categories( $post_id );
    if ( $categories ) {
        $related_posts = get_posts( array(
            'category__in'   => $categories,
            'post__not_in'   => array( $post_id ),
            'posts_per_page' => 5,
            'orderby'        => 'rand',
        ) );
        if ( $related_posts ) {
            $related_html .= '<section class="mbsm-related"><h3>You Might Also Like</h3><ul>';
            foreach ( $related_posts as $rp ) {
                $related_html .= '<li><a href="' . esc_url( get_permalink( $rp->ID ) ) . '" target="_blank">' . esc_html( get_the_title( $rp->ID ) ) . '</a></li>';
            }
            $related_html .= '</ul></section>';
        }
    }

    // Categories
    $categories_html = '<section class="mbsm-categories"><h3>Global Categories</h3><div class="category-cloud">';
    foreach ( get_categories( array( 'hide_empty' => 0 ) ) as $cat ) {
        $categories_html .= '<a href="' . esc_url( get_category_link( $cat->term_id ) ) . '" target="_blank" title="View ' . esc_attr( $cat->name ) . '">' . esc_html( $cat->name ) . '</a>';
    }
    $categories_html .= '</div></section>';

    // Tags
    $tags_arr  = get_the_tags( $post_id );
    $tags_html = '';
    if ( $tags_arr ) {
        $tags_html .= '<section class="mbsm-tags"><h3>Topic Tags</h3><div class="tag-cloud">';
        foreach ( $tags_arr as $tag ) {
            $tags_html .= '<a href="' . esc_url( get_tag_link( $tag->term_id ) ) . '" target="_blank">#' . esc_html( $tag->name ) . '</a>';
        }
        $tags_html .= '</div></section>';
    }

    // Recent 50
    $recent_html = '<section class="mbsm-recent"><h3>Latest 50 Technical Guides</h3><ul>';
    foreach ( get_posts( array( 'numberposts' => 50, 'post_status' => 'publish' ) ) as $recent ) {
        $recent_html .= '<li><a href="' . esc_url( get_permalink( $recent->ID ) ) . '" target="_blank">' . esc_html( $recent->post_title ) . '</a></li>';
    }
    $recent_html .= '</ul></section>';

    // Table Fix
    $fixed_content = preg_replace(
        '/<table(.*?)>(.*?)<\/table>/is',
        '<div class="table-responsive"><table$1>$2</table></div>',
        $content
    );

    // PDF Embedder (The core request: open PDF inside the page)
    $fixed_content = preg_replace_callback(
        '/<a[^>]+href=["\']([^"\']+\.pdf)["\'][^>]*>(.*?)<\/a>/is',
        function($matches) {
            $pdf_url = $matches[1];
            $pdf_title = $matches[2];
            return '
            <div class="mbsm-pdf-viewer" style="margin:25px 0; border:1px solid #e1e4e8; border-radius:8px; overflow:hidden; background:#f8fafc;">
                <div style="background:#1e293b; color:#fff; padding:10px 15px; font-size:14px; font-weight:bold; display:flex; justify-content:space-between; align-items:center;">
                    <span>📄 ' . esc_html($pdf_title) . '</span>
                    <a href="' . esc_url($pdf_url) . '" target="_blank" style="color:#fff; background:#e11d48; padding:3px 10px; border-radius:4px; text-decoration:none; font-size:12px;">Full Screen</a>
                </div>
                <iframe src="' . esc_url($pdf_url) . '" width="100%" height="600px" style="border:none;"></iframe>
            </div>';
        },
        $fixed_content
    );

    $out  = '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">';
    $out .= '<meta name="viewport" content="width=device-width, initial-scale=1">';
    $out .= '<title>' . esc_html( $post->post_title ) . '</title>';
    $out .= $options['adsense_code'];
    $out .= '<style>
    *{box-sizing:border-box;}
    html,body{margin:0;padding:0;}
    body{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;line-height:1.7;background:#f4f7f6;color:#1a202c;padding:10px;}
    a{color:#2563eb;text-decoration:none;}
    a:hover{text-decoration:underline;}
    img{max-width:100%;height:auto;}
    .container{max-width:1050px;margin:0 auto;background:#ffffff;padding:30px 24px;border:1px solid #e1e4e8;border-radius:8px;box-shadow:0 1px 2px rgba(15,23,42,.06);}
    .top-pages-menu{background:#111827;padding:10px 8px;text-align:center;border-radius:6px;margin-bottom:18px;overflow-x:auto;white-space:nowrap;}
    .top-pages-menu a{color:#f9fafb;margin:0 10px;font-size:13px;font-weight:500;}
    header img.banner{max-width:100%;border-radius:4px;margin-bottom:18px;}
    .site-identity{display:flex;align-items:center;gap:18px;border-bottom:1px solid #e5e7eb;padding-bottom:20px;margin-bottom:20px;flex-wrap:wrap;}
    .site-logo{width:80px;height:80px;border-radius:14px;object-fit:cover;border:1px solid #e5e7eb;}
    .site-info h1{margin:0 0 4px;font-size:22px;color:#111827;}
    .site-stats{font-size:12px;color:#4b5563;background:#f9fafb;padding:5px 10px;border-radius:999px;border:1px solid #e5e7eb;display:inline-block;}
    .visit-cta{background:#e11d48;color:#fff !important;padding:10px 20px;border-radius:999px;font-weight:600;display:inline-block;margin-top:12px;font-size:14px;}
    .content table{width:100%;border-collapse:collapse;font-size:14px;min-width:480px;}
    .content th, .content td{border:1px solid #e2e8f0;padding:10px;}
    .table-responsive{width:100%;overflow-x:auto;margin:20px 0;}
    .mbsm-related, .mbsm-categories, .mbsm-tags, .mbsm-recent{margin:25px 0;padding:18px;border:1px solid #e5e7eb;border-radius:8px;background:#f9fafb;}
    .category-cloud a, .tag-cloud a{display:inline-block;background:#edf2f7;padding:6px 14px;margin:4px;border-radius:20px;font-size:13px;border:1px solid #cbd5e0;}
    footer{margin-top:35px;text-align:center;color:#718096;font-size:13px;}
    ' . $options['htm_custom_css'] . '
    </style></head><body>';

    $out .= '<div class="container">' . $pages_menu_html;
    $out .= '<header><img src="' . esc_url( $banner_url ) . '" class="banner"><div class="site-identity">';
    if ( $logo_url ) $out .= '<img src="' . esc_url( $logo_url ) . '" class="site-logo">';
    $out .= '<div class="site-info"><h1>' . esc_html( $site_name ) . '</h1><p>' . esc_html( $site_desc ) . '</p>';
    $out .= '<div class="site-stats">📊 Database: ' . intval( $total_posts ) . ' Articles</div><br>';
    $out .= '<a href="' . esc_url( $post_url ) . '" target="_blank" class="visit-cta">🚀 Visit Official Website</a></div></div></header>';
    
    $out .= $related_html . $categories_html;
    $out .= '<article><h2>' . esc_html( $post->post_title ) . '</h2><div class="content">' . $fixed_content . '</div></article>';
    $out .= $tags_html . $recent_html;

    $out .= '<footer>&copy; ' . date( 'Y' ) . ' ' . esc_html( $site_name ) . ' - All Rights Reserved</footer>';
    $out .= '</div></body></html>';

    return $out;
}

/*
 * =========================================================
 * SINGLE POST EXPORT BUTTON
 * =========================================================
 */

add_filter( 'the_content', 'mbsm_sh_append_export_button' );
function mbsm_sh_append_export_button( $content ) {
    if ( is_singular('post') && is_main_query() ) {
        global $post;
        $options = mbsm_sh_get_options();
        if ( ! empty( $options['enabled'] ) ) {
            $file_name = $options['file_prefix'] . $post->post_name . '.htm';
            $static_url = trailingslashit( $options['folder_url'] ) . $file_name;
            $content .= '<div style="text-align:center; padding:20px; border-top:2px dashed #eee; margin-top:30px;">';
            $content .= '<a href="' . esc_url( $static_url ) . '" target="_blank" style="display:inline-block; background:#2563eb; color:#fff; padding:12px 25px; border-radius:6px; text-decoration:none; font-weight:bold;">📂 Open Static HTML (Offline Version)</a>';
            $content .= '</div>';
        }
    }
    return $content;
}