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

// Check if export request
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    // Set headers for Excel download
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=transfer_report_".date('Ymd').".xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    // Get the same data as displayed
    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
    $part_number = isset($_GET['part_number']) ? $_GET['part_number'] : '';
    
    $sql = "SELECT l.part_number, l.quantity, l.transfer_date, l.remark, p.name
            FROM list_transfer_prod_loc l
            LEFT JOIN products p ON l.part_number = p.part_number
            WHERE l.transfer_date BETWEEN '$start_date' AND '$end_date'";
    if (!empty($part_number)) {
        $sql .= " AND l.part_number LIKE '%$part_number%'";
    }
    $sql .= " ORDER BY l.transfer_date DESC";
    $transfers = find_by_sql($sql);
    
    // Start Excel content
    echo "<table border='1'>";
    echo "<tr><th>Part Number</th><th>Name</th><th>Quantity</th><th>Transfer Date</th><th>Remark</th></tr>";
    
    foreach ($transfers as $transfer) {
        echo "<tr>";
        echo "<td>".htmlspecialchars($transfer['part_number'])."</td>";
        echo "<td>".htmlspecialchars($transfer['name'])."</td>";
        echo "<td>".htmlspecialchars($transfer['quantity'])."</td>";
        echo "<td>".htmlspecialchars($transfer['transfer_date'])."</td>";
        echo "<td>".htmlspecialchars($transfer['remark'])."</td>";
        echo "</tr>";
    }
    
    echo "</table>";
    exit(); // Stop further execution after exporting
}

// 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_transfer_prod_loc l
        WHERE l.transfer_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.transfer_date, l.remark, p.name
        FROM list_transfer_prod_loc l
        LEFT JOIN products p ON l.part_number = p.part_number
        WHERE l.transfer_date BETWEEN '$start_date' AND '$end_date'";
if (!empty($part_number)) {
    $sql .= " AND l.part_number LIKE '%$part_number%'";
}
$sql .= " ORDER BY l.transfer_date DESC"; // Order by transfer_date from newest to oldest
$sql .= " LIMIT $per_page OFFSET $offset";
$transfers = find_by_sql($sql);

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

<form method="get" action="list_transfer_prod_loc.php">
    <label for="start_date">Start Date:</label>
    <input type="date" name="start_date" value="<?php echo $start_date; ?>">
    <label for="end_date">End Date:</label>
    <input type="date" name="end_date" value="<?php echo $end_date; ?>">
    <label for="part_number">Part Number:</label>
    <input type="text" name="part_number" value="<?php echo $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="submit" name="export" value="excel" class="btn btn-success">Export to Excel</button>
</form>

<?php if (!empty($transfers)) : ?>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>Part Number</th>
                <th>Name</th>
                <th>Quantity</th>
                <th>Transfer Date</th>
                <th>Remark</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($transfers as $transfer): ?>
                <tr>
                    <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['transfer_date']); ?></td>
                    <td><?php echo remove_junk($transfer['remark']); ?></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="list_transfer_prod_loc.php?page=<?php echo $i; ?>&start_date=<?php echo $start_date; ?>&end_date=<?php echo $end_date; ?>&part_number=<?php echo $part_number; ?>&per_page=<?php echo $per_page; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
            <?php endif; ?>
        </ul>
    </nav>
<?php else: ?>
    <p>No transfer records found for the selected date range and part number.</p>
<?php endif; ?>

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