<?php
require_once('includes/load.php');
page_require_level(3); // Memerlukan tingkat akses minimal 3 untuk mengakses halaman ini

// Set default start and end dates to the beginning of the current month and today's date
$default_start_date = date('Y-m-01');
$default_end_date = date('Y-m-d');

// Initialize filter values with default dates
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : $default_start_date;
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : $default_end_date;
$part_number = isset($_GET['part_number']) ? $_GET['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;

// Construct SQL query with filters
$sql = "SELECT COUNT(*) as total FROM list_consume_production l
        WHERE l.consume_date BETWEEN '$start_date' AND '$end_date'";
if (!empty($part_number)) {
    $sql .= " AND l.part_number LIKE '%$part_number%'";
}
$total_result = find_by_sql($sql);
$total_records = $total_result[0]['total'];
$total_pages = ceil($total_records / $per_page);

$sql = "SELECT l.part_number, l.quantity, l.consume_date, l.remark, p.name
        FROM list_consume_production l
        LEFT JOIN products p ON l.part_number = p.part_number
        WHERE l.consume_date BETWEEN '$start_date' AND '$end_date'";
if (!empty($part_number)) {
    $sql .= " AND l.part_number LIKE '%$part_number%'";
}
$sql .= " ORDER BY l.consume_date DESC"; // Order by consume_date from newest to oldest
$sql .= " LIMIT $per_page OFFSET $offset";
$consumes = find_by_sql($sql);

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

<!-- Page Content Wrapper -->
<main id="page-content-wrapper" class="flex-fill p-4">
    <h2>Data Consume Production</h2>

    <!-- Filter Form -->
    <form method="get" action="data_consume.php" class="mb-4">
        <div class="row">
            <div class="col-md-3 mb-3">
                <label for="start_date" class="form-label">Start Date:</label>
                <input type="date" class="form-control" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
            </div>
            <div class="col-md-3 mb-3">
                <label for="end_date" class="form-label">End Date:</label>
                <input type="date" class="form-control" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
            </div>
            <div class="col-md-3 mb-3">
                <label for="part_number" class="form-label">Part Number:</label>
                <input type="text" class="form-control" name="part_number"
                    value="<?php echo htmlspecialchars($part_number); ?>">
            </div>
            <div class="col-md-3 mb-3">
                <label for="per_page" class="form-label">Records Per Page:</label>
                <input type="number" class="form-control" name="per_page" value="<?php echo htmlspecialchars($per_page); ?>"
                    min="1">
            </div>
        </div>
        <button type="submit" class="btn btn-primary">Filter</button>
        <button type="button" class="btn btn-success" id="exportExcelBtn">Export Excel</button>
    </form>

    <?php if (!empty($consumes)) : ?>
        <table class="table table-bordered mt-4">
            <thead>
                <tr>
                    <th>Part Number</th>
                    <th>Name</th>
                    <th>Quantity</th>
                    <th>Consume Date</th>
                    <th>Remark</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($consumes as $consume): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($consume['part_number']); ?></td>
                        <td><?php echo htmlspecialchars($consume['name']); ?></td>
                        <td><?php echo htmlspecialchars($consume['quantity']); ?></td>
                        <td><?php echo htmlspecialchars($consume['consume_date']); ?></td>
                        <td><?php echo htmlspecialchars($consume['remark']); ?></td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <nav class="mt-4">
            <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="data_consume.php?page=<?php echo $i; ?>&start_date=<?php echo urlencode($start_date); ?>&end_date=<?php echo urlencode($end_date); ?>&part_number=<?php echo urlencode($part_number); ?>&per_page=<?php echo $per_page; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                <?php endif; ?>
            </ul>
        </nav>
    <?php else: ?>
        <p>No consume records found for the selected date range and part number.</p>
    <?php endif; ?>
</main>
<script>
    document.getElementById('exportExcelBtn').addEventListener('click', function() {
        var table = document.querySelector('table');
        var wb = XLSX.utils.table_to_book(table, {
            sheet: "Sheet1"
        });
        var wbout = XLSX.write(wb, {
            bookType: 'xlsx',
            type: 'array'
        });
        var filename = 'data_consume.xlsx';
        saveAs(new Blob([wbout], {
            type: "application/octet-stream"
        }), filename);
    });
</script>

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