<?php include 'db.php'; 
include 'auth.php';
require_right('Add Expense'); ?>


<!DOCTYPE html>
<html>
<head>
    <title>Add Expense</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .select2-container { width: 100% !important; }
    </style>
</head>
<body class="p-4">

<h4>Add New Expense</h4>
<form method="POST">
    <div class="mb-3">
        <label>Expense Account</label>
        <select name="account_id" class="form-select select2" required>
            <option value="">Select Expense Account</option>
            <?php
            $res = mysqli_query($conn, "SELECT id, name FROM expense_accounts");
            while ($row = mysqli_fetch_assoc($res)) {
                echo "<option value='{$row['id']}'>{$row['name']}</option>";
            }
            ?>
        </select>
    </div>
    <div class="mb-3">
        <label>Amount</label>
        <input type="number" step="0.01" name="amount" class="form-control" required placeholder="Amount">
    </div>
    <div class="mb-3">
        <label>Remarks</label>
        <textarea name="remarks" class="form-control" placeholder="Remarks"></textarea>
    </div>
    <button type="submit" name="save_expense" class="btn btn-primary">Save</button>
</form>

<?php
if (isset($_POST['save_expense'])) {
    $account = mysqli_real_escape_string($conn, $_POST['account_id']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $remarks = mysqli_real_escape_string($conn, $_POST['remarks']);
    mysqli_query($conn, "INSERT INTO expenses (account_id, amount, remarks) VALUES ('$account', '$amount', '$remarks')");

    // SweetAlert2 on success and close modal/refresh
    echo "<script>
        window.onload = function() {
            Swal.fire({
                icon: 'success',
                title: 'Expense Added!',
                text: 'The expense has been successfully saved.',
                confirmButtonText: 'OK'
            }).then(() => {
                window.parent.location.reload();
            });
        };
    </script>";
}
?>

<!-- JS Includes -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="assets/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $('.select2').select2();
</script>

</body>
</html>
