<?php
require_once('includes/load.php');
page_require_level(7);

$records_per_page = 10;
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($current_page - 1) * $records_per_page;

$search = '';
$location_filter = '';

// Cek apakah ada pencarian yang dilakukan
if (isset($_POST['search'])) {
    $search = remove_junk($db->escape($_POST['search']));
    $location_filter = isset($_POST['location_filter']) ? $_POST['location_filter'] : '';

    // Query dengan filter berdasarkan pencarian part_number, name, dan location
    $transfers = find_by_sql("
        SELECT wt.*, p.name 
        FROM wh_transfer wt 
        LEFT JOIN products p ON wt.part_number = p.part_number 
        WHERE (wt.part_number LIKE '%$search%' OR p.name LIKE '%$search%')
        AND (wt.location LIKE '%$location_filter%')
        ORDER BY wt.transfer_date DESC
        LIMIT $records_per_page OFFSET $offset
    ");
} else {
    // Query default tanpa filter
    $transfers = find_by_sql(" 
        SELECT wt.*, p.name 
        FROM wh_transfer wt 
        LEFT JOIN products p ON wt.part_number = p.part_number 
        ORDER BY wt.transfer_date DESC
        LIMIT $records_per_page OFFSET $offset
    ");
}

// Calculate total number of records
$total_records_query = isset($_POST['search']) ? "
    SELECT COUNT(*) as total 
    FROM wh_transfer wt 
    LEFT JOIN products p ON wt.part_number = p.part_number 
    WHERE (wt.part_number LIKE '%$search%' OR p.name LIKE '%$search%')
    AND (wt.location LIKE '%$location_filter%')
" : "
    SELECT COUNT(*) as total 
    FROM wh_transfer wt 
    LEFT JOIN products p ON wt.part_number = p.part_number
";

$total_records_result = find_by_sql($total_records_query);
$total_records = $total_records_result[0]['total'];
$total_pages = ceil($total_records / $records_per_page);

// Generate pagination links with search and filter parameters
$pagination_links = '';
for ($i = 1; $i <= $total_pages; $i++) {
    $active = ($i == $current_page) ? 'active' : '';
    $search_param = isset($_POST['search']) ? "&search=" . urlencode($search) : '';
    $location_param = isset($_POST['location_filter']) ? "&location_filter=" . urlencode($location_filter) : '';
    $pagination_links .= "<li class='page-item $active'><a class='page-link' href='?page=$i$search_param$location_param'>$i</a></li>";
}
?>

<?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">
                <h3 class="panel-title">Transfer Warehouse List</h3>
                <button id="export-btn" class="btn btn-success pull-right">Export to Excel</button>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-6">
                        <!-- Form filter yang lebih rapi -->
                        <form method="post" action="" class="form-inline">
                            <div class="form-group mb-2">
                                <input type="text" class="form-control" name="search" placeholder="Cari Part Number atau Name"
                                    value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            <div class="form-group mb-2" style="margin-left: 10px;">
                                <select class="form-control" name="location_filter">
                                    <option value="">Pilih Lokasi</option>
                                    <option value="wh_jakarta"
                                        <?php echo (isset($_POST['location_filter']) && $_POST['location_filter'] == 'wh_jakarta') ? 'selected' : ''; ?>>
                                        WH Jakarta</option>
                                    <option value="wh_makassar"
                                        <?php echo (isset($_POST['location_filter']) && $_POST['location_filter'] == 'wh_makassar') ? 'selected' : ''; ?>>
                                        WH Makassar</option>
                                    <option value="wh_bali"
                                        <?php echo (isset($_POST['location_filter']) && $_POST['location_filter'] == 'wh_bali') ? 'selected' : ''; ?>>
                                        WH Bali</option>
                                </select>
                            </div>
                            <div class="form-group mb-2" style="margin-left: 10px;">
                                <button class="btn btn-primary" type="submit">Search</button>
                            </div>
                        </form>
                    </div>
                </div>
                <br>

                <!-- Tabel transfer -->
                <table class="table table-bordered table-striped" id="transfer-table">
                    <thead>
                        <tr>
                            <th class="text-center">#</th>
                            <th>Part Number</th>
                            <th>Name</th>
                            <th>Quantity</th>
                            <th>Location</th>
                            <th>Remark</th>
                            <th>Transfer Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($transfers): ?>
                            <?php foreach ($transfers as $transfer): ?>
                                <tr>
                                    <td class="text-center"><?php echo count_id(); ?></td>
                                    <td><?php echo remove_junk($transfer['part_number']); ?></td>
                                    <td><?php echo remove_junk($transfer['name']); ?></td>
                                    <td><?php echo remove_junk($transfer['quantity']); ?></td>
                                    <td><?php echo remove_junk($transfer['location']); ?></td>
                                    <td><?php if (!empty($transfer['remark'])) {
                                            echo remove_junk($transfer['remark']);
                                        } else {
                                            echo '';
                                        } ?>
                                    </td>
                                    <td><?php echo remove_junk($transfer['transfer_date']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="7" class="text-center">Tidak ada hasil yang ditemukan</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Pagination Controls -->
<div class="row">
    <div class="col-md-12">
        <nav aria-label="Page navigation">
            <ul class="pagination">
                <?php echo $pagination_links; ?>
            </ul>
        </nav>
    </div>
</div>

<!-- Include SheetJS dan FileSaver.js dari CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

<!-- JavaScript untuk ekspor ke Excel -->
<script>
    document.getElementById('export-btn').addEventListener('click', function() {
        var table = document.getElementById('transfer-table');
        var workbook = XLSX.utils.table_to_book(table, {
            sheet: "Transfers"
        });
        var wbout = XLSX.write(workbook, {
            bookType: 'xlsx',
            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"
        }), 'transfers.xlsx');
    });
</script>

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