<?php
$page_title = 'Product';
require_once('includes/load.php');
page_require_level(3);

// Variable declarations
$search_query = "";
$search_option = "";
$category_filter = "";

// Handle search functionality
if (isset($_POST['search'])) {
    $search_query = $_POST['search_query'];
    $search_option = $_POST['search_option'];
    $products = search_products($search_query, $search_option); // Replace with your search function
} else {
    // Handle category filter functionality
    if (isset($_POST['filter_category'])) {
        $category_filter = $_POST['category_filter'];
        $products = filter_products_by_category($category_filter); // Replace with your filter function
    } else {
        // Handle pagination
        $per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 50;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $total_products = count_all_products(); // Replace with your function to count total products
        $total_pages = ceil($total_products / $per_page);

        if ($per_page == 0) {
            $products = get_all_products();
        } else {
            $products = join_product_table($per_page, $page);
        }
    }
}
?>

<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <div class="pull-left">
                    <a href="add_product.php" class="btn btn-primary">Add New</a>
                </div>
                <div class="pull-right">
                    <button type="button" class="btn btn-success" id="exportExcelBtn">Export Excel</button>
                    <script>
                        document.getElementById('exportExcelBtn').addEventListener('click', function() {
                            var wb = XLSX.utils.table_to_book(document.querySelector('.table'));
                            var wbout = XLSX.write(wb, {
                                bookType: 'xlsx',
                                bookSST: true,
                                type: 'binary'
                            });

                            function s2ab(s) {
                                var buf = new ArrayBuffer(s.length);
                                var view = new Uint8Array(buf);
                                for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
                                return buf;
                            }

                            saveAs(new Blob([s2ab(wbout)], {
                                type: 'application/octet-stream'
                            }), 'export.xlsx');
                        });
                    </script>
                </div>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-6">
                        <form class="form-inline float-right" method="get" action="product.php">
                            <div class="form-group">
                                <label for="per_page">View per page:</label>
                                <select class="form-control" id="per_page" name="per_page">
                                    <option value="0" <?php if ($per_page == 0) echo 'selected'; ?>>All</option>
                                    <option value="25" <?php if ($per_page == 25) echo 'selected'; ?>>25</option>
                                    <option value="50" <?php if ($per_page == 50) echo 'selected'; ?>>50</option>
                                    <option value="100" <?php if ($per_page == 100) echo 'selected'; ?>>100</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-default">Update</button>
                        </form>
                    </div>
                    <div class="col-md-6">
                        <form method="post" action="product.php" class="form-inline float-right">
                            <div class="form-group">
                                <label for="category_filter">Filter by Category:</label>
                                <select class="form-control" id="category_filter" name="category_filter">
                                    <option value="">All Categories</option>
                                    <?php foreach (get_all_categories() as $category) : ?>
                                        <option value="<?php echo $category['id']; ?>"
                                            <?php if ($category_filter == $category['id']) echo 'selected'; ?>>
                                            <?php echo $category['name']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" name="filter_category" class="btn btn-default">Filter</button>
                        </form>
                    </div>
                    <div class="col-md-12">
                        <div class="float-left">
                            <img src="images/logo.png" alt="Logo" style="max-width: 50px; max-height: 50px;">
                            <span style="font-weight: bold;">Database item (by Nanda)</span>
                        </div>
                        <div class="float-right">
                            <form method="post" action="product.php" class="form-inline">
                                <div class="form-group">
                                    <input type="text" class="form-control" name="search_query" placeholder="Search..."
                                        value="<?php echo htmlspecialchars($search_query); ?>">
                                </div>
                                <div class="form-group">
                                    <select class="form-control" name="search_option">
                                        <option value="product" <?php if ($search_option === "product") echo "selected"; ?>>Search by
                                            Product Name</option>
                                        <option value="part_number" <?php if ($search_option === "part_number") echo "selected"; ?>>Search
                                            by Part Number</option>
                                    </select>
                                </div>
                                <button type="submit" name="search" class="btn btn-default">Search</button>
                            </form>
                        </div>
                    </div>
                    <div class="col-md-12">
                        <!-- Product Table -->
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <th class="text-center">#</th>
                                        <th>Part Number</th>
                                        <th class="text-center">New Code</th>
                                        <th>Product</th>
                                        <th class="text-center">Categories</th>
                                        <th class="text-center">In-Stock</th>
                                        <th class="text-center">UoM</th>
                                        <th class="text-center">Unit Price</th>
                                        <th class="text-center">Location ID</th>
                                        <th class="text-center">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($products as $product) : ?>
                                        <tr>
                                            <td class="text-center"><?php echo count_id(); ?></td>
                                            <td>
                                                <?php echo isset($product['part_number']) ? htmlspecialchars($product['part_number']) : 'N/A'; ?>
                                            </td>
                                            <td class="text-center"><?php echo remove_junk($product['new_code']); ?></td>
                                            <td><?php echo remove_junk($product['name']); ?></td>
                                            <td class="text-center"><?php echo remove_junk($product['categorie']); ?></td>
                                            <td class="text-center"><?php echo get_product_stock($product['id']); ?></td>
                                            <td class="text-center"><?php echo remove_junk($product['uom']); ?></td>
                                            <td class="text-center"><?php echo remove_junk($product['buy_price']); ?></td>
                                            <td class="text-center"><?php echo remove_junk($product['loc_id']); ?></td>
                                            <td class="text-center">
                                                <div class="btn-group">
                                                    <a href="aa.php?id=<?php echo (int)$product['id']; ?>" class="btn btn-info btn-xs" title="Edit"
                                                        data-toggle="tooltip">
                                                        <span class="glyphicon glyphicon-edit"></span>
                                                    </a>
                                                    <a href="aa.php?id=<?php echo (int)$product['id']; ?>" class="btn btn-danger btn-xs"
                                                        title="Delete" data-toggle="tooltip">
                                                        <span class="glyphicon glyphicon-trash"></span>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <!-- Pagination -->
                        <div class="col-md-12">
                            <ul class="pagination">
                                <?php if ($total_pages > 1) : ?>
                                    <?php
                                    $pagination_start = max(1, $page - 2);
                                    $pagination_end = min($total_pages, $page + 2);

                                    if ($page > 1) {
                                        echo '<li><a href="product.php?page=1&per_page=' . $per_page . '">First</a></li>';
                                        echo '<li><a href="product.php?page=' . ($page - 1) . '&per_page=' . $per_page . '">Previous</a></li>';
                                    }

                                    for ($i = $pagination_start; $i <= $pagination_end; $i++) {
                                        echo $i == $page ? '<li class="active"><span>' . $i . '</span></li>' : '<li><a href="product.php?page=' . $i . '&per_page=' . $per_page . '">' . $i . '</a></li>';
                                    }

                                    if ($page < $total_pages) {
                                        echo '<li><a href="product.php?page=' . ($page + 1) . '&per_page=' . $per_page . '">Next</a></li>';
                                        echo '<li><a href="product.php?page=' . $total_pages . '&per_page=' . $per_page . '">Last</a></li>';
                                    }
                                    ?>
                                <?php endif; ?>
                            </ul>
                        </div>
                        <!-- End Pagination -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include_once('layouts/footer.php'); ?>