<?php
// Sesuaikan dengan koneksi database kamu
include "config/koneksi.php"; // ganti dengan file koneksi kamu jika beda

header('Content-Type: application/json');

$limit = 6;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// 1. Hitung Total Data (Cepat & Ringan)
$queryCount = "SELECT COUNT(*) AS total FROM blog";
$resultCount = mysqli_query($konek, $queryCount);
$rowCount = mysqli_fetch_assoc($resultCount);
$total_data = (int)($rowCount['total'] ?? 0);
$total_pages = ceil($total_data / $limit);

// 2. Tarik Cuma 6 Data Saja!
$queryArticle = "SELECT * FROM blog ORDER BY id_blog DESC LIMIT $limit OFFSET $offset";
$resultArticle = mysqli_query($konek, $queryArticle);

$articles = [];
if ($resultArticle && mysqli_num_rows($resultArticle) > 0) {
    while ($g = mysqli_fetch_array($resultArticle)) {
        $isi_blog = strip_tags($g['isi_blog']);
        
        if (mb_strlen($isi_blog) > 115) {
            $isi = mb_substr($isi_blog, 0, 115);
            $last_space = mb_strrpos($isi, " ");
            $isi = ($last_space !== false) ? mb_substr($isi, 0, $last_space) : $isi;
            $isi .= "...";
        } else {
            $isi = $isi_blog;
        }

        $tgl_posting = function_exists('tgl_indo') ? tgl_indo($g['tgl_posting']) : date('d M Y', strtotime($g['tgl_posting']));
        $url_artikel = htmlspecialchars(($d['alamat_website'] ?? '') . "/article-" . ($g['blog_seo'] ?? ''));
        $url_gambar  = !empty($g['gambar']) ? htmlspecialchars(($d['alamat_website'] ?? '') . "/foto_blog/" . $g['gambar']) : 'assets/img/default-article.jpg';

        $articles[] = [
            'judul' => htmlspecialchars($g['judul_blog'] ?? '', ENT_QUOTES, 'UTF-8'),
            'isi'   => htmlspecialchars($isi, ENT_QUOTES, 'UTF-8'),
            'tgl'   => $tgl_posting,
            'link'  => $url_artikel,
            'img'   => $url_gambar
        ];
    }
}

echo json_encode([
    'status'       => 'success',
    'current_page' => $page,
    'total_pages'  => $total_pages,
    'articles'     => $articles
]);
?>