<?php
session_start();
if (!isset($_SESSION['username'])) {
    echo "<script>window.top.location.href='index.php';</script>"; // Redirect parent window to login page
    exit();
}

include 'connect.php'; // Database connection

$message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $expense_name = mysqli_real_escape_string($conn, $_POST['expense_name']);
    $expense_date = mysqli_real_escape_string($conn, $_POST['expense_date']);
    $amount = floatval(str_replace(',', '', $_POST['amount'])); // Remove commas before saving
    $description = mysqli_real_escape_string($conn, $_POST['description']);

    // Insert query
    $query = "INSERT INTO expense (expense_name, expense_date, amount, description) 
              VALUES ('$expense_name', '$expense_date', '$amount', '$description')";

    if (mysqli_query($conn, $query)) {
        $message = '<div class="alert alert-success">Expense added successfully!</div>';
    } else {
        $message = '<div class="alert alert-danger">Error: ' . mysqli_error($conn) . '</div>';
    }

    mysqli_close($conn);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Expense</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script>
        // Function to set the current date as default
        function setCurrentDate() {
            let today = new Date().toISOString().split('T')[0]; // Get today's date in YYYY-MM-DD format
            document.getElementById('expense_date').value = today;
        }

        // Function to format amount on blur (when clicking another textbox)
        function formatAmount(input) {
            let value = input.value.replace(/,/g, ''); // Remove existing commas
            let floatValue = parseFloat(value);

            if (!isNaN(floatValue)) {
                input.value = floatValue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
            }
        }
    </script>
</head>
<body onload="setCurrentDate()">
    <div class="container mt-5">
        <h2 class="mb-4">Add New Expense</h2>

        <?php echo $message; ?>

        <form action="" method="POST">
            <div class="mb-3">
                <label for="expense_name" class="form-label">Expense Name:</label>
                <input type="text" class="form-control" id="expense_name" name="expense_name" required>
            </div>

            <div class="mb-3">
                <label for="expense_date" class="form-label">Expense Date:</label>
                <input type="date" class="form-control" id="expense_date" name="expense_date" required>
            </div>

            <div class="mb-3">
                <label for="amount" class="form-label">Amount:</label>
                <input type="text" class="form-control" id="amount" name="amount" onblur="formatAmount(this)" required>
            </div>

            <div class="mb-3">
                <label for="description" class="form-label">Description:</label>
                <textarea class="form-control" id="description" name="description" rows="3"></textarea>
            </div>

            <button type="submit" class="btn btn-primary">Submit Expense</button>
        </form>
    </div>
</body>
</html>
