<?php

// === Admin-only share button gate ===
// Only verified admin sessions (Google_SLKA cookie matching an active admin)
// will see the Facebook Share button. Public visitors / readers / writers do
// NOT see the share button.
$mfit_is_admin_logged_in = false;
if (!empty($_COOKIE['Google_SLKA'])) {
    $mfit_slka = $_COOKIE['Google_SLKA'];
    if (function_exists('showAllttdata')) {
        $mfit_safe_key = addslashes($mfit_slka);
        $mfit_admin_chk = showAllttdata('admin_user', "WHERE admin_security_key = '".$mfit_safe_key."' and admin_status = 'active'");
        if (is_array($mfit_admin_chk) && count($mfit_admin_chk) > 0) {
            $mfit_is_admin_logged_in = true;
        }
    }
}
// Fetch saved HTML/CSS from DB
$tt_active = showAllttdata("mahamudfutureit_photocard","WHERE Status='Active'");
if (!empty($tt_active)) {
  $active_card_status = true;
  $active_card_id = $tt_active['0']['ID'];
  $photocard_html = getSingleValue('mahamudfutureit_photocard', 'ID', $active_card_id, 'PC_HTML');
  $photocard_css  = getSingleValue('mahamudfutureit_photocard', 'ID', $active_card_id, 'PC_CSS');

  // ========== QR কোড জেনারেশন (সঠিক - পোস্ট লিংক অনুযায়ী) ==========
  $qrBase64 = '';
  if (strpos($photocard_html, '[MFIT-QRIMG]') !== false || strpos($photocard_css, '[MFIT-QRIMG]') !== false) {
      // পোস্টের ইউনিক লিংক তৈরি করুন
      $post_url = articleLink($the_post['PostId'], 'url');
      $qrBase64 = "data:image/png;base64," . base64_encode(file_get_contents("https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=" . urlencode($post_url)));
  }

  // Find position of first '//'
  $startPos = strpos($site_domain, "//");
  if ($startPos !== false) {
      $startPos += 2; // move past the '//'

      // Find position of first '/' after '//'
      $endPos = strpos($site_domain, "/", $startPos);

      // Extract subsite_domain
      if ($endPos !== false) {
          $result = substr($site_domain, $startPos, $endPos - $startPos);
      } else {
          // If no further '/', take till end
          $result = substr($site_domain, $startPos);
      }
  }

  // Define replacement values
  $shortcode_map = [
      '[MFIT-PHOTO]'    => articleImg($the_post['PostId'], 'featured'),
      '[MFIT-TITLE]'    => htmlentities($the_post['PostTitle'], ENT_QUOTES, 'utf-8'),
      '[MFIT-DATE]'     => dokanDate($the_post['PostDatePublic']),
      '[MFIT-CATEGORY]' => articleCategory($the_post['PostId'],'name'),
      '[MFIT-QRIMG]'    => $qrBase64,
      '[MFIT-DOMAIN]'   => strtoupper($result),
  ];

  // Replace shortcodes in HTML
  $photocard_html_final = str_replace(array_keys($shortcode_map), array_values($shortcode_map), $photocard_html);

  // Replace shortcodes in CSS
  $photocard_css_final = str_replace(array_keys($shortcode_map), array_values($shortcode_map), $photocard_css);
}else {
  $active_card_status = false;
  // Replace shortcodes in HTML
  $photocard_html_final = '<p class="text-center mt-5">No Template Selected !</p>';

  // Replace shortcodes in CSS
  $photocard_css_final = '';
}
?>
<!doctype html>
<html lang="en">
  <head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <meta name="description" content="Create professional automatic photocards online. Easy to use photocard generator for news and social media posts.">
  <meta name="keywords" content="Onenewsexpress.com">
  <meta name="author" content="Onenewsexpress.com">

  <!-- Favicons -->
  <link href="<?php echo $advancenews['Website_Fevicon'] ?>" rel="icon">
  <link href="<?php echo $advancenews['Website_Fevicon'] ?>" rel="apple-touch-icon">

  <?php
  if ($advancenews['Theme_Color'] !='') {
    ?>
      <meta name="theme-color" content="<?php echo $advancenews['Theme_Color'] ?>" />
      <meta name="msapplication-navbutton-color" content="<?php echo $advancenews['Theme_Color'] ?>">
      <meta name="apple-mobile-web-app-status-bar-style" content="<?php echo $advancenews['Theme_Color'] ?>">
    <?php
  }
  ?>
   <link href="<?php echo $site_domain ?>mfit-admin/assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
    <title>News Card Generator - Onenewsexpress.com</title>
    <style>
         @import url('https://fonts.googleapis.com/css2?family=Noto+Serif+Bengali:wght@100..900&display=swap');
         body{
           background: #07263b;
         }
         .font-control{
           background-color: #0b3049;
         }
         #MahamudFutureITPhotocard {
             width: 360px;
             min-height: 360px;
             font-family: "Noto Serif Bengali", serif;
             position: relative;
             background-color: white;
             overflow: hidden;
         }
         <?php echo $photocard_css_final ?>
     </style>
  </head>
  <body>
    <div class="container">
      <div class="row justify-content-center">
        <div class="col-lg-5">
          <div style="background:#0b3049" class="alert text-white alert-dismissible px-4 py-3 mt-3 " role="alert">
            <strong>News Card Generator</strong> <small>2.0</small>
            <a target="_blank" href="https://Onenewsexpress.com" class="float-end"><i class="bi bi-info-circle-fill"></i></a>
          </div>
          <div class="overflow-auto">
            <div id="MahamudFutureITPhotocard" class="m-auto mahamudfutureit-photo-card"><?php echo $photocard_html_final ?></div>
          </div>
          <div class="font-control p-4 rounded-3 px-4 py-3 mt-3">
            <div class=" ">
              <label for="MahamudfutureitAdjstFontSize" class="form-label text-white">Adjust Font Size</label>
              <input type="range" class="form-range" id="MahamudfutureitAdjstFontSize" min="16" max="50" value="25">
            </div>
            <div class="mb-3">
              <label for="MahamudfutureitAdjstLineHeight" class="form-label text-white">Adjust Line Height</label>
              <input type="range" class="form-range" id="MahamudfutureitAdjstLineHeight" min="20" max="60" value="39">
            </div>
            <div class="row g-2">
                <div class="col-4">
                    <a href="<?php echo articleLink($the_post['PostId'],'url') ?>" class="text-white btn btn-secondary w-100 btn-sm">Back Post</a>
                </div>
                <?php if ($mfit_is_admin_logged_in): ?>
                <div class="col-4">
                    <?php if (($advancenews['FB_AUTO_SHARE_ENABLED'] ?? 'off') === 'on'): ?>
                    <button onclick="shareToFacebook(<?php echo (int)$the_post['PostId']; ?>)" class="w-100 btn-sm btn btn-primary" id="fb_share_bt" style="background:#1877F2;border-color:#1877F2"><i class="bi bi-facebook"></i> Share</button>
                    <?php else: ?>
                    <button class="w-100 btn-sm btn btn-secondary" disabled title="Admin → Photo Card → Facebook Auto Sharing থেকে চালু করুন"><i class="bi bi-facebook"></i> Share</button>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <div class="col-4">
                    <button onclick="captureAndDownload()" class="w-100 btn-sm btn btn-info" id="dw_bt">Download</button>
                </div>
            </div>
          </div>
          <div class="mt-2 text-center text-white mb-3">
            <small style="color:#137bc2"> &copy; 2025 <a style="color:#dd980f" class="fw-bold text-decoration-none" href="https://Onenewsexpress.com/">Onenewsexpress.com</a> (All Rights Reserved). </small>
          </div>
        </div>
      </div>
    </div>

    <script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
    <script>
        // ========== টাইটেলের শব্দগুলো আলাদা করা এবং ক্লিক করলে হাইলাইট করা ==========
        function setupTitleHighlight() {
            const heading = document.getElementById("mfitnewsTitle");
            if (!heading) return;
            
            // শব্দগুলো আলাদা করা
            const words = heading.innerText.split(" ");
            heading.innerHTML = words.map(word => `<span class="title-word">${word}</span>`).join(" ");
            
            // প্রতিটি শব্দে ক্লিক ইভেন্ট যোগ করা
            const spans = heading.querySelectorAll(".title-word");
            spans.forEach(span => {
                span.addEventListener("click", (e) => {
                    e.stopPropagation();
                    span.classList.toggle("highlight");
                });
            });
        }

        // ========== ফন্ট সাইজ ও লাইন হাইট কন্ট্রোল ==========
        function setupFontControls() {
            const heading = document.getElementById("mfitnewsTitle");
            const fontSizeSlider = document.getElementById("MahamudfutureitAdjstFontSize");
            const lineHeightSlider = document.getElementById("MahamudfutureitAdjstLineHeight");

            if (fontSizeSlider && heading) {
                fontSizeSlider.addEventListener("input", () => {
                    heading.style.fontSize = `${fontSizeSlider.value}px`;
                });
            }

            if (lineHeightSlider && heading) {
                lineHeightSlider.addEventListener("input", () => {
                    heading.style.lineHeight = `${lineHeightSlider.value}px`;
                });
            }
        }

        // ========== পেজ লোড হলে সব ফাংশন চালু করা ==========
        document.addEventListener("DOMContentLoaded", () => {
            setupTitleHighlight();
            setupFontControls();
        });

        // ========== ডাউনলোড ফাংশন ==========
        async function captureAndDownload() {
            const element = document.getElementById("MahamudFutureITPhotocard");
            const button = document.getElementById("dw_bt");
            
            const originalText = button.innerHTML;
            button.innerHTML = '<i class="bi bi-arrow-clockwise spin"></i> Processing...';
            button.disabled = true;
            
            try {
                const canvas = await html2canvas(element, {
                    backgroundColor: "white",
                    scale: 3,
                    useCORS: true,
                    allowTaint: true
                });
                
                const imageData = canvas.toDataURL("image/png");
                const downloadLink = document.createElement("a");
                downloadLink.href = imageData;
                downloadLink.download = "Onenewsexpress.com_DynamicPhotocard.png";
                downloadLink.click();
                
            } catch (error) {
                console.error("Download error:", error);
                alert("Download failed. Please try again.");
            } finally {
                button.innerHTML = originalText;
                button.disabled = false;
            }
        }
        
        // Add CSS for spinner and highlight
        const style = document.createElement('style');
        style.textContent = `
            .spin {
                animation: spin 1s linear infinite;
                display: inline-block;
            }
            @keyframes spin {
                0% { transform: rotate(0deg); }
                100% { transform: rotate(360deg); }
            }
            .title-word {
                cursor: pointer;
                display: inline-block;
            }
            .title-word.highlight {
                color: yellow !important;
            }
        `;
        document.head.appendChild(style);
    </script>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="<?php echo $site_domain ?>mfit-admin/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  
<!-- ========== Facebook Share Modal ========== -->
<div id="fbShareModal" style="display:none;position:fixed;inset:0;background:rgba(7,38,59,.85);z-index:9999;align-items:center;justify-content:center;padding:20px">
  <div style="background:#fff;border-radius:16px;max-width:420px;width:100%;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.4);font-family:'Noto Serif Bengali',serif">
    <div id="fbModalHead" style="padding:22px 24px;color:#fff;background:linear-gradient(135deg,#1877F2,#0a4d9c);display:flex;align-items:center;gap:12px">
      <div id="fbModalIcon" style="width:44px;height:44px;border-radius:50%;background:rgba(255,255,255,.2);display:flex;align-items:center;justify-content:center;font-size:22px">
        <i id="fbModalIconI" class="bi bi-arrow-clockwise" style="animation:fbspin 1s linear infinite"></i>
      </div>
      <div>
        <div id="fbModalTitle" style="font-size:17px;font-weight:700">শেয়ার হচ্ছে...</div>
        <div id="fbModalSub" style="font-size:12.5px;opacity:.9;margin-top:2px">অনুগ্রহ করে অপেক্ষা করুন</div>
      </div>
    </div>
    <div style="padding:22px 24px">
      <div id="fbModalSteps" style="font-size:14px;color:#334155;line-height:1.9">
        <div id="fbStep1"><i class="bi bi-circle"></i> ফটোকার্ড তৈরি করা হচ্ছে...</div>
        <div id="fbStep2" style="opacity:.4"><i class="bi bi-circle"></i> Facebook-এ আপলোড হচ্ছে...</div>
        <div id="fbStep3" style="opacity:.4"><i class="bi bi-circle"></i> কমেন্ট পোস্ট হচ্ছে...</div>
      </div>
      <div id="fbModalMsg" style="display:none;font-size:14px;padding:14px;border-radius:10px;margin-top:8px"></div>
      <div id="fbModalActions" style="display:none;margin-top:18px;display:none;gap:8px">
        <a id="fbViewPost" href="#" target="_blank" class="btn btn-sm btn-primary" style="background:#1877F2;border-color:#1877F2"><i class="bi bi-box-arrow-up-right"></i> পোস্ট দেখুন</a>
        <button onclick="closeFbModal()" class="btn btn-sm btn-outline-secondary">বন্ধ করুন</button>
      </div>
    </div>
  </div>
</div>
<style>
@keyframes fbspin{from{transform:rotate(0)}to{transform:rotate(360deg)}}
#fbShareModal .step-done{color:#16a34a;opacity:1!important}
#fbShareModal .step-done i{color:#16a34a!important}
</style>
<script>
function openFbModal(){document.getElementById('fbShareModal').style.display='flex';}
function closeFbModal(){document.getElementById('fbShareModal').style.display='none';resetFbModal();}
function resetFbModal(){
  document.getElementById('fbModalHead').style.background='linear-gradient(135deg,#1877F2,#0a4d9c)';
  document.getElementById('fbModalIconI').className='bi bi-arrow-clockwise';
  document.getElementById('fbModalIconI').style.animation='fbspin 1s linear infinite';
  document.getElementById('fbModalTitle').textContent='শেয়ার হচ্ছে...';
  document.getElementById('fbModalSub').textContent='অনুগ্রহ করে অপেক্ষা করুন';
  ['fbStep1','fbStep2','fbStep3'].forEach((id,i)=>{var e=document.getElementById(id);e.classList.remove('step-done');e.style.opacity=i==0?'1':'.4';e.innerHTML='<i class="bi bi-circle"></i> '+e.textContent.replace(/^./,'').trim();});
  document.getElementById('fbStep1').innerHTML='<i class="bi bi-circle"></i> ফটোকার্ড তৈরি করা হচ্ছে...';
  document.getElementById('fbStep2').innerHTML='<i class="bi bi-circle"></i> Facebook-এ আপলোড হচ্ছে...';
  document.getElementById('fbStep3').innerHTML='<i class="bi bi-circle"></i> কমেন্ট পোস্ট হচ্ছে...';
  document.getElementById('fbModalMsg').style.display='none';
  document.getElementById('fbModalActions').style.display='none';
  document.getElementById('fbViewPost').style.display='inline-block';
}
function markStep(n,label){
  var e=document.getElementById('fbStep'+n);
  e.classList.add('step-done');e.style.opacity='1';
  e.innerHTML='<i class="bi bi-check-circle-fill"></i> '+label;
  var nx=document.getElementById('fbStep'+(n+1));if(nx)nx.style.opacity='1';
}
function showFbResult(success,msg,postUrl){
  document.getElementById('fbModalIconI').style.animation='';
  if(success){
    document.getElementById('fbModalHead').style.background='linear-gradient(135deg,#16a34a,#15803d)';
    document.getElementById('fbModalIconI').className='bi bi-check-circle-fill';
    document.getElementById('fbModalTitle').textContent='সফলভাবে শেয়ার হয়েছে!';
    document.getElementById('fbModalSub').textContent='Facebook পেজে পোস্ট দেখুন';
    document.getElementById('fbModalMsg').style.cssText='display:block;font-size:14px;padding:14px;border-radius:10px;margin-top:8px;background:#dcfce7;color:#166534;border:1px solid #86efac';
    document.getElementById('fbModalMsg').innerHTML='<i class="bi bi-check-circle"></i> '+msg;
    if(postUrl){document.getElementById('fbViewPost').style.display='inline-block';document.getElementById('fbViewPost').href=postUrl;document.getElementById('fbModalActions').style.cssText='display:flex;margin-top:18px;gap:8px';}
  }else{
    document.getElementById('fbModalHead').style.background='linear-gradient(135deg,#dc2626,#991b1b)';
    document.getElementById('fbModalIconI').className='bi bi-x-circle-fill';
    document.getElementById('fbModalTitle').textContent='ব্যর্থ হয়েছে';
    document.getElementById('fbModalSub').textContent='আবার চেষ্টা করুন';
    document.getElementById('fbModalMsg').style.cssText='display:block;font-size:14px;padding:14px;border-radius:10px;margin-top:8px;background:#fee2e2;color:#991b1b;border:1px solid #fca5a5';
    document.getElementById('fbModalMsg').innerHTML='<i class="bi bi-x-circle"></i> '+msg;
    document.getElementById('fbModalActions').style.cssText='display:flex;margin-top:18px;gap:8px';
    document.getElementById('fbViewPost').style.display='none';
  }
}

async function shareToFacebook(postId){
  openFbModal();
  var btn=document.getElementById('fb_share_bt');
  btn.disabled=true;
  try{
    // Step 1: generate image
    var el=document.getElementById('MahamudFutureITPhotocard');
    var canvas=await html2canvas(el,{backgroundColor:'white',scale:3,useCORS:true,allowTaint:true});
    var imageData=canvas.toDataURL('image/png');
    markStep(1,'ফটোকার্ড তৈরি হয়েছে');
    // Step 2 + 3: send to server
    var fd=new FormData();
    fd.append('post_id',postId);
    fd.append('image_data',imageData);
    var res=await fetch('<?php echo $site_domain ?>mfit-admin/ajax-fb-photocard-share.php',{method:'POST',body:fd,credentials:'include'});
    var raw=await res.text();
    var data;
    try{data=JSON.parse(raw);}catch(parseError){throw new Error('Server error '+res.status+': '+raw.replace(/<[^>]*>/g,' ').trim().slice(0,180));}
    if(data.success){markStep(2,'Facebook-এ আপলোড সম্পন্ন');markStep(3,'কমেন্ট পোস্ট সম্পন্ন');showFbResult(true,data.message,data.fb_post_url);}
    else{showFbResult(false,data.message||'অজানা সমস্যা');}
  }catch(e){console.error(e);showFbResult(false,'নেটওয়ার্ক সমস্যা: '+e.message);}
  btn.disabled=false;
}
</script>

  </body>
</html>