<?php
require_once '../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = getInput();

try {
    $db = getDB();

    switch ($method) {
        case 'GET':
            // Get all expenses
            $stmt = $db->query("SELECT * FROM expenses ORDER BY expense_date DESC, created_at DESC");
            sendJson($stmt->fetchAll());
            break;

        case 'POST':
            // Add new expense
            $stmt = $db->prepare("INSERT INTO expenses
                (category, description, amount, expense_date)
                VALUES (?, ?, ?, ?)");
            $stmt->execute([
                $input['category'] ?? 'other',
                $input['description'] ?? '',
                $input['amount'] ?? 0,
                $input['expenseDate'] ?? date('Y-m-d'),
            ]);
            sendJson(['success' => true, 'id' => $db->lastInsertId()]);
            break;

        case 'DELETE':
            // Delete expense
            $id = $_GET['id'] ?? 0;
            $stmt = $db->prepare("DELETE FROM expenses WHERE id = ?");
            $stmt->execute([$id]);
            sendJson(['success' => true]);
            break;

        default:
            sendJson(['error' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    sendJson(['error' => $e->getMessage()], 500);
}
