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

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

$id = intval($_GET['id'] ?? 0);

$res = mysqli_query($conn, "SELECT * FROM categories WHERE id=$id");
$cat = mysqli_fetch_assoc($res);

if (!$cat) {
    echo "<script>window.location.href='categories.php'</script>";
    exit;
}
?>

<style>
body {
    background:#f6f7f9;
}

.card{
    border-radius:12px;
}

.preview-img{
    width:90px;
    border-radius:8px;
    margin-top:10px;
}
</style>

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

    <div class="container my-4">

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

            <input type="hidden" name="id" value="<?= $cat['id'] ?>">

            <!-- BASIC INFO -->
            <div class="card mb-3">
                <div class="card-body">

                    <h5>Basic Information</h5>

                    <div class="row mt-3">

                        <div class="col-md-6">
                            <label class="form-label">Category Name</label>
                            <input type="text"
                                   name="name"
                                   id="catName"
                                   value="<?= htmlspecialchars($cat['name']) ?>"
                                   class="form-control"
                                   required>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Slug</label>
                            <input type="text"
                                   name="slug"
                                   id="catSlug"
                                   value="<?= $cat['slug'] ?>"
                                   class="form-control"
                                   placeholder="auto-generated">
                        </div>

                    </div>

                    <div class="row mt-3">

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

<?php if($cat['image']){ ?>
<img src="uploads/categories/<?= $cat['image'] ?>" id="imagePreview" class="preview-img">
<?php } else { ?>
<img id="imagePreview" class="preview-img" style="display:none;">
<?php } ?>

                        </div>

                    </div>

                    <div class="row mt-3">

                        <div class="col-md-6">
                            <label class="form-label">Sort Order</label>
                            <input type="number"
                                   name="sort_order"
                                   value="<?= $cat['sort_order'] ?>"
                                   class="form-control">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">

                                <option value="active"
                                    <?= $cat['status']=='active'?'selected':'' ?>>
                                    Active
                                </option>

                                <option value="inactive"
                                    <?= $cat['status']=='inactive'?'selected':'' ?>>
                                    Inactive
                                </option>

                            </select>
                        </div>

                    </div>

                </div>
            </div>

            <button type="submit" class="btn btn-primary">
                Update Category
            </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 */
$('#catName').on('input', function () {

    let slug = $(this).val()
        .toLowerCase()
        .replace(/[^a-z0-9]+/g,'-')
        .replace(/(^-|-$)/g,'');

    $('#catSlug').val(slug);

});

/* UPDATE CATEGORY */
$('#editCategoryForm').on('submit', function(e){

    e.preventDefault();

    let formData = new FormData(this);

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

            if(res.status === 'success'){

                toastr.success(res.message);

                setTimeout(()=>{
                    window.location.href='show-category.php';
                },1200);

            }else{

                toastr.error(res.message);

            }

        }
    });

});

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

    const file = this.files[0];

    if(file){

        const reader = new FileReader();

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

        reader.readAsDataURL(file);

    }

});

</script>