<?php
if(!isset($_SESSION['admin_email'])){
    echo "<script>window.open('login.php','_self')</script>";
} else {
?>

<div class="row"><!-- 1 row Starts -->
    <div class="col-lg-12">
        <ol class="breadcrumb">
            <li>
                <i class="fa fa-dashboard"></i> Dashboard / Insert Category
            </li>
        </ol>
    </div>
</div>

<div class="row"><!-- 2 row Starts -->
    <div class="col-lg-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">
                    <i class="fa fa-money fa-fw"></i> Insert Category
                </h3>
            </div>

            <div class="panel-body">
                <form class="form-horizontal" action="" method="post">

                    <!-- Category Name -->
                    <div class="form-group">
                        <label class="col-md-3 control-label">Category Name</label>
                        <div class="col-md-6">
                            <input type="text" name="cat_name" class="form-control" required>
                        </div>
                    </div>

                    <!-- Parent Category -->
                    <!-- Parent Category -->
<div class="form-group">
    <label class="col-md-3 control-label">Parent Category</label>
    <div class="col-md-6">
        <select name="parent_cat_id" class="form-control">
            <option value="0">Main Category</option>
            <?php
            $get_cats = "SELECT cat_id, cat_name FROM categories"; // ✅ FIXED
            $run_cats = mysqli_query($con, $get_cats);
            while ($row_cats = mysqli_fetch_array($run_cats)) {
                $cat_id = $row_cats['cat_id'];
                $cat_name = $row_cats['cat_name'];
                echo "<option value='$cat_id'>$cat_name</option>";
            }
            ?>
        </select>
    </div>
</div>


                    <!-- Submit -->
                    <div class="form-group">
                        <label class="col-md-3 control-label"></label>
                        <div class="col-md-6">
                            <input type="submit" name="submit" value="Insert Category" class="btn btn-primary form-control">
                        </div>
                    </div>

                </form>
            </div>
        </div>
    </div>
</div>

<?php
if(isset($_POST['submit'])){
    $cat_name = $_POST['cat_name'];
    $parent_cat_id = $_POST['parent_cat_id'];

    $insert_cat = "INSERT INTO categories (cat_name, parent_cat_id) VALUES ('$cat_name', '$parent_cat_id')";
    $run_cat = mysqli_query($con, $insert_cat);

    if($run_cat){
        echo "<script>alert('New Category Has Been Inserted')</script>";
        echo "<script>window.open('index.php?view_cats','_self')</script>";
    }
}
?>

<?php } ?>
