<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'db_config.php';

// Check for $pdo from db_config.php
if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection variable \$pdo not found in db_config.php"]);
    exit();
}

try {
    $stmt = $pdo->query("SELECT * FROM expenses ORDER BY id DESC");
    $expenses = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Ensure correct data types for JSON
    foreach ($expenses as &$row) {
        $row['id'] = (int)$row['id'];
        $row['amount'] = (double)$row['amount'];
    }
    
    echo json_encode(["status" => "success", "data" => $expenses]);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "SQL Error: " . $e->getMessage()]);
}
?>