<?php
/**
 * Copyright (C) 2026 Plugixa (https://plugixa.com)
 * License: GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.txt
 */

/**
 * Print Template
 *
 * Print-optimized full-page recipe layout. No navigation, no ads,
 * clean typography with @media print optimizations.
 *
 * Available variables:
 * @var object $recipe          Full recipe object with all fields
 * @var array  $view_config     Decoded JSON view configuration
 *
 * @package PlugixaRecipe
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- template-scope render variables, not global-namespace pollution.

$title              = isset( $recipe->title ) ? $recipe->title : '';
$description        = isset( $recipe->description ) ? $recipe->description : '';
$image_url          = isset( $recipe->image_url ) ? $recipe->image_url : '';
$author_name        = isset( $recipe->author_name ) ? $recipe->author_name : '';
$source_url         = isset( $recipe->permalink ) ? $recipe->permalink : '';
$prep_time          = isset( $recipe->prep_time ) ? absint( $recipe->prep_time ) : 0;
$cook_time          = isset( $recipe->cook_time ) ? absint( $recipe->cook_time ) : 0;
$total_time         = $prep_time + $cook_time;
$servings           = isset( $recipe->servings ) ? absint( $recipe->servings ) : 0;
$difficulty         = isset( $recipe->difficulty ) ? $recipe->difficulty : '';
$cuisine            = isset( $recipe->cuisine ) ? $recipe->cuisine : '';
$ingredient_groups  = isset( $recipe->ingredient_groups ) && is_array( $recipe->ingredient_groups ) ? $recipe->ingredient_groups : array();
$instruction_groups = isset( $recipe->instruction_groups ) && is_array( $recipe->instruction_groups ) ? $recipe->instruction_groups : array();
$nutrition          = isset( $recipe->nutrition ) ? $recipe->nutrition : null;
$site_name          = get_bloginfo( 'name' );
$site_url           = home_url( '/' );

if ( ! function_exists( 'pxr_format_time' ) ) {
    function pxr_format_time( $minutes ) {
        if ( $minutes < 60 ) {
            /* translators: %d: number of minutes. */
            return sprintf( _n( '%d min', '%d mins', $minutes, 'plugixarecipe' ), $minutes );
        }
        $hours = floor( $minutes / 60 );
        $mins  = $minutes % 60;
        if ( $mins === 0 ) {
            /* translators: %d: number of hours. */
            return sprintf( _n( '%d hr', '%d hrs', $hours, 'plugixarecipe' ), $hours );
        }
        /* translators: 1: number of hours, 2: number of minutes. */
        return sprintf( __( '%1$d hr %2$d min', 'plugixarecipe' ), $hours, $mins );
    }
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="robots" content="noindex, nofollow" />
    <title><?php echo esc_html( $title ); ?> - <?php esc_html_e( 'Print', 'plugixarecipe' ); ?></title>
    <style>
        /* Reset & Base */
        *, *::before, *::after {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: Georgia, 'Times New Roman', Times, serif;
            font-size: 14px;
            line-height: 1.6;
            color: #1a1a1a;
            background: #fff;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        h1 {
            font-size: 28px;
            line-height: 1.2;
            margin-bottom: 8px;
        }

        h2 {
            font-size: 20px;
            margin-top: 24px;
            margin-bottom: 12px;
            padding-bottom: 6px;
            border-bottom: 2px solid #333;
        }

        h3 {
            font-size: 16px;
            margin-top: 16px;
            margin-bottom: 8px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #555;
        }

        .pxr-print-header {
            border-bottom: 3px solid #000;
            padding-bottom: 16px;
            margin-bottom: 20px;
        }

        .pxr-print-description {
            font-style: italic;
            color: #444;
            margin-bottom: 12px;
        }

        .pxr-print-meta {
            display: flex;
            flex-wrap: wrap;
            gap: 24px;
            margin-bottom: 8px;
            font-size: 13px;
        }

        .pxr-print-meta dt {
            font-weight: bold;
            display: inline;
        }

        .pxr-print-meta dd {
            display: inline;
            margin-left: 4px;
        }

        .pxr-print-meta-item {
            display: flex;
            gap: 4px;
        }

        .pxr-print-image {
            max-width: 100%;
            height: auto;
            border-radius: 4px;
            margin-bottom: 16px;
        }

        .pxr-print-ingredients ul {
            list-style: disc;
            padding-left: 24px;
        }

        .pxr-print-ingredients li {
            margin-bottom: 4px;
        }

        .pxr-print-instructions ol {
            padding-left: 24px;
        }

        .pxr-print-instructions li {
            margin-bottom: 12px;
            padding-left: 4px;
        }

        /* Nutrition Table */
        .pxr-print-nutrition-table {
            width: 100%;
            max-width: 400px;
            border-collapse: collapse;
            margin-top: 8px;
            font-size: 13px;
        }

        .pxr-print-nutrition-table th,
        .pxr-print-nutrition-table td {
            text-align: left;
            padding: 4px 8px;
            border-bottom: 1px solid #ddd;
        }

        .pxr-print-nutrition-table th {
            font-weight: bold;
            background: #f5f5f5;
        }

        .pxr-print-nutrition-table td:last-child {
            text-align: right;
        }

        /* Footer */
        .pxr-print-footer {
            margin-top: 32px;
            padding-top: 12px;
            border-top: 1px solid #ccc;
            font-size: 11px;
            color: #888;
            text-align: center;
        }

        /* Print button (hidden when printing) */
        .pxr-print-action {
            text-align: center;
            margin-bottom: 24px;
        }

        .pxr-print-action button {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            font-size: 14px;
            font-weight: 600;
            padding: 10px 32px;
            border: 2px solid #333;
            background: #fff;
            cursor: pointer;
            border-radius: 4px;
            transition: background 0.2s;
        }

        .pxr-print-action button:hover {
            background: #f5f5f5;
        }

        /* Print-specific styles */
        @media print {
            body {
                padding: 0;
                font-size: 12px;
            }

            .pxr-print-action {
                display: none !important;
            }

            .pxr-print-image {
                max-width: 50%;
            }

            h1 {
                font-size: 24px;
            }

            h2 {
                font-size: 18px;
                margin-top: 18px;
                page-break-after: avoid;
            }

            h3 {
                page-break-after: avoid;
            }

            .pxr-print-ingredients,
            .pxr-print-instructions {
                page-break-inside: avoid;
            }

            .pxr-print-instructions li {
                page-break-inside: avoid;
            }

            a {
                color: inherit;
                text-decoration: none;
            }

            .pxr-print-footer a::after {
                content: " (" attr(href) ")";
            }
        }
    </style>
</head>
<body>

    <!-- Print Button -->
    <div class="pxr-print-action">
        <button type="button" onclick="window.print();" aria-label="<?php esc_attr_e( 'Print this recipe', 'plugixarecipe' ); ?>">
            <?php esc_html_e( 'Print Recipe', 'plugixarecipe' ); ?>
        </button>
    </div>

    <!-- Header -->
    <header class="pxr-print-header">
        <h1><?php echo esc_html( $title ); ?></h1>

        <?php if ( $description ) : ?>
            <p class="pxr-print-description"><?php echo esc_html( wp_strip_all_tags( $description ) ); ?></p>
        <?php endif; ?>

        <?php if ( $author_name ) : ?>
            <p style="font-size: 13px; color: #666;">
                <?php
                /* translators: %s: author name */
                echo esc_html( sprintf( __( 'By %s', 'plugixarecipe' ), $author_name ) );
                ?>
            </p>
        <?php endif; ?>

        <!-- Meta -->
        <div class="pxr-print-meta" style="margin-top: 12px;">
            <?php if ( $prep_time ) : ?>
                <div class="pxr-print-meta-item">
                    <dt><?php esc_html_e( 'Prep:', 'plugixarecipe' ); ?></dt>
                    <dd><?php echo esc_html( pxr_format_time( $prep_time ) ); ?></dd>
                </div>
            <?php endif; ?>

            <?php if ( $cook_time ) : ?>
                <div class="pxr-print-meta-item">
                    <dt><?php esc_html_e( 'Cook:', 'plugixarecipe' ); ?></dt>
                    <dd><?php echo esc_html( pxr_format_time( $cook_time ) ); ?></dd>
                </div>
            <?php endif; ?>

            <?php if ( $total_time ) : ?>
                <div class="pxr-print-meta-item">
                    <dt><?php esc_html_e( 'Total:', 'plugixarecipe' ); ?></dt>
                    <dd><?php echo esc_html( pxr_format_time( $total_time ) ); ?></dd>
                </div>
            <?php endif; ?>

            <?php if ( $servings ) : ?>
                <div class="pxr-print-meta-item">
                    <dt><?php esc_html_e( 'Servings:', 'plugixarecipe' ); ?></dt>
                    <dd><?php echo esc_html( $servings ); ?></dd>
                </div>
            <?php endif; ?>

            <?php if ( $difficulty ) : ?>
                <div class="pxr-print-meta-item">
                    <dt><?php esc_html_e( 'Difficulty:', 'plugixarecipe' ); ?></dt>
                    <dd><?php echo esc_html( $difficulty ); ?></dd>
                </div>
            <?php endif; ?>

            <?php if ( $cuisine ) : ?>
                <div class="pxr-print-meta-item">
                    <dt><?php esc_html_e( 'Cuisine:', 'plugixarecipe' ); ?></dt>
                    <dd><?php echo esc_html( $cuisine ); ?></dd>
                </div>
            <?php endif; ?>
        </div>
    </header>

    <!-- Image -->
    <?php if ( $image_url ) : ?>
        <img src="<?php echo esc_url( $image_url ); ?>"
             alt="<?php echo esc_attr( $title ); ?>"
             class="pxr-print-image" />
    <?php endif; ?>

    <!-- Ingredients -->
    <?php if ( ! empty( $ingredient_groups ) ) : ?>
        <section class="pxr-print-ingredients">
            <h2><?php esc_html_e( 'Ingredients', 'plugixarecipe' ); ?></h2>
            <?php foreach ( $ingredient_groups as $group ) : ?>
                <?php if ( ! empty( $group->name ) ) : ?>
                    <h3><?php echo esc_html( $group->name ); ?></h3>
                <?php endif; ?>
                <?php if ( ! empty( $group->items ) && is_array( $group->items ) ) : ?>
                    <ul>
                        <?php foreach ( $group->items as $ingredient ) : ?>
                            <li>
                                <?php if ( ! empty( $ingredient->amount ) ) : ?>
                                    <strong><?php echo esc_html( $ingredient->amount ); ?></strong>
                                <?php endif; ?>
                                <?php if ( ! empty( $ingredient->unit ) ) : ?>
                                    <?php echo esc_html( $ingredient->unit ); ?>
                                <?php endif; ?>
                                <?php echo esc_html( $ingredient->name ?? $ingredient->text ?? '' ); ?>
                                <?php if ( ! empty( $ingredient->notes ) ) : ?>
                                    <em>(<?php echo esc_html( $ingredient->notes ); ?>)</em>
                                <?php endif; ?>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            <?php endforeach; ?>
        </section>
    <?php endif; ?>

    <!-- Instructions -->
    <?php if ( ! empty( $instruction_groups ) ) : ?>
        <section class="pxr-print-instructions">
            <h2><?php esc_html_e( 'Instructions', 'plugixarecipe' ); ?></h2>
            <?php foreach ( $instruction_groups as $group ) : ?>
                <?php if ( ! empty( $group->name ) ) : ?>
                    <h3><?php echo esc_html( $group->name ); ?></h3>
                <?php endif; ?>
                <?php if ( ! empty( $group->steps ) && is_array( $group->steps ) ) : ?>
                    <ol>
                        <?php foreach ( $group->steps as $step ) : ?>
                            <li>
                                <?php echo esc_html( wp_strip_all_tags( $step->text ?? '' ) ); ?>
                                <?php if ( ! empty( $step->tip ) ) : ?>
                                    <br /><em><?php esc_html_e( 'Tip:', 'plugixarecipe' ); ?> <?php echo esc_html( $step->tip ); ?></em>
                                <?php endif; ?>
                            </li>
                        <?php endforeach; ?>
                    </ol>
                <?php endif; ?>
            <?php endforeach; ?>
        </section>
    <?php endif; ?>

    <!-- Nutrition Facts (Simplified Table) -->
    <?php if ( $nutrition ) : ?>
        <section class="pxr-print-nutrition">
            <h2><?php esc_html_e( 'Nutrition Facts', 'plugixarecipe' ); ?></h2>
            <?php if ( ! empty( $nutrition->serving_size ) ) : ?>
                <p style="font-size: 13px; margin-bottom: 8px;">
                    <?php
                    /* translators: %s: serving size */
                    echo esc_html( sprintf( __( 'Serving Size: %s', 'plugixarecipe' ), $nutrition->serving_size ) );
                    ?>
                </p>
            <?php endif; ?>

            <table class="pxr-print-nutrition-table">
                <thead>
                    <tr>
                        <th><?php esc_html_e( 'Nutrient', 'plugixarecipe' ); ?></th>
                        <th><?php esc_html_e( 'Amount', 'plugixarecipe' ); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $nutrients = array(
                        'calories'           => array( __( 'Calories', 'plugixarecipe' ), '' ),
                        'total_fat'          => array( __( 'Total Fat', 'plugixarecipe' ), 'g' ),
                        'saturated_fat'      => array( __( 'Saturated Fat', 'plugixarecipe' ), 'g' ),
                        'trans_fat'          => array( __( 'Trans Fat', 'plugixarecipe' ), 'g' ),
                        'cholesterol'        => array( __( 'Cholesterol', 'plugixarecipe' ), 'mg' ),
                        'sodium'             => array( __( 'Sodium', 'plugixarecipe' ), 'mg' ),
                        'total_carbohydrate' => array( __( 'Total Carbohydrate', 'plugixarecipe' ), 'g' ),
                        'dietary_fiber'      => array( __( 'Dietary Fiber', 'plugixarecipe' ), 'g' ),
                        'total_sugars'       => array( __( 'Total Sugars', 'plugixarecipe' ), 'g' ),
                        'added_sugars'       => array( __( 'Added Sugars', 'plugixarecipe' ), 'g' ),
                        'protein'            => array( __( 'Protein', 'plugixarecipe' ), 'g' ),
                        'vitamin_d'          => array( __( 'Vitamin D', 'plugixarecipe' ), 'mcg' ),
                        'calcium'            => array( __( 'Calcium', 'plugixarecipe' ), 'mg' ),
                        'iron'               => array( __( 'Iron', 'plugixarecipe' ), 'mg' ),
                        'potassium'          => array( __( 'Potassium', 'plugixarecipe' ), 'mg' ),
                        'vitamin_a'          => array( __( 'Vitamin A', 'plugixarecipe' ), '%' ),
                        'vitamin_c'          => array( __( 'Vitamin C', 'plugixarecipe' ), '%' ),
                    );

                    foreach ( $nutrients as $key => $info ) :
                        $value = isset( $nutrition->$key ) ? $nutrition->$key : null;
                        if ( $value === null ) continue;
                    ?>
                        <tr>
                            <td><?php echo esc_html( $info[0] ); ?></td>
                            <td><?php echo esc_html( $value . $info[1] ); ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </section>
    <?php endif; ?>

    <!-- Footer -->
    <footer class="pxr-print-footer">
        <p>
            <?php
            echo wp_kses(
                /* translators: 1: site name, 2: site URL. */
                sprintf( __( 'Printed from <a href="%2$s">%1$s</a>', 'plugixarecipe' ), esc_html( $site_name ), esc_url( $site_url ) ),
                array( 'a' => array( 'href' => array() ) )
            );
            ?>
            <?php if ( $source_url ) : ?>
                &mdash;
                <a href="<?php echo esc_url( $source_url ); ?>"><?php echo esc_html( $source_url ); ?></a>
            <?php endif; ?>
        </p>
    </footer>

    <script>
    (function() {
        var params = new URLSearchParams(window.location.search);
        if (params.get('auto') === '1') {
            window.addEventListener('load', function() {
                window.print();
            });
        }
    })();
    </script>

</body>
</html>
