<?php
/**
 * Punto de entrada directo para generar la vista PDF.
 * URL: /wp-content/plugins/wp-post-pdf-printer/pdf-viewer.php?id=424725
 * URL: /wp-content/plugins/wp-post-pdf-printer/pdf-viewer.php?id=424725&print=1
 *
 * Este archivo carga WordPress manualmente y no depende de
 * ninguna regla de reescritura ni del routing de WP.
 */

// ── Seguridad básica ───────────────────────────────────────────────────────
$post_id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
if ( ! $post_id || $post_id <= 0 ) {
    http_response_code( 400 );
    die( '<h2>ID de entrada no válido.</h2>' );
}

// ── Cargar WordPress ───────────────────────────────────────────────────────
// Subimos directorios hasta encontrar wp-load.php
$dir = __DIR__;
$wp_load = '';
for ( $i = 0; $i < 8; $i++ ) {
    $dir = dirname( $dir );
    if ( file_exists( $dir . '/wp-load.php' ) ) {
        $wp_load = $dir . '/wp-load.php';
        break;
    }
}
if ( ! $wp_load ) {
    http_response_code( 500 );
    die( '<h2>No se pudo encontrar WordPress. Verifica la instalación del plugin.</h2>' );
}

// Suprimir output de otros plugins durante la carga
define( 'DOING_AJAX', true ); // evita que algunos temas/plugins hagan output

require_once $wp_load;

// ── Verificar el post ──────────────────────────────────────────────────────
$post = get_post( $post_id );
if ( ! $post || 'publish' !== $post->post_status ) {
    http_response_code( 404 );
    die( '<h2>Entrada no encontrada o no publicada.</h2><p><a href="javascript:history.back()">← Volver</a></p>' );
}

// ── Configuración ──────────────────────────────────────────────────────────
$settings   = get_option( 'wppdf_settings', [] );
$color      = sanitize_hex_color( $settings['primary_color'] ?? '#c0392b' );
$site_name  = esc_html( get_bloginfo( 'name' ) );
$site_url   = esc_url( home_url() );
$logo_url   = esc_url( get_site_icon_url( 64 ) );
$title      = esc_html( $post->post_title );
$permalink  = esc_url( get_permalink( $post->ID ) );
$date_fmt   = get_option( 'date_format' );
$auto_print = isset( $_GET['print'] ) ? 'true' : 'false';
$paper      = esc_html( $settings['paper_size'] ?? 'A4' );

// ── Log ────────────────────────────────────────────────────────────────────
if ( ! empty( $settings['enable_logs'] ) ) {
    global $wpdb;
    $wpdb->insert(
        $wpdb->prefix . 'wppdf_logs',
        [
            'post_id'     => $post_id,
            'user_id'     => get_current_user_id(),
            'user_ip'     => sanitize_text_field( $_SERVER['REMOTE_ADDR'] ?? '' ),
            'action_type' => isset( $_GET['print'] ) ? 'print' : 'download',
            'created_at'  => current_time( 'mysql' ),
        ],
        [ '%d', '%d', '%s', '%s', '%s' ]
    );
}

// ── Meta ───────────────────────────────────────────────────────────────────
$meta_parts = [];
if ( ! empty( $settings['include_author'] ) )
    $meta_parts[] = 'Por ' . esc_html( get_the_author_meta( 'display_name', $post->post_author ) );
if ( ! empty( $settings['include_date'] ) )
    $meta_parts[] = esc_html( get_the_date( $date_fmt, $post ) );
if ( ! empty( $settings['include_categories'] ) ) {
    $cats = get_the_category( $post->ID );
    if ( $cats )
        $meta_parts[] = esc_html( implode( ', ', wp_list_pluck( $cats, 'name' ) ) );
}
$meta_html = $meta_parts
    ? '<p class="meta">' . implode( ' &nbsp;·&nbsp; ', $meta_parts ) . '</p>'
    : '';

// ── Imagen destacada ───────────────────────────────────────────────────────
$featured_html = '';
if ( ! empty( $settings['include_featured'] ) && has_post_thumbnail( $post->ID ) ) {
    $img = get_the_post_thumbnail_url( $post->ID, 'large' );
    if ( $img )
        $featured_html = '<img class="featured" src="' . esc_url( $img ) . '" alt="' . esc_attr( $post->post_title ) . '">';
}

// ── Contenido ──────────────────────────────────────────────────────────────
$content = apply_filters( 'the_content', $post->post_content );
$content = preg_replace( '#<script[^>]*>.*?</script>#is', '', $content );
$content = preg_replace( '#<style[^>]*>.*?</style>#is',   '', $content );
$content = strip_shortcodes( $content );

// ── Watermark ──────────────────────────────────────────────────────────────
$watermark = ( ! empty( $settings['show_watermark'] ) && ! empty( $settings['watermark_text'] ) )
    ? '<div class="watermark">' . esc_html( $settings['watermark_text'] ) . '</div>'
    : '';

// ── Output HTML ────────────────────────────────────────────────────────────
nocache_headers();
header( 'Content-Type: text/html; charset=UTF-8' );
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title><?php echo $title; ?> — <?php echo $site_name; ?></title>
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:Georgia,'Times New Roman',serif;font-size:13pt;color:#111;background:#fff;line-height:1.65}
/* Barra de acciones */
.action-bar{position:fixed;top:0;left:0;right:0;background:<?php echo $color ?>;color:#fff;padding:10px 20px;display:flex;align-items:center;gap:10px;z-index:9999;font-family:Arial,sans-serif;font-size:13px;box-shadow:0 2px 6px rgba(0,0,0,.3)}
.action-bar strong{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.action-bar button{background:rgba(255,255,255,.2);color:#fff;border:1px solid rgba(255,255,255,.5);padding:7px 16px;border-radius:4px;cursor:pointer;font-size:13px;font-weight:700;display:flex;align-items:center;gap:6px}
.action-bar button:hover{background:rgba(255,255,255,.35)}
.action-bar a.back{color:rgba(255,255,255,.85);text-decoration:none;font-size:12px;white-space:nowrap}
.action-bar a.back:hover{color:#fff}
/* Contenido */
.page-wrap{max-width:760px;margin:0 auto;padding:80px 40px 48px;position:relative}
.site-header{display:flex;align-items:center;gap:10px;padding-bottom:12px;border-bottom:3px solid <?php echo $color ?>;margin-bottom:22px}
.site-name{font-family:Arial,sans-serif;font-size:17pt;font-weight:700;color:<?php echo $color ?>;text-decoration:none}
h1.post-title{font-family:Arial,sans-serif;font-size:22pt;font-weight:700;color:#111;line-height:1.25;margin-bottom:10px}
.meta{font-family:Arial,sans-serif;font-size:9.5pt;color:#666;margin-bottom:16px;border-left:3px solid <?php echo $color ?>;padding-left:10px}
img.featured{width:100%;height:auto;max-height:380px;object-fit:cover;display:block;margin-bottom:22px;border-radius:3px}
.post-content{font-size:12.5pt;line-height:1.7}
.post-content p{margin-bottom:14px}
.post-content h2,.post-content h3,.post-content h4{font-family:Arial,sans-serif;color:<?php echo $color ?>;margin:20px 0 8px}
.post-content img{max-width:100%;height:auto;display:block;margin:14px auto}
.post-content a{color:<?php echo $color ?>;word-break:break-all}
.post-content blockquote{border-left:4px solid <?php echo $color ?>;padding:8px 16px;margin:14px 0;background:#f7f7f7;color:#444;font-style:italic}
.post-content table{width:100%;border-collapse:collapse;margin:14px 0}
.post-content th,.post-content td{border:1px solid #ddd;padding:6px 10px}
.post-content th{background:<?php echo $color ?>;color:#fff}
.post-footer{margin-top:28px;padding-top:12px;border-top:1px solid #ddd;font-family:Arial,sans-serif;font-size:8.5pt;color:#999}
.post-footer a{color:#999}
.watermark{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) rotate(-35deg);font-size:56pt;font-family:Arial,sans-serif;font-weight:700;color:rgba(0,0,0,.05);white-space:nowrap;pointer-events:none;z-index:0;user-select:none}
/* Print */
@media print{
    .action-bar{display:none!important}
    .page-wrap{padding-top:32px!important}
    .watermark{position:fixed!important}
    @page{size:<?php echo $paper ?> portrait;margin:15mm 15mm 20mm}
    h1.post-title{page-break-after:avoid}
    .post-content p{orphans:3;widows:3}
    img.featured{max-height:260px}
}
</style>
</head>
<body>

<div class="action-bar">
    <strong><?php echo $title; ?></strong>
    <a class="back" href="<?php echo $permalink; ?>">← Volver al artículo</a>
    <button onclick="window.print()">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M19 8H5c-1.66 0-3 1.34-3 3v6h4v4h12v-4h4v-6c0-1.66-1.34-3-3-3zm-3 11H8v-5h8v5zm3-7c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm-1-9H6v4h12V3z"/></svg>
        Imprimir / Guardar PDF
    </button>
</div>

<?php echo $watermark; ?>

<div class="page-wrap">
    <div class="site-header">
        <?php if ( $logo_url ) echo '<img src="' . $logo_url . '" alt="" style="height:36px;width:auto;">'; ?>
        <a class="site-name" href="<?php echo $site_url; ?>"><?php echo $site_name; ?></a>
    </div>

    <h1 class="post-title"><?php echo $title; ?></h1>
    <?php echo $meta_html; ?>
    <?php echo $featured_html; ?>

    <div class="post-content">
        <?php echo $content; ?>
    </div>

    <div class="post-footer">
        Fuente: <a href="<?php echo $permalink; ?>"><?php echo $permalink; ?></a>
        &nbsp;·&nbsp; <?php echo $site_name; ?> &nbsp;·&nbsp; <?php echo date_i18n( $date_fmt ); ?>
    </div>
</div>

<script>
if ( <?php echo $auto_print; ?> ) {
    window.addEventListener('load', function() {
        setTimeout(function(){ window.print(); }, 700);
    });
}
</script>
</body>
</html>
<?php
// Fin — no hay más código
