<?php
include('db_connection.php');

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Validate inputs
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
    $date = isset($_POST['date']) ? $_POST['date'] : '';
    $term = isset($_POST['term']) ? $_POST['term'] : '';
    $session = isset($_POST['session']) ? $_POST['session'] : '';

    // Basic validation
    if (empty($description) || empty($amount) || empty($date)) {
        die("Please fill all required fields.");
    }

    // Prepare statement
    $stmt = $conn->prepare("
        INSERT INTO expenses (description, amount, date, term, session) 
        VALUES (?, ?, ?, ?, ?)
    ");

    if (!$stmt) {
        die("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("sdsss", $description, $amount, $date, $term, $session);

    if ($stmt->execute()) {
        // ✅ Redirect properly (NO echo before header)
        header('Location: view_transactions.php?success=1');
        exit();
    } else {
        echo "Error inserting data: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();

} else {
    echo "Invalid request.";
}
?>