<?php
// 1. Allow React to access this script (CORS Headers)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");

// 2. Connect to the Database
include_once 'db_connect.php';

// 3. Prepare the Query
// We select all news items, ordered by date (newest first)
$query = "SELECT id, title, category, author, date, excerpt, image_url FROM news ORDER BY date DESC";
$result = $conn->query($query);

// 4. Check if data exists
if ($result->num_rows > 0) {
    $news_array = array();

    // 5. Loop through results and add to array
    while($row = $result->fetch_assoc()) {
        // Fix image path if strictly relative (optional, depends on your setup)
        // If image_url is "/assets/...", it works fine on frontend.
        
        $news_item = array(
            "id" => $row['id'],
            "title" => $row['title'],
            "category" => $row['category'],
            "author" => $row['author'],
            "date" => date("M d, Y", strtotime($row['date'])), // Format date nicely (e.g. Oct 12, 2025)
            "excerpt" => $row['excerpt'],
            "image" => $row['image_url'] // React expects 'image', DB has 'image_url'
        );

        array_push($news_array, $news_item);
    }

    // 6. Return JSON response
    // http_response_code(200);
    echo json_encode($news_array);

} else {
    // No news found
    echo json_encode(array());
}

// 7. Close connection
$conn->close();
?>