<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// Handle form submission
$message = '';
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    $date = $_POST['date'] ?? date('Y-m-d');
    $amount = floatval($_POST['amount'] ?? 0);
    $description = $conn->real_escape_string($_POST['description'] ?? '');
    $recorded_by = $_SESSION['username'] ?? 'Unknown';

    if($amount > 0 && $description){
        $insert = $conn->query("INSERT INTO petty_cash (date, amount, description, recorded_by) 
                                VALUES ('$date', '$amount', '$description', '$recorded_by')");
        if($insert){
            $message = "<div class='alert alert-success'>Petty Cash entry added successfully!</div>";
        } else {
            $message = "<div class='alert alert-danger'>Error: ".$conn->error."</div>";
        }
    } else {
        $message = "<div class='alert alert-warning'>Please enter valid amount and description.</div>";
    }
}
?>

<div class="container mt-4">
    <button class="btn btn-secondary mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h3><i class="fa fa-wallet"></i> Add Petty Cash Entry</h3>
    <hr>

    <?= $message ?>

    <div class="card p-3">
        <form method="post">
            <div class="mb-3">
                <label>Date</label>
                <input type="date" name="date" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="mb-3">
                <label>Amount</label>
                <input type="number" step="0.01" name="amount" class="form-control" required>
            </div>
            <div class="mb-3">
                <label>Description</label>
                <textarea name="description" class="form-control" rows="3" required></textarea>
            </div>
            <button type="submit" class="btn btn-success">
                <i class="fa fa-plus"></i> Add Entry
            </button>
        </form>
    </div>
</div>

<?php include 'includes/footer.php'; ?>