<?php
include 'inc/header.php';

if (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'user') {
    echo "<script>window.location.href='index.php'</script>";
    exit;
}
?>

<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-secondary">Add SubCategory</h6>
    </div>

    <div class="container my-4">

       <form id="subcategoryForm" enctype="multipart/form-data">

            <div class="card mb-3">
                <div class="card-body">
                    <h5>Basic Information</h5>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Main Category</label>
                            <select name="category_id" class="form-control" required>
                                <option value="">Select Category</option>

                                <?php
                                $cats = mysqli_query($conn,"SELECT id,name FROM categories WHERE status='active' ORDER BY sort_order ASC");
                                while($c = mysqli_fetch_assoc($cats)){
                                    echo "<option value='{$c['id']}'>{$c['name']}</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label>SubCategory Name</label>
                            <input type="text" name="name" id="subName" class="form-control" required>
                        </div>
                    </div>

                    <div class="row mt-3">
    <div class="col-md-12">
        <label>SubCategory Image</label>
       <input type="file" name="image" id="imageInput" class="form-control">

<img id="imagePreview" 
     src="" 
     style="display:none; margin-top:10px; width:120px; border-radius:6px;">
    </div>
</div>

                    <div class="row mt-3">
                        <div class="col-md-6">
                            <label>Slug</label>
                            <input type="text" name="slug" id="subSlug" class="form-control" placeholder="auto-generated">
                        </div>

                        <div class="col-md-3">
                            <label>Sort Order</label>
                            <input type="number" name="sort_order" class="form-control" value="1">
                        </div>

                        <div class="col-md-3">
                            <label>Status</label>
                            <select name="status" class="form-control">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>

                </div>
            </div>

            <button type="submit" class="btn btn-primary">Save SubCategory</button>
        </form>

    </div>
</div>

<?php include 'inc/footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
     toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000"
    };
/* AUTO SLUG */
$('#subName').on('input', function () {
    let slug = $(this).val()
        .toLowerCase()
        .replace(/[^a-z0-9]+/g, '-')
        .replace(/(^-|-$)/g, '');

    $('#subSlug').val(slug);
});

/* SUBMIT */
$('#subcategoryForm').on('submit', function(e){
    e.preventDefault();

    let formData = new FormData(this);

    $.ajax({
        url: 'api/save_subcategory.php',
        type: 'POST',
        data: formData,
        processData:false,
        contentType:false,
        dataType:'json',
        success:function(res){

            if(res.status === 'success'){
                toastr.success(res.message);
                $('#subcategoryForm')[0].reset();
                $('#subSlug').val('');
            }else{
                toastr.error(res.message);
            }

        }
    });

});
/* IMAGE PREVIEW */
$('#imageInput').on('change', function(){

    let file = this.files[0];

    if(file){
        let reader = new FileReader();

        reader.onload = function(e){
            $('#imagePreview')
                .attr('src', e.target.result)
                .show();
        }

        reader.readAsDataURL(file);
    }

});
</script>