<?php
// Filename: news.php
require 'config.php';

// --- 1. SETTINGS & HEADERS ---
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set('Asia/Kuala_Lumpur');
requireLogin();

$s_name = getSetting('school_name', 'SAS');
$theme_gradient = getHeaderTheme(); 

// --- 2. CONFIGURATION FOR TYPES ---
$type = $_GET['type'] ?? 'pengumuman'; // Default
$sources = [
    'pengumuman' => [
        'title' => 'Pengumuman',
        'url'   => 'https://www.moe.gov.my/pemberitahuan/pengumuman',
        'cache' => __DIR__ . '/cache_news_pengumuman.json'
    ],
    'surat_siaran' => [
        'title' => 'Surat Siaran',
        'url'   => 'https://www.moe.gov.my/pemberitahuan/surat-siaran',
        'cache' => __DIR__ . '/cache_news_surat.json'
    ]
];

// Validate type, fallback to default if invalid
if (!array_key_exists($type, $sources)) {
    $type = 'pengumuman';
}

$current_config = $sources[$type];
$cache_file = $current_config['cache'];
$cache_time = 3600; // 1 Hour

// --- 3. ROBUST SCRAPING ENGINE ---
function fetchMoeData($url) {
    $data = [];

    // 1. Curl Setup
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 25);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $html = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // 2. Parse HTML
    if ($http_code === 200 && !empty($html)) {
        libxml_use_internal_errors(true);
        $dom = new DOMDocument();
        @$dom->loadHTML($html);
        $xpath = new DOMXPath($dom);

        // Find ALL table rows (works for both Pengumuman & Surat Siaran)
        $rows = $xpath->query("//tr");

        foreach ($rows as $row) {
            // Ignore headers
            if ($row->getElementsByTagName('th')->length > 0) continue;

            // Find Link (Title)
            $linkNode = $xpath->query(".//a", $row)->item(0);
            
            if ($linkNode) {
                $title = trim($linkNode->nodeValue);
                $href  = trim($linkNode->getAttribute('href'));
                
                if (strpos($href, 'http') === false) {
                    $href = "https://www.moe.gov.my" . $href;
                }

                // Find Date (Logic: Look for digits in last columns)
                $cols = $xpath->query(".//td", $row);
                $dateRaw = "";
                
                if ($cols->length > 0) {
                    // Usually date is in the last column
                    $lastCol = $cols->item($cols->length - 1)->nodeValue;
                    // Or second to last
                    $secondLast = ($cols->length > 1) ? $cols->item($cols->length - 2)->nodeValue : '';

                    if (preg_match('/\d{4}/', $lastCol)) $dateRaw = trim($lastCol);
                    elseif (preg_match('/\d{4}/', $secondLast)) $dateRaw = trim($secondLast);
                }

                // Parse Date
                $ts = time();
                if ($dateRaw) {
                    $malay = ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'];
                    $eng   = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                    $dateClean = str_replace($malay, $eng, $dateRaw);
                    $tsCheck = strtotime($dateClean);
                    if ($tsCheck) $ts = $tsCheck;
                }

                $title = preg_replace('/\s+/', ' ', $title);

                if (strlen($title) > 5) {
                    $data[] = [
                        'title' => $title,
                        'link'  => $href,
                        'date'  => $ts,
                        'ago'   => date('d M Y', $ts)
                    ];
                }
            }
            if (count($data) >= 20) break; // Limit 20 items
        }
        libxml_clear_errors();
    }
    return $data;
}

// --- 4. LOGIC CONTROLLER ---
$items = [];
$last_updated = "Belum Dikemaskini";

// Force Refresh
if (isset($_GET['refresh']) && $_GET['refresh'] == 'true') {
    $fetched = fetchMoeData($current_config['url']);
    if (!empty($fetched)) {
        file_put_contents($cache_file, json_encode(['time' => time(), 'items' => $fetched]));
    }
    header("Location: news.php?type=" . $type);
    exit;
}

// Load Cache or Fetch
if (file_exists($cache_file)) {
    $cached = json_decode(file_get_contents($cache_file), true);
    if ($cached) {
        $items = $cached['items'] ?? [];
        $last_updated = date('d M h:i A', $cached['time'] ?? time());
        
        // Auto-refresh expired
        if ((time() - ($cached['time'] ?? 0)) > $cache_time) {
            // Note: In auto-refresh, we can't show a loader easily without AJAX, 
            // but this usually happens fast enough or we accept the delay.
            $fetched = fetchMoeData($current_config['url']);
            if (!empty($fetched)) {
                $items = $fetched;
                $last_updated = "Baru Sebentar Tadi";
                file_put_contents($cache_file, json_encode(['time' => time(), 'items' => $fetched]));
            }
        }
    }
} else {
    // First run
    $items = fetchMoeData($current_config['url']);
    if (!empty($items)) {
        $last_updated = "Baru Sebentar Tadi";
        file_put_contents($cache_file, json_encode(['time' => time(), 'items' => $items]));
    }
}

// Fallback
if (empty($items)) {
    $items = [['title' => 'Tiada data atau sambungan gagal. Tekan Refresh.', 'link' => '#', 'date' => time(), 'ago' => 'Ralat']];
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <title>Portal KPM - <?= htmlspecialchars($s_name) ?></title>
    
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css">

    <style>
        :root { --primary-grad: <?= $theme_gradient ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }
        
        .app-header { 
            background: var(--primary-grad); padding: 20px 20px 80px 20px; 
            border-radius: 0 0 35px 35px; color: white; text-align: center; position: relative;
        }
        
        .content-sheet { margin-top: -50px; padding: 0 20px; }
        
        .news-card {
            background: white; border-radius: 16px; padding: 16px; margin-bottom: 12px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.02);
            display: flex; gap: 15px; align-items: start;
            text-decoration: none; color: inherit; transition: transform 0.2s;
        }
        .news-card:active { transform: scale(0.98); background: #f8fafc; }
        
        .date-badge {
            background: #f1f5f9; color: #475569; border-radius: 12px;
            width: 55px; height: 55px; display: flex; flex-direction: column;
            align-items: center; justify-content: center; flex-shrink: 0;
            line-height: 1; border: 1px solid #e2e8f0;
        }
        .date-day { font-size: 1.2rem; font-weight: 800; color: #1e293b; }
        .date-mon { font-size: 0.65rem; font-weight: 700; text-transform: uppercase; margin-top: 3px; }
        
        .news-info { flex-grow: 1; }
        .news-title { font-size: 0.9rem; font-weight: 700; color: #1e293b; line-height: 1.4; margin-bottom: 6px; }
        .news-meta { font-size: 0.75rem; color: #64748b; display: flex; align-items: center; gap: 5px; }
        
        .tag-new { background: #fee2e2; color: #ef4444; font-size: 0.6rem; padding: 2px 6px; border-radius: 4px; font-weight: 800; }

        /* Dropdown Styling */
        .source-select {
            background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3);
            color: white; border-radius: 20px; padding: 5px 15px; font-size: 0.9rem;
            font-weight: 600; cursor: pointer; text-align: center;
            appearance: none; -webkit-appearance: none;
            background-image: url("data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23FFFFFF%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E");
            background-repeat: no-repeat; background-position: right 10px top 50%; background-size: 10px auto;
            padding-right: 30px;
        }
        .source-select option { color: #333; background: white; }

        .refresh-btn {
            position: absolute; top: 20px; right: 20px;
            background: rgba(255,255,255,0.2); border: none; color: white;
            width: 40px; height: 40px; border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            backdrop-filter: blur(5px); cursor: pointer; transition: 0.2s;
        }
        .refresh-btn:active { transform: rotate(180deg); background: rgba(255,255,255,0.4); }

        /* LOADING OVERLAY STYLES */
        .loading-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(255,255,255,0.85); z-index: 9999;
            display: flex; flex-direction: column; align-items: center; justify-content: center;
            backdrop-filter: blur(8px);
        }
    </style>
</head>
<body>

    <div id="loadingOverlay" class="loading-overlay d-none">
        <div class="spinner-border text-primary mb-3" role="status" style="width: 3rem; height: 3rem;"></div>
        <div class="fw-bold text-dark animate__animated animate__pulse animate__infinite">Sedang Mengemaskini...</div>
        <div class="small text-muted">Mendapatkan data dari KPM</div>
    </div>

    <div class="app-header">
        <a href="dashboard.php" class="text-white position-absolute top-0 start-0 mt-3 ms-3"><i class="bi bi-arrow-left fs-3"></i></a>
        
        <a href="#" onclick="triggerRefresh('news.php?type=<?= $type ?>&refresh=true')" class="refresh-btn"><i class="bi bi-arrow-clockwise fs-5"></i></a>

        <div class="mb-2 opacity-75 small text-uppercase fw-bold" style="letter-spacing:1px;">Portal KPM</div>
        
        <div class="d-inline-block position-relative">
            <select class="source-select" onchange="triggerRefresh('news.php?type='+this.value)">
                <option value="pengumuman" <?= $type == 'pengumuman' ? 'selected' : '' ?>>Pengumuman</option>
                <option value="surat_siaran" <?= $type == 'surat_siaran' ? 'selected' : '' ?>>Surat Siaran</option>
            </select>
        </div>

        <div class="opacity-75 small mt-2"><i class="bi bi-clock me-1"></i> Dikemaskini: <?= htmlspecialchars($last_updated) ?></div>
    </div>

    <div class="content-sheet">
        <div class="small fw-bold text-muted text-uppercase mb-3 ps-1" style="font-size: 0.75rem; letter-spacing: 0.5px;">
            Senarai <?= htmlspecialchars($current_config['title']) ?>
        </div>

        <?php foreach($items as $index => $item): 
            $day = date('d', $item['date']);
            $mon = date('M', $item['date']);
            $is_new = (time() - $item['date']) < (86400 * 7); // 7 Days considered new
            $delay = $index * 0.05;
        ?>
            <a href="<?= htmlspecialchars($item['link']) ?>" target="_blank" rel="noopener noreferrer" class="news-card animate__animated animate__fadeInUp" style="animation-delay: <?= $delay ?>s;">
                <div class="date-badge">
                    <span class="date-day"><?= $day ?></span>
                    <span class="date-mon"><?= $mon ?></span>
                </div>
                <div class="news-info">
                    <div class="news-title"><?= htmlspecialchars($item['title']) ?></div>
                    <div class="news-meta">
                        <span><?= $type == 'surat_siaran' ? 'Surat Pekeliling' : 'Kenyataan Media' ?></span>
                        <?php if($is_new): ?><span class="tag-new ms-2">BARU</span><?php endif; ?>
                        <i class="bi bi-chevron-right ms-auto opacity-50"></i>
                    </div>
                </div>
            </a>
        <?php endforeach; ?>
        
        <div class="text-center mt-4 mb-3">
            <small class="text-muted opacity-50" style="font-size: 0.65rem;">
                Sumber: Laman Web Rasmi KPM<br>Sistem scraping automatik
            </small>
        </div>
    </div>

    <?php include 'menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        function triggerRefresh(url) {
            // Show the loading overlay
            document.getElementById('loadingOverlay').classList.remove('d-none');
            // Navigate to the URL after a tiny delay to ensure UI updates
            setTimeout(() => {
                window.location.href = url;
            }, 50);
        }
    </script>
</body>
</html>