<?php
include 'api_helper.php';

$apiBase = "https://blogsystem.online/api/blogs";

// get current domain (for multi-domain API)
$currentDomain = $_SERVER['HTTP_HOST'];

$params = [
    'domain' => $currentDomain,
    'limit'  => 12,
    'page'   => 1
];

$response = callAPI($apiBase, 'GET', $params);

$blogs = (!empty($response['success']) && !empty($response['data'])) 
            ? $response['data'] 
            : [];
?>

<?php include 'header.php'; ?>

<main>
<section class="blog_area section-padding">
<div class="container">
<div class="row">

    <!-- Main Blog Column -->
    <div class="col-lg-8 mb-5 mb-lg-0">
        <div class="blog_left_sidebar">

            <?php if (empty($blogs)): ?>
                <p>No blogs found.</p>

            <?php else: ?>
                <?php foreach ($blogs as $row): ?>

                    <?php
                        $date = date('d', strtotime($row['blog_date']));
                        $month = date('M', strtotime($row['blog_date']));
                    ?>

                    <article class="blog_item">
                        <div class="blog_item_img">
                            <img src="<?= $row['image_url']; ?>" 
                                 class="card-img rounded-0" 
                                 alt="<?= htmlspecialchars($row['title']) ?>">

                            <a href="<?= $BASE_URL . 'blog-detail/' . urlencode($row['blog_url']) ?>" class="blog_item_date">
                                <h3><?= $date ?></h3>
                                <p><?= $month ?></p>
                            </a>
                        </div>

                        <div class="blog_details">
                          <a class="d-inline-block" href="<?= $BASE_URL . 'blog-detail/' . urlencode($row['blog_url']) ?>">

                                <h2><?= htmlspecialchars($row['title']) ?></h2>
                            </a>

                            <p><?= htmlspecialchars($row['short_desc']) ?></p>

                            <ul class="blog-info-link">
                                <li><a href="#"><i class="fa fa-user"></i> <?= htmlspecialchars($row['cat_name']) ?></a></li>
                                <li><a href="#"><i class="fa fa-comments"></i> 0 Comments</a></li>
                            </ul>
                        </div>
                    </article>

                <?php endforeach; ?>
            <?php endif; ?>

        </div>
    </div>

    <!-- Sidebar -->
    <div class="col-lg-4">
        <?php include 'sidebar.php'; ?>
    </div>

</div>
</div>
</section>
</main>

<?php include 'footer.php'; ?>
