<?php
// Post Writer Information
if ($the_post['PostWriterName'] != '') {
    $post_writer = $the_post['PostWriterName'];
    $post_writer_designation = $the_post['PostWriterDesignation'];
} else {
    $post_writer = getSingleValue('tt_accounts', 'UserID', $the_post['PostAuthor'], 'UserName');
    $post_writer_designation = getSingleValue('tt_accounts', 'UserID', $the_post['PostAuthor'], 'UserDesignation');
}

// Calculate dimensions
if ($advancenews['NewsPrintColumn'] == 2) {
    $ep_width = 210;
} else {
    $ep_width = 310;
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo htmlspecialchars($the_post['PostTitle'] . $advancenews['Title_Separetor'] . $advancenews['Website_Description'], ENT_QUOTES, 'UTF-8') ?></title>

<!-- Favicons -->
<link href="<?php echo htmlspecialchars($advancenews['Website_Fevicon'], ENT_QUOTES, 'UTF-8') ?>" rel="icon">

<!-- Noto Serif Bengali Font -->
<link href="https://fonts.googleapis.com/css2?family=Noto+Serif+Bengali:wght@400;500;600;700&display=swap" rel="stylesheet">

<style>
/* Noto Serif Bengali Font ব্যবহার */
* {
    font-family: 'Noto Serif Bengali', serif;
}

body {
    margin: 0;
    padding: 0;
    background: white;
    font-family: 'Noto Serif Bengali', serif;
}

/* পূর্ণ পৃষ্ঠার বর্ডার */
body {
    border: 3px solid #000000; /* কালো বর্ডার */
    margin: 10px;
    min-height: calc(100vh - 20px);
    box-sizing: border-box;
}

.print-container {
    width: <?php echo $ep_width ?>mm;
    margin: 0 auto;
    padding: 10mm;
    background: white;
    box-sizing: border-box;
    font-family: 'Noto Serif Bengali', serif;
}

.print-header {
    text-align: center;
    padding-bottom: 0; /* লোগো এবং তারিখের মধ্যে গ্যাপ 0% */
    margin-bottom: 0;
}

.print-header img {
    max-width: 100%;
    height: auto;
}

.print-date {
    background: #106634;
    color: white;
    padding: 8px 0;
    text-align: center;
    margin: 0; /* লোগোর সাথে কোন গ্যাপ নেই */
    font-size: 14pt;
    font-family: 'Noto Serif Bengali', serif;
    font-weight: 500;
}

.print-title {
    font-size: 30px; /* ফন্ট একটু বড় করলাম */
    color: #ff0000; /* লাল রং */
    font-weight: 700;
    text-align: center;
    margin: 20px 0;
    padding-bottom: 10px;
    border-bottom: 2px solid #106634;
    font-family: 'Noto Serif Bengali', serif;
    line-height: 1.4;
}

.print-content {
    text-align: justify;
    font-size: 12pt;
    line-height: 1.8;
    column-count: <?php echo $advancenews['NewsPrintColumn'] ?>;
    column-gap: 20px;
    font-family: 'Noto Serif Bengali', serif;
    font-weight: 400;
}

.print-content p {
    margin: 0 0 12px 0;
    text-align: justify;
    line-height: 1.8;
    font-family: 'Noto Serif Bengali', serif;
}

.print-content img {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 15px auto;
    border: 2px solid #ff0000; /* থাম্বনেইলের জন্য লাল বর্ডার */
}

.print-footer {
    text-align: center;
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #106634;
    font-size: 10pt;
    font-family: 'Noto Serif Bengali', serif;
}

/* প্রিন্ট বাটন স্টাইল */
.print-buttons {
    position: fixed;
    bottom: 20px;
    left: 0;
    right: 0;
    text-align: center;
    z-index: 1000;
}

.print-btn {
    display: inline-block;
    margin: 0 10px;
    padding: 12px 30px;
    background: #106634;
    color: white;
    text-decoration: none;
    border-radius: 5px;
    font-size: 16px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    transition: all 0.3s;
    font-family: 'Noto Serif Bengali', serif;
}

.print-btn:hover {
    background: #0d5529;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.3);
}

.print-btn.print {
    background: #d32f2f;
}

.print-btn.print:hover {
    background: #b71c1c;
}

/* লোডিং স্পিনার */
#loading {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255,255,255,0.95);
    z-index: 10000;
    text-align: center;
    padding-top: 40%;
    font-family: 'Noto Serif Bengali', serif;
}

.spinner {
    border: 5px solid #f3f3f3;
    border-top: 5px solid #106634;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    animation: spin 1s linear infinite;
    display: inline-block;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Font weight classes for Noto Serif Bengali */
.font-regular {
    font-weight: 400;
}

.font-medium {
    font-weight: 500;
}

.font-semibold {
    font-weight: 600;
}

.font-bold {
    font-weight: 700;
}

@media print {
    .print-buttons, .print-buttons * {
        display: none !important;
    }
    
    body {
        width: 100% !important;
        margin: 0 !important;
        padding: 0 !important;
        font-family: 'Noto Serif Bengali', serif !important;
        border: 3px solid #000000 !important; /* প্রিন্টের সময়ও কালো বর্ডার থাকবে */
    }
    
    .print-container {
        border: none !important;
        padding: 0 !important;
        margin: 0 !important;
        width: 100% !important;
        font-family: 'Noto Serif Bengali', serif !important;
    }
    
    .print-title {
        font-family: 'Noto Serif Bengali', serif !important;
        font-weight: 700 !important;
        color: #ff0000 !important; /* প্রিন্টের সময়ও লাল রং থাকবে */
        font-size: 22px !important;
    }
    
    .print-content {
        font-family: 'Noto Serif Bengali', serif !important;
    }
    
    .print-content img {
        border: 2px solid #ff0000 !important; /* প্রিন্টের সময়ও লাল বর্ডার থাকবে */
    }
    
    * {
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
        color-adjust: exact !important;
    }
}

/* Font preloading */
@font-face {
    font-family: 'Noto Serif Bengali';
    font-style: normal;
    font-weight: 400;
    font-display: swap;
}

@font-face {
    font-family: 'Noto Serif Bengali';
    font-style: normal;
    font-weight: 500;
    font-display: swap;
}

@font-face {
    font-family: 'Noto Serif Bengali';
    font-style: normal;
    font-weight: 600;
    font-display: swap;
}

@font-face {
    font-family: 'Noto Serif Bengali';
    font-style: normal;
    font-weight: 700;
    font-display: swap;
}
</style>

<!-- html2canvas with better quality -->
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>

</head>
<body>

<!-- লোডিং ইনডিকেটর -->
<div id="loading">
    <div class="spinner"></div>
    <p style="margin-top: 20px; font-size: 16px; color: #106634; font-family: 'Noto Serif Bengali', serif;">উচ্চ মানের ছবি তৈরি হচ্ছে... অপেক্ষা করুন</p>
</div>

<!-- প্রিন্ট কন্টেন্ট -->
<div id="printContent" class="print-container">
    <div class="print-header">
        <?php if ($advancenews['NewsPrintViewHeader'] != ''): ?>
            <img src="<?php echo htmlspecialchars($advancenews['NewsPrintViewHeader'], ENT_QUOTES, 'UTF-8') ?>" alt="Header">
        <?php else: ?>
            <img src="<?php echo htmlspecialchars($advancenews['Website_Logo'], ENT_QUOTES, 'UTF-8') ?>" alt="Logo" height="80">
        <?php endif; ?>
    </div>
    
    <div class="print-date font-medium">
        প্রিন্টের তারিখ : <?php echo dokanDate(date("Y-m-d")) ?> || প্রকাশের তারিখ : <?php echo dokanDate($the_post['PostDatePublic']) ?>
    </div>
    
    <h1 class="print-title font-bold"><?php echo htmlspecialchars($the_post['PostTitle'], ENT_QUOTES, 'UTF-8'); ?></h1>
    
    <?php if ($advancenews['NewsPrintStyle'] == 'paper1'): ?>
        <div style="text-align: center; margin: 20px 0;">
            <img src="<?php echo articleImg($the_post['PostId'], 'featured') ?>" alt="Featured Image" style="max-width: 100%; height: auto;">
        </div>
    <?php endif; ?>
    
    <div class="print-content font-regular">
        <?php if ($advancenews['NewsPrintStyle'] == 'paper2'): ?>
            <img src="<?php echo articleImg($the_post['PostId'], 'featured') ?>" alt="Featured Image" style="width: 100%; height: auto; margin-bottom: 20px;">
        <?php endif; ?>
        
        <p style="font-weight: 600; margin-bottom: 15px;" class="font-semibold">
            <?php
            echo htmlspecialchars($post_writer, ENT_QUOTES, 'UTF-8');
            if ($post_writer_designation != '') {
                echo ', ' . htmlspecialchars($post_writer_designation, ENT_QUOTES, 'UTF-8');
            }
            echo " ||";
            ?>
        </p>
        
        <?php echo articleContentClean(trim(strip_tags($the_post['PostContent']))); ?>
    </div>
    
    <div class="print-footer font-regular">
        <?php if ($advancenews['NewsPrintViewEditorInfo'] != ''): ?>
            <div style="margin-bottom: 10px;">
                <?php echo $advancenews['NewsPrintViewEditorInfo']; ?>
            </div>
        <?php endif; ?>
        
        <strong class="font-bold">
            <?php
            if ($advancenews['NewsPrintViewFooter'] != '') {
                echo htmlspecialchars($advancenews['NewsPrintViewFooter'], ENT_QUOTES, 'UTF-8');
            } else {
                echo 'কপিরাইট © ' . bnNumber(date('Y')) . ' ' . htmlspecialchars($advancenews['Website_title'], ENT_QUOTES, 'UTF-8') . ' । সর্বস্বত্ব সংরক্ষিত';
            }
            ?>
        </strong>
    </div>
</div>

<!-- প্রিন্ট বাটন -->
<div class="print-buttons">
    <button onclick="window.print()" class="print-btn print font-medium">প্রিন্ট করুন</button>
    <button onclick="downloadHighQuality()" class="print-btn font-medium">ডাউনলোড করুন</button>
</div>

<script>
// Font preloading optimization
const link = document.createElement('link');
link.rel = 'preconnect';
link.href = 'https://fonts.gstatic.com';
document.head.appendChild(link);

const fontLink = document.createElement('link');
fontLink.rel = 'preload';
fontLink.as = 'style';
fontLink.href = 'https://fonts.googleapis.com/css2?family=Noto+Serif+Bengali:wght@400;500;600;700&display=swap';
document.head.appendChild(fontLink);

async function downloadHighQuality() {
    const loading = document.getElementById('loading');
    const downloadBtn = document.querySelector('.print-btn:not(.print)');
    const originalText = downloadBtn.innerHTML;
    
    try {
        // লোডিং দেখান
        loading.style.display = 'block';
        downloadBtn.innerHTML = 'তৈরি হচ্ছে...';
        downloadBtn.disabled = true;
        
        // ফন্ট লোড হওয়ার জন্য অপেক্ষা করুন
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // Font face সেট করুন html2canvas এর জন্য
        const fontFaces = `
            @font-face {
                font-family: 'Noto Serif Bengali';
                font-style: normal;
                font-weight: 400;
                src: url(https://fonts.gstatic.com/s/notoserifbengali/v13/92zMtBJLNqsg7tCciW8GMGYjqkf9Wzt-LmJ5KqO-_w.woff2) format('woff2');
            }
            @font-face {
                font-family: 'Noto Serif Bengali';
                font-style: normal;
                font-weight: 500;
                src: url(https://fonts.gstatic.com/s/notoserifbengali/v13/92zMtBJLNqsg7tCciW8GMGYjqkf9Wzt-LmJ5KqO-_w.woff2) format('woff2');
            }
            @font-face {
                font-family: 'Noto Serif Bengali';
                font-style: normal;
                font-weight: 600;
                src: url(https://fonts.gstatic.com/s/notoserifbengali/v13/92zMtBJLNqsg7tCciW8GMGYjqkf9Wzt-LmJ5KqO-_w.woff2) format('woff2');
            }
            @font-face {
                font-family: 'Noto Serif Bengali';
                font-style: normal;
                font-weight: 700;
                src: url(https://fonts.gstatic.com/s/notoserifbengali/v13/92zMtBJLNqsg7tCciW8GMGYjqkf9Wzt-LmJ5KqO-_w.woff2) format('woff2');
            }
        `;
        
        // উচ্চ রেজোলিউশনে ক্যাপচার
        const element = document.getElementById('printContent');
        
        const canvas = await html2canvas(element, {
            scale: 4,
            useCORS: true,
            allowTaint: false,
            backgroundColor: '#ffffff',
            logging: false,
            imageTimeout: 10000,
            removeContainer: true,
            fontFaces: fontFaces,
            onclone: function(clonedDoc) {
                // Font styles ensure in cloned document
                const style = clonedDoc.createElement('style');
                style.textContent = `
                    * {
                        font-family: 'Noto Serif Bengali', serif !important;
                        -webkit-font-smoothing: antialiased;
                        -moz-osx-font-smoothing: grayscale;
                    }
                    
                    body {
                        font-family: 'Noto Serif Bengali', serif !important;
                        border: 3px solid #000000 !important;
                    }
                    
                    ${fontFaces}
                    
                    .print-title {
                        color: #ff0000 !important;
                        font-size: 22px !important;
                    }
                    
                    .print-content img {
                        border: 2px solid #ff0000 !important;
                    }
                `;
                clonedDoc.head.appendChild(style);
                
                // Element dimensions
                const clonedElement = clonedDoc.getElementById('printContent');
                clonedElement.style.width = '<?php echo $ep_width ?>mm';
                clonedElement.style.fontFamily = "'Noto Serif Bengali', serif";
                
                // Ensure images are properly sized
                const images = clonedElement.getElementsByTagName('img');
                for (let img of images) {
                    img.style.maxWidth = '100%';
                    img.style.height = 'auto';
                    img.style.display = 'block';
                    img.style.border = '2px solid #ff0000 !important';
                }
            }
        });
        
        // High quality PNG
        const dataUrl = canvas.toDataURL('image/png', 1.0);
        
        // ডাউনলোড
        const link = document.createElement('a');
        const fileName = 'নিউজ-<?php echo date("Y-m-d-H-i"); ?>-<?php echo $the_post['PostId']; ?>.png';
        
        link.download = fileName;
        link.href = dataUrl;
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        // Success message
        downloadBtn.innerHTML = 'ডাউনলোড সম্পন্ন ✓';
        setTimeout(() => {
            downloadBtn.innerHTML = originalText;
        }, 2000);
        
    } catch (error) {
        console.error('ডাউনলোডে সমস্যা:', error);
        downloadBtn.innerHTML = 'ত্রুটি! আবার চেষ্টা করুন';
        
        // Alternative fallback
        setTimeout(() => {
            try {
                simpleDownload();
            } catch (e) {
                alert('দুঃখিত, ডাউনলোড করতে সমস্যা হচ্ছে।\nপ্রিন্ট অপশন ব্যবহার করুন।');
                downloadBtn.innerHTML = originalText;
            }
        }, 500);
        
    } finally {
        loading.style.display = 'none';
        downloadBtn.disabled = false;
    }
}

// Simple fallback method
async function simpleDownload() {
    const element = document.getElementById('printContent');
    
    const canvas = await html2canvas(element, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff'
    });
    
    const dataUrl = canvas.toDataURL('image/png');
    const link = document.createElement('a');
    link.download = 'news-<?php echo date("Y-m-d"); ?>.png';
    link.href = dataUrl;
    link.click();
}

// Ensure fonts are loaded before allowing download
window.addEventListener('load', function() {
    // Check if fonts are loaded
    document.fonts.ready.then(() => {
        console.log('Noto Serif Bengali ফন্ট লোড হয়েছে');
    });
    
    // Preload all images
    const images = document.querySelectorAll('img');
    images.forEach(img => {
        const image = new Image();
        image.src = img.src;
    });
});
</script>

</body>
</html>