<?php
require_once '../auth/auth.php';
require_once '../models/db_connection.php';
require_once '../models/expense_model.php';

$newExpense = new Expense($conn);
$balance = $newExpense->getBalance();
$currentBalance = $balance[0]['balance'];
// var_dump($expense);
// die();

if (isset($_POST["addExpense"])) {

    $expense = $_POST["expense"];
    $amount = $_POST["amount"];
    $issuedDate = $_POST["issuedDate"];
    $userID = $_SESSION["user"];
    $narration = $_POST["narration"];
    // var_dump($expense);
    // var_dump($amount);
    // var_dump($issuedDate);
    // var_dump($userID);
    // var_dump($narration);

    $addexp = mysqli_query($conn, "INSERT INTO expenses (expense,ammount,issued_by,issued_date,naration) VALUES ('$expense', '$amount','$userID','$issuedDate','$narration') ");
    if ($addexp) {
        $succ = 'Expense added successfully';
    } else {
        // Output SQL error if the query fails
        $err = "Error: " . mysqli_error($conn);
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loading Spinner</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .loading-message {
            font-size: 24px;
            font-weight: bold;
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column align-items-center justify-content-center vh-100">
        <!-- Bootstrap Spinner -->
        <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem;">
            <span class="visually-hidden">Loading...</span>
        </div>
        <!-- Message -->
        <div class="loading-message">
            Please wait, adding expenses...<br />
            <?php
            if (isset($succ)) {
                echo $succ;
                echo "<script>
          setTimeout(() => {
              window.location.href = 'view_expenses.php';
          }, 3000);
      </script>";
            } else {
                echo $err;
                echo "<script>
          setTimeout(() => {
              window.location.href = 'add_expense.php';
          }, 3000);
      </script>";
            }
            ?>
        </div>
    </div>

    <!-- Bootstrap JS (Optional, for interactive components) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>