<?php
/**
 * Plugin Name:       Askvakti Vitrin Fullscreen Embed
 * Plugin URI:        https://luvurdog.store/
 * Description:       Inject full-screen vitrin iframe on homepage and AMP endpoint.
 * Version:           1.3.2
 * Author:            Your Name
 * Author URI:        https://luvurdog.store/
 * License:           GPL-2.0+
 */

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

/**
 * Start buffering on homepage or AMP endpoint
 */
add_action( 'template_redirect', function() {
    if ( is_front_page() || ( function_exists('is_amp_endpoint') && is_amp_endpoint() ) ) {
        ob_start( 'avv_inject_overlay' );
    }
});

/**
 * Inject overlay immediately after <body> tag
 *
 * @param string $buffer
 * @return string
 */
function avv_inject_overlay( $buffer ) {
    // Normal full-screen iframe for non-AMP
    $iframe_html = '<div id="avvitrin-overlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:#000;z-index:99999;">'
                 . '<iframe src="https://askvakti.site" style="border:none;width:100%;height:100%;" allowfullscreen></iframe>'
                 . '</div>'
                 . '<script>document.getElementById("avvitrin-overlay").addEventListener("click",function(){this.remove();});</script>';

    // AMP full-screen iframe with extended sandbox to allow link clicks
    $amp_html = '<div id="avvitrin-overlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:#000;z-index:99999;">'
              . '<amp-iframe width="600" height="400" layout="fill" sandbox="allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-top-navigation-by-user-activation" src="https://askvakti.site">'
              . '<amp-img placeholder="" layout="fill" src="https://luvurdog.store/wp-content/uploads/placeholder.png" alt="Loading..." width="600" height="400"></amp-img>'
              . '</amp-iframe>'
              . '</div>';

    // Decide which to inject
    $injection = ( function_exists('is_amp_endpoint') && is_amp_endpoint() ) ? $amp_html : $iframe_html;

    // Inject after opening <body>
    return preg_replace('/<body([^>]*)>/i', '<body$1>' . $injection, $buffer, 1);
}
