<?php

require_once 'databaseConnection.php';

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

    // Check if required fields are present and not empty
    if (
        !empty($_POST['reference']) &&
        !empty($_POST['expense']) &&
        !empty($_POST['narration']) &&
        !empty($_POST['category']) &&
        !empty($_POST['date']) &&
        !empty($_POST['amount']) &&
        isset($_POST['status'])
    ) {
        // Sanitize and assign values
        $reference = htmlspecialchars(trim($_POST['reference']));
        $expense = htmlspecialchars(trim($_POST['expense']));
        $narration = htmlspecialchars(trim($_POST['narration']));
        $category = htmlspecialchars(trim($_POST['category']));
        $date = htmlspecialchars(trim($_POST['date']));
        $amount = htmlspecialchars(trim($_POST['amount']));
        $status = htmlspecialchars(trim($_POST['status']));

        // Connect to database
        $mysqli = db_connect();
        if (!$mysqli) {
            echo "Database connection failed: " . $mysqli->connect_error;
            exit;
        }

        // Prepare SQL insert (add all fields you're validating)
        $stmt = $mysqli->prepare("INSERT INTO `addExpense` (`reference`, `expense`, `narration`, `category`, `date`, `amount`, `status`) VALUES (?, ?, ?, ?, ?, ?, ?)");
        if (!$stmt) {
            echo "Error preparing statement: " . $mysqli->error;
            exit;
        }

        // Bind parameters and execute
        $stmt->bind_param("sssssds", $reference, $expense, $narration, $category, $date, $amount, $status);
        if ($stmt->execute()) {
            header("Location: ../expense-list.php");
            exit;
        } else {
            echo "Error inserting record: " . $stmt->error;
        }

        // Cleanup
        $stmt->close();
        $mysqli->close();

    } else {
        echo "All fields are required.";
    }

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