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

<div class="card shadow mb-4">
    <div class="card-header">
        <h5>Add Material (Global)</h5>
    </div>

    <div class="card-body">

        <form id="materialForm">

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

                <div class="col-md-6">
                    <label>Slug</label>
                    <input type="text" name="slug" id="matSlug" class="form-control">
                </div>
            </div>

            <div class="row mt-3">
                <div class="col-md-6">
                    <label>Type</label>
                    <select name="type" class="form-control">
                        <option value="sqft">SQFT</option>
                        <option value="lnft">LNFT</option>
                    </select>
                </div>

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

            <button class="btn btn-primary mt-3">Save Material</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: "2500"
};

$(document).ready(function(){

    /* AUTO SLUG */
    $('#matName').on('input', function () {
        let slug = $(this).val()
            .toLowerCase()
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/(^-|-$)/g, '');

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


    /* SUBMIT */
    $('#materialForm').submit(function(e){
        e.preventDefault();

        $.ajax({
            url: 'api/save_material.php',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(res){

                if(res.status === 'success'){
                    toastr.success(res.message);

                    $('#materialForm')[0].reset();
                    $('#matSlug').val('');

                } else {
                    toastr.error(res.message);
                }

            },
            error: function(xhr){
                console.log(xhr.responseText);
                toastr.error('Server error');
            }
        });

    });

});
</script>