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

if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(["status" => "error", "message" => "Database connection variable \$pdo not found"]);
    exit();
}

$id = $_POST['id'] ?? null;
$head = $_POST['head'] ?? '';
$description = $_POST['description'] ?? '';
$amount = $_POST['amount'] ?? 0;
$status = $_POST['status'] ?? 'Pending';

if (empty($head)) {
    echo json_encode(["status" => "error", "message" => "Head is required"]);
    exit();
}

try {
    if ($id) {
        $stmt = $pdo->prepare("UPDATE expenses SET head=?, description=?, amount=?, status=? WHERE id=?");
        $stmt->execute([$head, $description, $amount, $status, $id]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO expenses (head, description, amount, status) VALUES (?, ?, ?, ?)");
        $stmt->execute([$head, $description, $amount, $status]);
    }
    echo json_encode(["status" => "success", "message" => "Operation successful"]);
} catch (PDOException $e) {
    echo json_encode(["status" => "error", "message" => "Database error: " . $e->getMessage()]);
}
?>