<?php
date_default_timezone_set('Asia/Kolkata');
$op = get_option('print_Options_option_name');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php the_title("Print | "); ?></title>

<?php
// ✅ Fonts path (from plugin folder)
$plugin_base = plugin_dir_url(dirname(__FILE__));
$fonts_base  = $plugin_base . 'assest/fonts/';
?>

<!-- ✅ Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400&family=Ramabhadra&display=swap" rel="stylesheet">

<style>
@font-face {
  font-family: 'JIMS';
  src: url('<?php echo esc_url($fonts_base . "JIMS-Regular.woff2"); ?>') format('woff2'),
       url('<?php echo esc_url($fonts_base . "JIMS-Regular.woff"); ?>') format('woff'),
       url('<?php echo esc_url($fonts_base . "JIMS Regular.otf"); ?>') format('opentype');
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}
@font-face {
  font-family: 'Ramabhadra';
  src: url('<?php echo esc_url($fonts_base . "Ramabhadra-Regular.woff2"); ?>') format('woff2'),
       url('<?php echo esc_url($fonts_base . "Ramabhadra-Regular.ttf"); ?>') format('truetype');
  font-weight: 700;
  font-style: normal;
  font-display: swap;
}

/* ===== Base Fonts ===== */
html, body.print-body, .news-details-print, article {
  font-family: 'JIMS', "Noto Sans Telugu", sans-serif !important;
  font-weight: 400;
  background: white;
  margin: 0;
  padding: 0;
}
	
body.print-body p {
 font-size: 20px;
  line-height: 1.2;
  word-spacing: 0.1px;     /* ✅ Telugu కి చాలా ఎక్కువ spacing avoid */
  letter-spacing: 0.1px;   /* ✅ narrow kerning */
  text-align: justify;
  text-justify: inter-word; /* ✅ prevent Telugu words breaking */
  hyphens: auto;            /* ✅ proper word wrap (browser supported) */
  margin-bottom: 1px;
  color: #000000;
}

/* ===== Headline ===== */
h2.p-title {
  font-family: 'Ramabhadra', sans-serif !important;
  font-weight: 500 !important;
  text-align: center;
  color: red !important;
  line-height: 1.4;
  margin: 10px 0;
  font-size: clamp(28px, 3.2vw + 10px, 60px);
}
@media (max-width: 768px) {
  h2.p-title {
    font-size: clamp(40px, 10vw + 12px, 90px);
    line-height: 1.45;
  }
}

/* ===== Date + Editor ===== */
.time.p-date {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  background: #2F4F4F;
  color: #fff;
  padding: 6px 12px;
  font-size: 18px;
  font-family: 'JIMS', sans-serif;
}
.time.p-date > div {
  white-space: nowrap;
  text-align: center;
}

/* ===== Outer Container (Green border outside) ===== */
.content-center {
  text-align: center;
  margin: 60px auto;
  background: white;
  padding: 30px 25px;
  max-width: 920px;
  border-radius: 8px;
  position: relative;
}

/* visible green outline using pseudo element */
.content-center::before {
  content: "";
  position: absolute;
  top: -10px; left: -10px; right: -10px; bottom: -10px;
  border: 8px solid #106634;
  border-radius: 10px;
  pointer-events: none;
}

/* ===== Export-only overrides (clean capture) ===== */
.exporting .content-center {
  box-shadow: none !important;
  margin: 0 !important;
  max-width: none !important;
  width: 100% !important;
  padding: 25px !important;
  border-radius: 4px !important;
  background: #ffffff !important;
  box-sizing: border-box !important;
  border: 1px solid #f5f5f5 !important;
}
.exporting .content-center::before { display: none !important; }

/* ===== Misc ===== */
.news-details-print { padding: 10px; }
.print-copyright { text-align: center; font-size: 22px; margin: 10px; }
.print-float { position: fixed; bottom: 40px; right: 10%; z-index: 9999; }
a.btn { border-radius: 5px; margin: 5px; padding: 6px 10px; font-size: 22px; color: #fff; text-decoration: none; }
a.btn.red { background: red; }
a.btn.green { background: green; }
a.btn img { max-height: 18px; filter: brightness(0) invert(1); }
@media print { .no-print, .no-print * { display:none!important; } img { width:100%!important; } }

/* ===== Column Dropdown Style ===== */
#epaperCols {
  font-family: 'JIMS', sans-serif;
  font-size: 18px;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #ccc;
  margin-right: 10px;
}

/* ===== Hide ads inside print page when print-page-noads class is present =====
   This hides common ad elements and prevents leaving empty boxes by forcing size:0.
*/
body.print-page-noads .adsbygoogle,
body.print-page-noads ins.adsbygoogle,
body.print-page-noads .ad,
body.print-page-noads .ad-container,
body.print-page-noads .ad-banner,
body.print-page-noads .wp_ad,
body.print-page-noads iframe[src*="google"],
body.print-page-noads [id^="ad-"],
body.print-page-noads [class*="ad-"],
body.print-page-noads .googleslot,
body.print-page-noads .google-ad {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  margin: 0 !important;
  padding: 0 !important;
  visibility: hidden !important;
  overflow: hidden !important;
}

/* 🟩 Prevent Ads inside Green Border (explicit extra rule you asked) */
.print-area ins.adsbygoogle,
.print-area iframe,
.print-area .google-auto-placed,
.print-area .adsbygoogle,
.print-area [id*="google_ads_iframe"],
.print-area .ad,
.print-area .ad-container {
  display: none !important;
  visibility: hidden !important;
  height: 0 !important;
  width: 0 !important;
  margin: 0 !important;
  padding: 0 !important;
}
</style>

<?php wp_head(); ?>
</head>

<body class="print-body">
<div id="epaper_ss" style="background:white!important;">
  <div class="content-center">

    <img src="<?php echo esc_url($op['header_banner_0']); ?>" alt="Logo" style="max-width:100%;height:auto;image-rendering:-webkit-optimize-contrast;">

    <div class="time p-date">
      <div>Date of Publish : <?php echo get_the_date("d F Y, g:i a"); ?></div>
      <div></div>
      <div>Editor : Sake Naresh</div>
    </div>

    <h2 class="p-title"><?php the_title(); ?></h2>

    <?php if ($op['design_3'] == "online"): ?>
      <center><img src="<?php echo get_the_post_thumbnail_url(get_the_ID(), 'full'); ?>" alt=""></center>
    <?php endif; ?>

    <div id="my-element" class="news-details-print print-container">
      <?php if ($op['design_3'] == "epaper"): $lead_photo = '<img src="' . get_the_post_thumbnail_url(get_the_ID(), "full") . '">'; endif; ?>
      <?php $post = get_post(get_the_id());
      if (!empty($post->post_content)) { echo wpautop($lead_photo . $post->post_content); } ?>
    </div>

    <div class="print-copyright">
      <hr>
      <?php if ($op['editor_information_1']): ?>
        <p><?php echo html_entity_decode($op['editor_information_1']); ?></p>
      <?php endif; ?>
      <strong><?php echo $op['copyright_2'] ?: 'Copyright © '.esc_html(date('Y')).' '.esc_html(get_bloginfo('name')).'. All rights reserved.'; ?></strong>
    </div>
  </div>
</div>

<!-- ✅ Floating Buttons -->
<div class="print-float no-print">
  <select id="epaperCols">
    <option value="2">2 Columns</option>
    <option value="3">3 Columns</option>
  </select>
  <a href="#" class="btn red" onclick="window.print()">
    <img src="https://cdn-icons-png.flaticon.com/512/3022/3022251.png"> Print
  </a>
  <a href="#" id="print_news" onclick="download_NewsNow()" class="btn green">
    <img src="https://cdn-icons-png.flaticon.com/512/4208/4208397.png"> Save
  </a>
</div>

<?php wp_footer(); ?>

<script>
(function(){
  var select = document.getElementById('epaperCols');
  var newsEl = document.querySelector('.news-details-print');
  var bodyEl = document.querySelector('body.print-body');
  var baseWidth = 210; // base width for 2 columns (mm)
  var defaultCols = 2;

  function applyCols(val) {
    val = parseInt(val) || defaultCols;
    if(newsEl) {
      newsEl.style.columnCount = val;
      newsEl.style.WebkitColumnCount = val;
      newsEl.style.MozColumnCount = val;
    }
    if(bodyEl) {
      var newWidth = (baseWidth / 2) * val; // proportional width
      bodyEl.style.width = newWidth + 'mm';
    }
  }

  // load saved selection
  var saved = null;
  try { saved = localStorage.getItem('print_epaper_cols'); } catch(e){}
  if(saved && select) select.value = saved;
  applyCols(saved || defaultCols);

  // REPLACED change handler: save selection then reload (cache-bust)
  if (select) {
    select.addEventListener('change', function(e){
      var v = e.target.value;
      try { localStorage.setItem('print_epaper_cols', v); } catch(err){}

      // small delay so UI updates then reload with cache-bust param
      setTimeout(function(){
        try {
          var href = window.location.href.split('#')[0].split('?')[0];
          window.location.replace(href + '?_col_ts=' + Date.now());
        } catch(ex) {
          window.location.reload();
        }
      }, 200);
    });
  }

  /**
   * Improved export that:
   *  - adds .exporting class to body to temporarily override styles
   *  - clones the epaper node, appends hidden wrapper
   *  - uses domtoimage.toPng with options
   *  - removes .exporting and wrapper afterward
   */
  window.download_NewsNow = function() {
    var node = document.getElementById('epaper_ss');
    if(!node) {
      alert('No content found.');
      return;
    }

    if(typeof domtoimage === 'undefined') {
      alert('Export library not loaded. Using browser Print (Ctrl+P).');
      window.print();
      return;
    }

    // ensure selected columns applied before export
    var colVal = select ? select.value : defaultCols;
    applyCols(colVal);

    // add exporting class to body (CSS will hide pseudo and whitespace)
    document.body.classList.add('exporting');

    // small timeout so CSS takes effect
    setTimeout(function(){
      // compute original bounding rect
      var origRect = node.getBoundingClientRect();
      var width = Math.ceil(origRect.width);
      var height = Math.ceil(origRect.height);

      // clone node
      var cloned = node.cloneNode(true);
      // ensure clone uses same computed width (remove outside margins)
      cloned.style.boxSizing = 'border-box';
      cloned.style.margin = '0';
      cloned.style.width = width + 'px';
      cloned.style.height = height + 'px';
      cloned.style.background = '#ffffff';

      // wrapper off-screen
      var wrap = document.createElement('div');
      wrap.style.position = 'fixed';
      wrap.style.left = '-99999px';
      wrap.style.top = '0';
      wrap.style.width = width + 'px';
      wrap.style.height = height + 'px';
      wrap.style.overflow = 'visible';
      wrap.appendChild(cloned);
      document.body.appendChild(wrap);

      // choose scale (reduce if memory issue)
      var scale = 3; // you can increase to 4-5 for higher res but memory heavy

      var opts = {
        width: Math.round(width * scale),
        height: Math.round(height * scale),
        bgcolor: '#ffffff',
        quality: 1,
        style: {
          transform: 'scale(' + scale + ')',
          transformOrigin: 'top left',
          width: width + 'px',
          height: height + 'px',
          background: '#ffffff'
        }
      };

      // run domtoimage
      domtoimage.toPng(cloned, opts)
        .then(function(dataUrl){
          var link = document.createElement('a');
          link.download = 'News-<?php echo intval(get_the_ID()); ?>-ePaper-HD.png';
          link.href = dataUrl;
          document.body.appendChild(link);
          link.click();
          link.remove();
        })
        .catch(function(err){
          console.error('domtoimage error', err);
          alert('Export failed. Try a lower scale or use Print. See console for details.');
        })
        .finally(function(){
          setTimeout(function(){
            try { wrap.remove(); } catch(e){}
            document.body.classList.remove('exporting');
          }, 300);
        });

    }, 160); // timeout to let CSS reflow
  };
})();
</script>

<!-- ====== MOBILE HEADING FORCE-FIX: set bigger heading size on small screens ====== -->
<script>
document.addEventListener('DOMContentLoaded', function(){
  function applyMobileTitleSize(){
    var title = document.querySelector('.p-title');
    if (!title) return;
    var w = window.innerWidth || document.documentElement.clientWidth;
    if (w <= 600) {
      // force larger font on mobile
      title.style.fontSize = '75px';
      title.style.lineHeight = '1.25';
    } else {
      // remove inline override so CSS handles desktop
      title.style.removeProperty('font-size');
      title.style.removeProperty('line-height');
    }
  }

  // initial
  applyMobileTitleSize();

  // on rotate / resize adjust
  var resizeTimer;
  window.addEventListener('resize', function(){
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(applyMobileTitleSize, 120);
  }, { passive: true });
});
</script>
</body>
</html>
