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


 <div class="page-wrapper" style="margin-left: 250px; padding: 100px;">
     
<div class="page-header d-flex justify-content-between align-items-center">
    <h4 class="page-title">Expense Categories</h4>
</div>

<div class="row">
    <!-- Add Category Form -->
    <div class="col-md-6">
        <form method="POST" class="card card-body">
            <h5>Add Category</h5>
            <div class="mb-2">
                <input type="text" name="category_name" class="form-control" placeholder="Category Name" required>
            </div>
            <button class="btn btn-primary" name="add_category">Add Category</button>
        </form>
    </div>

    <!-- Add Subcategory Form -->
    <div class="col-md-6">
        <form method="POST" class="card card-body">
            <h5>Add Subcategory</h5>
            <div class="mb-2">
                <select name="category_id" class="form-select select2" required>
                    <option value="">Select Category</option>
                    <?php
                    $cats = mysqli_query($conn, "SELECT * FROM expense_categories");
                    while ($row = mysqli_fetch_assoc($cats)) {
                        echo "<option value='{$row['id']}'>{$row['name']}</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="mb-2">
                <input type="text" name="subcategory_name" class="form-control" placeholder="Subcategory Name" required>
            </div>
            <button class="btn btn-success" name="add_subcategory">Add Subcategory</button>
        </form>
    </div>
</div>

<?php
if (isset($_POST['add_category'])) {
    $cat = mysqli_real_escape_string($conn, $_POST['category_name']);
    mysqli_query($conn, "INSERT INTO expense_categories (name) VALUES ('$cat')");
    echo "<script>Swal.fire('Success', 'Category added!', 'success')</script>";
}

if (isset($_POST['add_subcategory'])) {
    $cat_id = $_POST['category_id'];
    $sub = mysqli_real_escape_string($conn, $_POST['subcategory_name']);
    mysqli_query($conn, "INSERT INTO expense_subcategories (category_id, name) VALUES ('$cat_id', '$sub')");
    echo "<script>Swal.fire('Success', 'Subcategory added!', 'success')</script>";
}
?>


