<?php
/**
 * Get News Articles
 */

header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';

$response = ['success' => false, 'data' => [], 'message' => ''];

try {
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $offset = isset($_GET['offset']) ? (int)$_GET['offset'] : 0;

    $sql = "SELECT id, title, slug, summary, featured_image, author_id, views, created_at, published_at 
            FROM news WHERE status = 'published' 
            ORDER BY published_at DESC 
            LIMIT ? OFFSET ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('ii', $limit, $offset);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $news = [];
    while ($article = $result->fetch_assoc()) {
        $news[] = $article;
    }

    $response['success'] = true;
    $response['data'] = $news;
    $response['count'] = count($news);

} catch (Exception $e) {
    http_response_code(500);
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
$conn->close();
?>
