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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$search_query = "";
$search_option = "";
$category_filter = "";

if (isset($_POST['search'])) {
    $search_query = $_POST['search_query'];
    $search_option = $_POST['search_option'];
    $products = search_products($search_query, $search_option); // Implement search_products function
} else {
    if (isset($_POST['filter_category'])) {
        $category_filter = $_POST['category_filter'];
        $products = filter_products_by_category($category_filter); // Implement filter_products_by_category function
    } else {
        $per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 50;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $total_products = count_all_products(); // Implement count_all_products function
        $total_pages = ceil($total_products / $per_page);

        if ($per_page == 0) {
            $products = get_all_products(); // Implement get_all_products function
        } else {
            $products = join_product_table($per_page, $page); // Implement join_product_table function
        }
    }
}

// Menghitung total quantity untuk setiap produk berdasarkan part_number
foreach ($products as &$product) {
    $product['scan_status'] = get_monthly_quantity($product['part_number']);
}
?>

<?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_new.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_new.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 $cat): ?>
                                        <option value="<?php echo (int)$cat['id']; ?>"><?php echo $cat['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" name="filter_category" class="btn btn-default">Filter</button>
                        </form>
                    </div>
                </div>
                <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">Monthly Quantity</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 number_format($product['quantity'], 2); ?></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"><?php echo number_format($product['scan_status'], 2); ?></td>
                                    <td class="text-center">
                                        <div class="btn-group">
                                            <a href="edit_product.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="delete_product.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>
            </div>
            <div class="panel-footer">
                <nav>
                    <ul class="pagination">
                        <?php for ($i = 1; $i <= $total_pages; $i++) : ?>
                            <li class="<?php if ($i == $page) echo 'active'; ?>"><a
                                    href="product_new.php?page=<?php echo $i; ?>&per_page=<?php echo $per_page; ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</div>

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