<?php
/**
 * Single Book Template
 * 
 * Custom template for displaying single book posts from the "book" custom post type
 * (provided by RS WP Book Showcase plugin). Uses global header/footer and pulls
 * book data from CMB2 meta fields.
 * 
 * @package Author_Website_Templates
 * @since 1.0.9
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Ensure we're in the loop
if (!have_posts()) {
    return;
}

the_post();

// Get book meta data
$book_id = get_the_ID();
$title = get_the_title();
$cover_url = get_the_post_thumbnail_url($book_id, 'large');
$placeholder_cover = RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/images/book-placeholder.png';

// Author/Illustrator - Try taxonomy first, then meta
$author_terms = get_the_terms($book_id, 'book-author');
$author_name = '';
if ($author_terms && !is_wp_error($author_terms)) {
    $author_name = $author_terms[0]->name;
} else {
    $author_name = get_post_meta($book_id, '_rsbs_book_translator', true);
}
if (empty($author_name)) {
    $author_name = __('Unknown Author', 'author-website-templates');
}

// Description
$description = get_post_meta($book_id, '_rsbs_short_description', true);
if (empty($description)) {
    $description = get_the_content();
}
if (empty($description)) {
    $description = get_the_excerpt();
}

// Buy Buttons
$primary_btn_text = get_post_meta($book_id, '_rsbs_buy_btn_text', true);
$primary_btn_link = get_post_meta($book_id, '_rsbs_buy_btn_link', true);
$additional_stores = get_post_meta($book_id, 'rswpbs_also_available_website_list', true);

// Peek Inside Gallery
$gallery_images = get_post_meta($book_id, 'rswpbs_book_sample_content', true);
$publishersQueryLink = rswpbs_static_search_string(array('publisher' => rswpbs_get_book_publisher_name($book_id)));
// Book Details
$book_info_fields = [
    'availability' => [
        'value' => rswpbs_get_book_availability_status($book_id),
        'label' => rswpbs_static_text_availability(),
        'condition' => function ($value) {
            return !empty($value) && $value !== 'blank';
        }
    ],
    'original_title' => [
        'value' => rswpbs_get_book_original_name($book_id),
        'label' => rswpbs_static_text_original_title(),
        'wrapper' => function ($value) {
            $url = rswpbs_get_book_original_url();
            return $url ? "<a href='" . esc_url($url) . "'>" . esc_html($value) . "</a>" : esc_html($value);
        }
    ],
    'categories' => [
        'value' => rswpbs_get_book_categories($book_id),
        'label' => rswpbs_static_text_categories(),
        'escape' => 'wp_kses_post'
    ],
    'series' => [
        'value' => rswpbs_get_book_series($book_id),
        'label' => rswpbs_static_text_series(),
        'escape' => 'wp_kses_post'
    ],
    'publish_date' => [
        'value' => rswpbs_get_book_publish_date($book_id),
        'label' => rswpbs_static_text_publish_date()
    ],
    'publish_year' => [
        'value' => rswpbs_get_book_publish_year($book_id),
        'label' => rswpbs_static_text_published_year(),
        'condition' => function () {
            return !empty(rswpbs_get_book_publish_date());
        }
    ],
    'publisher' => [
        'value' => "<a href='" . esc_url($publishersQueryLink) . "'>" . esc_html(rswpbs_get_book_publisher_name($book_id)) . "</a>",
        'label' => rswpbs_static_text_publisher_name(),
        'escape' => false
    ],
    'pages' => [
        'value' => rswpbs_get_book_pages($book_id),
        'label' => rswpbs_static_text_total_pages()
    ],
    'isbn' => [
        'value' => rswpbs_get_book_isbn($book_id),
        'label' => rswpbs_static_text_isbn()
    ],
    'isbn_10' => [
        'value' => rswpbs_get_book_isbn_10($book_id),
        'label' => rswpbs_static_text_isbn_10()
    ],
    'isbn_13' => [
        'value' => rswpbs_get_book_isbn_13($book_id),
        'label' => rswpbs_static_text_isbn_13()
    ],
    'asin' => [
        'value' => rswpbs_get_book_asin($book_id),
        'label' => rswpbs_static_text_asin()
    ],
    'format' => [
        'value' => rswpbs_get_book_format($book_id),
        'label' => rswpbs_static_text_format()
    ],
    'country' => [
        'value' => rswpbs_get_book_country($book_id),
        'label' => rswpbs_static_text_country()
    ],
    'language' => [
        'value' => rswpbs_get_book_language($book_id),
        'label' => rswpbs_static_text_language()
    ],
    'translator' => [
        'value' => rswpbs_get_book_translator($book_id),
        'label' => rswpbs_static_text_translator()
    ],
    'file_size' => [
        'value' => rswpbs_get_book_file_size($book_id),
        'label' => rswpbs_static_text_file_size()
    ],
    'dimension' => [
        'value' => rswpbs_get_book_dimension($book_id),
        'label' => rswpbs_static_text_dimension()
    ],
    'weight' => [
        'value' => rswpbs_get_book_weight($book_id),
        'label' => rswpbs_static_text_weight()
    ],
    'file_format' => [
        'value' => rswpbs_get_book_file_format($book_id),
        'label' => rswpbs_static_text_file_format()
    ],
    'simultaneous_device_usage' => [
        'value' => rswpbs_get_simultaneous_device_usage($book_id),
        'label' => rswpbs_static_text_simultaneous_device_usage()
    ],
    'text_to_speech' => [
        'value' => rswpbs_get_book_text_to_speech($book_id),
        'label' => rswpbs_static_text_text_to_speech()
    ],
    'screen_reader' => [
        'value' => rswpbs_get_screen_reader($book_id),
        'label' => rswpbs_static_text_screen_reader()
    ],
    'enhanced_typesetting' => [
        'value' => rswpbs_get_enhanced_typesetting($book_id),
        'label' => rswpbs_static_text_enhanced_typesetting()
    ],
    'x_ray' => [
        'value' => rswpbs_get_x_ray($book_id),
        'label' => rswpbs_static_text_x_ray()
    ],
    'word_wise' => [
        'value' => rswpbs_get_word_wise($book_id),
        'label' => rswpbs_static_text_word_wise()
    ],
    'sticky_notes' => [
        'value' => rswpbs_get_sticky_notes($book_id),
        'label' => rswpbs_static_text_sticky_notes()
    ],
    'print_length' => [
        'value' => rswpbs_get_print_length($book_id),
        'label' => rswpbs_static_text_print_length()
    ],
    'avg_rate' => [
        'value' => rswpbs_get_avg_rate($book_id),
        'label' => rswpbs_static_text_avarage_ratings(),
        'escape' => 'wp_kses_post'
    ],
    'reading_date' => [
        'value' => rswpbs_get_book_reading_date($book_id),
        'label' => rswpbs_static_text_reading_date(),
        'escape' => 'wp_kses_post'
    ]
];

// Back to books URL
$books_archive_url = get_post_type_archive_link('book');
?>
<?php
// Retrieve Global Settings
$awt_settings = get_option('awt_global_settings', []);

// Header Logic
$header_slug = isset($awt_settings['awt_global_header_block']) ? $awt_settings['awt_global_header_block'] : '';
$force_header_global = isset($awt_settings['awt_header_force_global']) ? $awt_settings['awt_header_force_global'] : false;

$header_id = false;
if (!empty($header_slug) && function_exists('rswpthemes_awt_get_block_id_by_slug')) {
    $header_id = rswpthemes_awt_get_block_id_by_slug($header_slug);
}

// Check conditions: We use custom header if ID found AND Force Global is enabled.
$use_custom_header = ($header_id && $force_header_global);

if ($use_custom_header) {
    ?>
    <!DOCTYPE html>
    <html <?php language_attributes(); ?>>
    <head>
        <meta charset="<?php bloginfo('charset'); ?>">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <?php wp_head(); ?>
    </head>
    <body <?php body_class('awt-wrapper'); ?>>
        <div class="bg-cream font-sans text-navy antialiased awt-body-inner">
    <?php
    echo do_blocks('<!-- wp:block {"ref":' . absint($header_id) . '} /-->');
} else {
    get_header();
}
?>

<main>
    <?php
    // Check if a custom template block is selected
    $template_slug = isset($awt_settings['awt_book_single_template_id']) ? $awt_settings['awt_book_single_template_id'] : '';
    $template_id = 0;

    if (!empty($template_slug) && function_exists('rswpthemes_awt_get_block_id_by_slug')) {
        $template_id = rswpthemes_awt_get_block_id_by_slug($template_slug);
    }

    if (!empty($template_id)) {
        // Render the selected Reusable Block
        $template_post = get_post($template_id);

        if ($template_post && $template_post->post_type === 'wp_block' && $template_post->post_status === 'publish') {
            // Render the block content
            echo do_blocks($template_post->post_content);
        } else {
            // Fallback if block doesn't exist
            echo '<p class="awt-container mx-auto px-6 py-16 text-center">' . esc_html__('Selected template block not found. Please update in settings.', 'author-website-templates') . '</p>';
        }
    }
    ?>
</main>

<?php
// Footer Logic
$footer_slug = isset($awt_settings['awt_global_footer_block']) ? $awt_settings['awt_global_footer_block'] : '';
$force_footer_global = isset($awt_settings['awt_footer_force_global']) ? $awt_settings['awt_footer_force_global'] : false;

$footer_id = false;
if (!empty($footer_slug) && function_exists('rswpthemes_awt_get_block_id_by_slug')) {
    $footer_id = rswpthemes_awt_get_block_id_by_slug($footer_slug);
}

$use_custom_footer = ($footer_id && $force_footer_global);

if ($use_custom_footer) {
    echo do_blocks('<!-- wp:block {"ref":' . absint($footer_id) . '} /-->');
    wp_footer();
    echo '</div></body></html>';
} else {
    get_footer();
}
?>