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

if (isset($_SESSION['user_role']) && $_SESSION['user_role'] == 'user') {
    echo "<script>window.location.href='index.php'</script>";
    exit;
}
?>
<style>
/* delete animation */
.row-deleting {
    background: #ffebee !important;
    transition: all .4s ease;
}

.row-fade-out {
    opacity: 0;
    transform: translateX(40px);
    transition: all .5s ease;
}
</style>

<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">

<div class="card shadow mb-4">

    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-secondary">Products List</h6>
        <a href="add-product.php" class="btn btn-primary btn-sm">
            + Add Product
        </a>
    </div>


    <div class="card-body">
        <div class="row mb-3">
            <div class="col-md-4">
                <label><strong>Filter by Category</strong></label>
                <select id="categoryFilter" class="form-control">
                    <option value="">All Categories</option>
                    <?php
        $cats = mysqli_query($conn,"SELECT id,name FROM categories ORDER BY name ASC");
        while($c = mysqli_fetch_assoc($cats)){
            echo "<option value='{$c['id']}'>".$c['name']."</option>";
        }
    ?>
                </select>

            </div>
            <div class="col-md-4">
<label><strong>Filter by Subcategory</strong></label>

<select id="subcategoryFilter" class="form-control">
<option value="">All Subcategories</option>
</select>

</div>
        </div>
        <table id="productsTable" class="display table table-bordered" width="100%">
            <thead>
                <tr>
                   <th>ID</th>
<th>Product Name</th>
<th>Category</th>
<th>Subcategory</th>
<th>Status</th>
<th>Created</th>
<th>Actions</th>
                </tr>
            </thead>

            <tbody>
                <?php
                $sql = "
SELECT p.*, 
       c.name as category_name,
       s.name as subcategory_name
FROM products p
LEFT JOIN categories c ON c.id = p.category_id
LEFT JOIN subcategories s ON s.id = p.subcategory_id
ORDER BY p.id DESC
";

                $res = mysqli_query($conn, $sql);

                while ($row = mysqli_fetch_assoc($res)) {
                ?>
                <tr 
data-id="<?= $row['id'] ?>" 
data-category="<?= $row['category_id'] ?>"
data-subcategory="<?= $row['subcategory_id'] ?>"
>
                    <td><?= $row['id'] ?></td>
                    <td><?= htmlspecialchars($row['name']) ?></td>
                    <td><?= htmlspecialchars($row['category_name']) ?></td>
                    <td>
<?= $row['subcategory_name'] ? htmlspecialchars($row['subcategory_name']) : '-' ?>
</td>

                    <td>
                        <span class="badge badge-<?= $row['status']=='active' ? 'success' : 'danger' ?>">
                            <?= ucfirst($row['status']) ?>
                        </span>
                    </td>

                    <td><?= date('d M Y h:i a', strtotime($row['created_at'])) ?></td>

                    <td>
                        <a href="edit_product.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-info">
                            Edit
                        </a>

                        <button class="btn btn-sm btn-danger delete-btn">
                            Delete
                        </button>
                    </td>
                </tr>
                <?php } ?>
            </tbody>

        </table>
    </div>
</div>

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

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
$(function() {

    const table = $('#productsTable').DataTable({
        order: [
            [0, 'desc']
        ]
    });

    toastr.options = {
        closeButton: true,
        progressBar: true,
        positionClass: "toast-top-right",
        timeOut: "3000"
    };

    /* CATEGORY FILTER */
  $('#categoryFilter, #subcategoryFilter').on('change', function(){

    let category = $('#categoryFilter').val();
    let subcategory = $('#subcategoryFilter').val();

    $.fn.dataTable.ext.search = [];

    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex){

        let rowNode = table.row(dataIndex).node();

        let rowCategory = $(rowNode).data('category');
        let rowSub = $(rowNode).data('subcategory');

        if(category && rowCategory != category){
            return false;
        }

        if(subcategory && rowSub != subcategory){
            return false;
        }

        return true;

    });

    table.draw();

});

$('#categoryFilter').on('change', function(){

    let categoryID = $(this).val();

    // clear subcategory dropdown
    $('#subcategoryFilter').html('');

    if(categoryID){

        $.post('api/get_subcategories.php',{category_id:categoryID},function(res){

            $('#subcategoryFilter').append(res);

        });

    }

});


    /* DELETE PRODUCT */
    $('#productsTable').on('click', '.delete-btn', function() {
        let row = $(this).closest('tr');
        let product_id = row.data('id');

        Swal.fire({
            title: 'Are you sure?',
            text: "This product will be permanently deleted!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, delete it!',
            reverseButtons: true
        }).then((result) => {

            if (result.isConfirmed) {
                $.post('delete_product.php', {
                    id: product_id
                }, function(res) {
                    if (res.status === 'success') {
                        row.addClass('row-deleting');
                        setTimeout(() => row.addClass('row-fade-out'), 200);
                        setTimeout(() => table.row(row).remove().draw(false), 600);
                        toastr.success(res.message || 'Product deleted successfully');
                    } else {
                        toastr.error(res.message || 'Unable to delete product');
                    }
                }, 'json');
            }
        });
    });

});
</script>