<?php
require_once 'db.php';
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$instansi_id = $_SESSION['instansi_id'];

$media = isset($_GET['media']) ? trim($_GET['media']) : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('-7 days'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

if (empty($media)) {
    die("Pilih media terlebih dahulu.");
}

// Ambil info instansi
$stmt_inst = $pdo->prepare("SELECT nama_instansi, logo_path FROM instansi WHERE id = ?");
$stmt_inst->execute([$instansi_id]);
$inst_data = $stmt_inst->fetch(PDO::FETCH_ASSOC);
$nama_instansi = $inst_data['nama_instansi'] ?? "Instansi ID $instansi_id";
$logo_path = !empty($inst_data['logo_path']) ? $inst_data['logo_path'] : '';

// Query berita untuk media dan tanggal tersebut
$stmt = $pdo->prepare("SELECT id, judul, link, thumbnail, tanggal, cuplikan, ringkasan FROM berita WHERE instansi_id = ? AND sumber = ? AND DATE(tanggal) >= ? AND DATE(tanggal) <= ? ORDER BY tanggal DESC");
$stmt->execute([$instansi_id, $media, $start_date, $end_date]);
$berita = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fungsi scraping OG Image jika thumbnail kosong
function fetch_og_image($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3); // Timeout 3 detik agar tidak terlalu lama
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36');
    $html = curl_exec($ch);
    curl_close($ch);
    
    if($html) {
        if(preg_match('/<meta\s+(?:property|name)=["\']og:image["\']\s+content=["\']([^"\']+)["\']/i', $html, $matches)) {
            return $matches[1];
        }
        if(preg_match('/<meta\s+content=["\']([^"\']+)["\']\s+(?:property|name)=["\']og:image["\']/i', $html, $matches)) {
            return $matches[1];
        }
    }
    return '';
}

// (Fungsi scraping dihapus, beralih ke layout ringkasan)

// Proses thumbnail kosong
foreach($berita as &$b) {
    if(empty($b['thumbnail']) && !empty($b['link'])) {
        $og_img = fetch_og_image($b['link']);
        if(!empty($og_img)) {
            $b['thumbnail'] = $og_img;
            // Opsi: Update ke database agar next load lebih cepat
            $stmt_upd = $pdo->prepare("UPDATE berita SET thumbnail = ? WHERE id = ?");
            $stmt_upd->execute([$og_img, $b['id']]);
        }
    }
}
unset($b); // un-reference

// Helper fungsi bulan indonesia
function tgl_indo($tanggal){
    $bulan = array (1 => 'Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember');
    $pecahkan = explode('-', $tanggal);
    return $pecahkan[2] . ' ' . $bulan[ (int)$pecahkan[1] ] . ' ' . $pecahkan[0];
}

$start_indo = tgl_indo($start_date);
$end_indo = tgl_indo($end_date);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Koran: <?= htmlspecialchars($media) ?> (<?= htmlspecialchars($start_date) ?>)</title>
    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=Lora:ital,wght@0,400;0,600;1,400&family=Oswald:wght@400;600&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg-color: #ffffff;
            --text-main: #333333;
            --newspaper-red: #c92228;
            --newspaper-blue: #1c3b7a;
            --newspaper-yellow: #f1c40f;
            --border-color: #222;
        }
        body {
            font-family: 'Lora', serif;
            background-color: #d1d5db;
            color: var(--text-main);
            margin: 0;
            padding: 20px 0;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .page {
            width: 210mm;
            min-height: 297mm;
            background-color: var(--bg-color);
            box-shadow: 0 10px 25px rgba(0,0,0,0.15);
            margin: 0 auto 30px auto;
            padding: 15mm;
            box-sizing: border-box;
            position: relative;
            page-break-after: always;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }
        
        /* Top Header */
        .masthead-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 2px solid var(--border-color);
            padding-bottom: 5px;
            margin-bottom: 15px;
            font-family: 'Oswald', sans-serif;
            font-weight: 600;
            font-size: 0.9rem;
            text-transform: uppercase;
        }
        .masthead-category {
            display: flex;
            align-items: stretch;
            background-color: var(--newspaper-blue);
            color: white;
            margin-bottom: 20px;
            font-family: 'Oswald', sans-serif;
            height: 35px;
        }
        .category-red {
            background-color: var(--newspaper-red);
            padding: 0 15px;
            display: flex;
            align-items: center;
            font-size: 1.2rem;
            font-weight: 600;
        }
        
        /* Typography */
        h1, h2, h3, h4, h5 { font-family: 'Playfair Display', serif; margin: 0; }
        .hero-title {
            font-size: 4rem;
            font-weight: 900;
            line-height: 0.95;
            text-transform: uppercase;
            margin-bottom: 10px;
            color: #111;
        }
        .section-title {
            font-family: 'Oswald', sans-serif;
            font-size: 1.6rem;
            text-transform: uppercase;
            margin-bottom: 10px;
            font-weight: 600;
        }
        .article-title {
            font-size: 1.4rem;
            line-height: 1.1;
            margin-bottom: 8px;
            font-weight: 700;
        }
        .article-text {
            font-size: 0.95rem;
            line-height: 1.5;
            text-align: justify;
            margin-bottom: 10px;
        }
        .quote-text {
            font-size: 1.2rem;
            font-style: italic;
            color: var(--newspaper-red);
            font-weight: 600;
            margin: 15px 0;
            line-height: 1.3;
        }
        
        /* Grid Layouts */
        .grid-3-col {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            margin-top: 20px;
            border-top: 2px solid #ccc;
            padding-top: 20px;
            flex-grow: 1;
        }
        .grid-2-col {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 20px;
            margin-top: 20px;
            border-top: 2px solid #ccc;
            padding-top: 20px;
            flex-grow: 1;
        }
        .col-border-right {
            border-right: 1px solid #ccc;
            padding-right: 15px;
        }
        
        /* Elements */
        .img-placeholder {
            background-color: #ccc;
            width: 100%;
            display: block;
            margin-bottom: 10px;
            object-fit: cover;
            filter: grayscale(100%);
        }
        .hero-img {
            width: 100%;
            height: 250px;
        }
        .red-box {
            background-color: var(--newspaper-red);
            color: white;
            padding: 15px;
            margin-top: 15px;
        }
        .red-box h4 {
            font-family: 'Oswald', sans-serif;
            color: var(--newspaper-yellow);
            font-size: 1.4rem;
            margin-bottom: 10px;
            text-transform: uppercase;
        }
        .red-box .article-text { color: white; margin-bottom: 0; }
        
        /* Print Button */
        .print-btn {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background: var(--newspaper-blue);
            color: white;
            border: none;
            padding: 15px 25px;
            border-radius: 5px;
            font-size: 1.1rem;
            font-family: 'Oswald', sans-serif;
            cursor: pointer;
            box-shadow: 0 5px 15px rgba(28, 59, 122, 0.4);
            z-index: 1000;
        }
        
        @media print {
            @page { size: A4 portrait; margin: 0; }
            body { background: white; padding: 0; margin: 0; }
            .page { max-width: 210mm; width: 210mm; box-shadow: none; margin: 0; border: none; min-height: 297mm; }
            .print-btn, .no-print { display: none !important; }
        }
    </style>
</head>
<body>

    <div class="no-print" style="position: fixed; bottom: 30px; left: 30px; background: white; padding: 15px; border-radius: 5px; box-shadow: 0 5px 15px rgba(0,0,0,0.2); z-index: 1000; font-family: 'Oswald', sans-serif;">
        <i class="fas fa-info-circle me-1" style="color: var(--text-title);"></i> <strong style="color: var(--text-main);">Tips:</strong> Klik dan geser foto berita untuk menyesuaikan bagian yang terpotong (Pan Crop).
    </div>

    <button class="print-btn" onclick="window.print()"><i class="fas fa-print me-2"></i> CETAK KORAN</button>

    <?php
    function get_summary($b, $length = 300) {
        $text = !empty($b['ringkasan']) ? $b['ringkasan'] : $b['cuplikan'];
        $text = preg_replace('/^MEDIA\s+CENTER\s+BANJARBARU\s*(?:&#8211;|-|–|—)\s*/i', '', trim($text));
        $text = preg_replace('/The post.*/i', '', $text);
        $text = strip_tags($text);
        
        if(strlen($text) > $length) {
            $text = substr($text, 0, $length) . '...';
        }
        return htmlspecialchars($text);
    }

    if(empty($berita)): 
    ?>
        <div class="page">
            <div class="masthead-top">
                <span><?= strtoupper(date('d.m.Y / l', strtotime($start_date))) ?></span>
                <span>VOL. 51 / EST. 2026</span>
            </div>
            <div class="masthead-category">
                <div class="category-red">MEDIA CENTER NEWS</div>
            </div>
            <div style="text-align: center; padding: 50px; font-family: 'Oswald', sans-serif; color: var(--text-main);">
                <h2>TIDAK ADA BERITA DITEMUKAN</h2>
            </div>
        </div>
    <?php 
    else: 
        // Chunk articles, max 6 per page
        $chunks = array_chunk($berita, 6);
        foreach($chunks as $page_index => $chunk):
            $is_template_a = ($page_index % 2 == 0); // Alternate templates
    ?>
            <div class="page">
                <?php if($is_template_a): ?>
                    <!-- TEMPLATE A: Politics News Style -->
                    <div class="masthead-top">
                        <span><?= strtoupper(date('d.m.Y / l', strtotime($chunk[0]['tanggal']))) ?></span>
                        <span>VOL. 51 / EST. 2026</span>
                    </div>
                    <div class="masthead-category">
                        <div class="category-red">MEDIA CENTER NEWS</div>
                    </div>
                    
                    <?php if(isset($chunk[0])): $b = $chunk[0]; ?>
                    <div style="margin-bottom: 20px;">
                        <h1 class="hero-title" style="font-size: <?= strlen($b['judul']) > 50 ? '3rem' : '4.5rem' ?>;"><?= htmlspecialchars($b['judul']) ?></h1>
                        <?php if(!empty($b['thumbnail'])): ?>
                            <img src="<?= htmlspecialchars($b['thumbnail']) ?>" class="img-placeholder hero-img">
                        <?php endif; ?>
                        <div class="quote-text">
                            <i class="fas fa-quote-left"></i> <?= get_summary($b, 150) ?> <i class="fas fa-quote-right"></i>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="grid-3-col">
                        <div class="col-border-right">
                            <?php if(isset($chunk[1])): $b = $chunk[1]; ?>
                            <div style="margin-bottom: 20px;">
                                <h3 class="section-title">SO WHAT NEXT?</h3>
                                <h4 class="article-title"><?= htmlspecialchars($b['judul']) ?></h4>
                                <div class="article-text"><?= get_summary($b, 250) ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if(isset($chunk[2])): $b = $chunk[2]; ?>
                            <div>
                                <h3 class="section-title">TODAY'S NEWS</h3>
                                <h4 class="article-title"><?= htmlspecialchars($b['judul']) ?></h4>
                                <div class="article-text"><?= get_summary($b, 250) ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-border-right">
                            <?php if(isset($chunk[3])): $b = $chunk[3]; ?>
                                <?php if(!empty($b['thumbnail'])): ?>
                                    <img src="<?= htmlspecialchars($b['thumbnail']) ?>" class="img-placeholder" style="height: 200px;">
                                <?php endif; ?>
                                <h4 class="article-title"><?= htmlspecialchars($b['judul']) ?></h4>
                                <div class="article-text"><?= get_summary($b, 350) ?></div>
                            <?php endif; ?>
                        </div>
                        
                        <div>
                            <?php if(isset($chunk[4])): $b = $chunk[4]; ?>
                                <h4 class="article-title"><?= htmlspecialchars($b['judul']) ?></h4>
                                <div class="article-text"><?= get_summary($b, 200) ?></div>
                            <?php endif; ?>
                            
                            <?php if(isset($chunk[5])): $b = $chunk[5]; ?>
                            <div class="red-box">
                                <h4>DID YOU KNOW THAT...</h4>
                                <div class="article-text" style="font-size: 0.95rem; font-style: italic;">
                                    <strong><?= htmlspecialchars($b['judul']) ?></strong><br>
                                    <?= get_summary($b, 200) ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                <?php else: ?>
                    <!-- TEMPLATE B: Financial News Style -->
                    <div class="masthead-top">
                        <span><?= strtoupper(date('d.m.Y / l', strtotime($chunk[0]['tanggal']))) ?></span>
                        <span>SPECIAL EDITION</span>
                    </div>
                    <div class="masthead-category">
                        <div class="category-red" style="background-color: var(--newspaper-blue);">HEADLINES</div>
                    </div>
                    
                    <?php if(isset($chunk[0])): $b = $chunk[0]; ?>
                    <h1 class="hero-title" style="font-size: 3.5rem; border-bottom: 3px solid #111; padding-bottom: 10px; margin-bottom: 20px;"><?= htmlspecialchars($b['judul']) ?></h1>
                    <?php endif; ?>
                    
                    <div class="grid-2-col" style="border-top: none; padding-top: 0; margin-top: 0;">
                        <div class="col-border-right">
                            <?php if(isset($chunk[0])): $b = $chunk[0]; ?>
                                <?php if(!empty($b['thumbnail'])): ?>
                                    <img src="<?= htmlspecialchars($b['thumbnail']) ?>" class="img-placeholder" style="height: 200px;">
                                <?php endif; ?>
                                <div class="article-text" style="column-count: 2; column-gap: 15px; margin-top: 15px;">
                                    <?= get_summary($b, 500) ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php if(isset($chunk[1])): $b = $chunk[1]; ?>
                            <div style="margin-top: 30px;">
                                <h3 class="section-title">ABOUT LOKAL</h3>
                                <h4 class="article-title"><?= htmlspecialchars($b['judul']) ?></h4>
                                <div class="article-text"><?= get_summary($b, 300) ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if(isset($chunk[2])): $b = $chunk[2]; ?>
                            <div style="border: 4px solid var(--newspaper-yellow); padding: 15px; margin-top: 20px;">
                                <h4 class="article-title" style="text-align: center;"><?= htmlspecialchars($b['judul']) ?></h4>
                                <div class="article-text" style="text-align: center; font-style: italic;">
                                    <?= get_summary($b, 200) ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div>
                            <?php if(isset($chunk[3])): $b = $chunk[3]; ?>
                            <div class="quote-text" style="margin-top: 0;">
                                <i class="fas fa-quote-left"></i> <?= get_summary($b, 100) ?> <i class="fas fa-quote-right"></i>
                            </div>
                            <h4 class="article-title"><?= htmlspecialchars($b['judul']) ?></h4>
                            <div class="article-text" style="margin-bottom: 30px;"><?= get_summary($b, 300) ?></div>
                            <?php endif; ?>
                            
                            <?php if(isset($chunk[4])): $b = $chunk[4]; ?>
                            <h3 class="section-title" style="border-top: 2px solid #ccc; padding-top: 15px;">WHAT PEOPLE THINK</h3>
                            <?php if(!empty($b['thumbnail'])): ?>
                                <img src="<?= htmlspecialchars($b['thumbnail']) ?>" class="img-placeholder" style="height: 150px; margin-bottom: 15px;">
                            <?php endif; ?>
                            <h4 class="article-title"><?= htmlspecialchars($b['judul']) ?></h4>
                            <div class="article-text"><?= get_summary($b, 300) ?></div>
                            <?php endif; ?>
                            
                            <?php if(isset($chunk[5])): $b = $chunk[5]; ?>
                            <h4 class="article-title" style="margin-top: 20px;"><?= htmlspecialchars($b['judul']) ?></h4>
                            <div class="article-text"><?= get_summary($b, 150) ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <script>
    document.addEventListener('DOMContentLoaded', () => {
        const images = document.querySelectorAll('.img-placeholder');
        
        images.forEach(img => {
            img.draggable = false;
            img.style.cursor = 'grab';
            
            let posX = 50;
            let posY = 50;
            let isDragging = false;
            let startClientX = 0;
            let startClientY = 0;

            const onStart = (clientX, clientY) => {
                isDragging = true;
                img.style.cursor = 'grabbing';
                startClientX = clientX;
                startClientY = clientY;
            };

            const onMove = (clientX, clientY) => {
                if (!isDragging) return;
                
                const dx = clientX - startClientX;
                const dy = clientY - startClientY;
                
                // Sensitivity 0.3
                posX -= dx * 0.3; 
                posY -= dy * 0.3;
                
                posX = Math.max(0, Math.min(100, posX));
                posY = Math.max(0, Math.min(100, posY));
                
                img.style.objectPosition = `${posX}% ${posY}%`;
                
                startClientX = clientX;
                startClientY = clientY;
            };

            const onEnd = () => {
                if (isDragging) {
                    isDragging = false;
                    img.style.cursor = 'grab';
                }
            };

            img.addEventListener('mousedown', (e) => {
                e.preventDefault(); 
                onStart(e.clientX, e.clientY);
            });
            window.addEventListener('mousemove', (e) => onMove(e.clientX, e.clientY));
            window.addEventListener('mouseup', onEnd);
            
            img.addEventListener('touchstart', (e) => onStart(e.touches[0].clientX, e.touches[0].clientY), {passive: false});
            window.addEventListener('touchmove', (e) => {
                if(isDragging && e.target === img) {
                    e.preventDefault(); 
                    onMove(e.touches[0].clientX, e.touches[0].clientY);
                }
            }, {passive: false});
            window.addEventListener('touchend', onEnd);
        });
    });
    </script>
</body>
</html>
