<?php
require_once('includes/load.php');
error_reporting(E_ALL);
ini_set('display_errors', 1);

page_require_level(3); // Memerlukan tingkat akses minimal 3 untuk mengakses halaman ini

// Set default values for filters
$default_part_number = '';

// Initialize filter values
$part_number = isset($_GET['part_number']) ? $_GET['part_number'] : $default_part_number;

// Pagination settings
$per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 200;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $per_page;

if (isset($_POST['categorie_id']) && !empty($_POST['categorie_id'])) {
    $categorie_id = (int)$_POST['categorie_id'];
    $sql = "SELECT pl.*, c.name AS category_name, p.quantity AS product_quantity, w.quantity AS wip_quantity
            FROM prod_loc pl
            LEFT JOIN categories c ON pl.categorie_id = c.id
            LEFT JOIN products p ON pl.product_id = p.id
            LEFT JOIN WIP w ON pl.part_number = w.part_number
            WHERE pl.categorie_id = $categorie_id";
} else {
    $sql = "SELECT pl.*, c.name AS category_name, p.quantity AS product_quantity, w.quantity AS wip_quantity
            FROM prod_loc pl
            LEFT JOIN categories c ON pl.categorie_id = c.id
            LEFT JOIN products p ON pl.product_id = p.id
            LEFT JOIN WIP w ON pl.part_number = w.part_number";
}


// Construct SQL query with filters
$sql = "SELECT COUNT(*) as total FROM WIP w";
if (!empty($part_number)) {
    $sql .= " WHERE w.part_number LIKE '%$part_number%'";
}
$total_result = find_by_sql($sql);
if (!$total_result) {
    die("Error in query: " . $sql); // Debugging line
}
$total_records = $total_result[0]['total'];
$total_pages = ceil($total_records / $per_page);

$sql = "SELECT w.part_number, w.name, w.quantity, w.uom, c.name AS category_name
        FROM WIP w
        LEFT JOIN categories c ON w.categorie_id = c.id";
if (!empty($part_number)) {
    $sql .= " WHERE w.part_number LIKE '%$part_number%'";
}
$sql .= " ORDER BY w.part_number ASC"; // Order by part_number (or any other field you prefer)
$sql .= " LIMIT $per_page OFFSET $offset";
$wip_data = find_by_sql($sql);
if (!$wip_data) {
    die("Error in query: " . $sql); // Debugging line
}

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

<form method="get" action="wip.php">
    <label for="part_number">Part Number:</label>
    <input type="text" name="part_number" value="<?php echo htmlspecialchars($part_number); ?>">
    <label for="per_page">Records Per Page:</label>
    <input type="number" name="per_page" value="<?php echo $per_page; ?>" min="1">
    <button type="submit">Filter</button>
    <button type="button" class="btn btn-success" id="exportExcelBtn">Export Excel</button>
</form>

<?php if (!empty($wip_data)) : ?>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Part Number</th>
                <th>Name</th>
                <th>Quantity</th>
                <th>UOM</th>
                <th>Category</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($wip_data as $item): ?>
                <tr>
                    <td><?php echo htmlspecialchars($item['part_number']); ?></td>
                    <td><?php echo htmlspecialchars($item['name']); ?></td>
                    <td><?php echo htmlspecialchars($item['quantity']); ?></td>
                    <td><?php echo htmlspecialchars($item['uom']); ?></td>
                    <td><?php echo htmlspecialchars($item['category_name']); ?></td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Pagination -->
    <nav>
        <ul class="pagination justify-content-center">
            <?php if ($total_pages > 1): ?>
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php if ($i == $current_page) echo 'active'; ?>">
                        <a class="page-link"
                            href="wip.php?page=<?php echo $i; ?>&part_number=<?php echo htmlspecialchars($part_number); ?>&per_page=<?php echo $per_page; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
            <?php endif; ?>
        </ul>
    </nav>
<?php else: ?>
    <p>No WIP records found for the selected filters.</p>
<?php endif; ?>

<?php include_once('layouts/footer.php'); ?>
<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'
        }), 'wip_data.xlsx');
    });
</script>