<?php
$page_title = 'Filter AWB Data';
require_once('includes/load.php');
page_require_level(15);

include_once('layouts/header.php');

// Check if start and end dates are provided and validate the format              
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date)) {
    $start_date = date('Y-m-d');
    $msg = ['type' => 'danger', 'message' => 'Invalid start date format. Defaulting to today.'];
}

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
    $end_date = date('Y-m-d');
    if (isset($msg)) {
        $msg['message'] .= ' Invalid end date format. Defaulting to today.';
    } else {
        $msg = ['type' => 'danger', 'message' => 'Invalid end date format. Defaulting to today.'];
    }
}

// Fetch only necessary data based on the selected date range without pagination              
$query = "SELECT id, tanggal_pesenan_dibuat, invoice, resi, kurir, part_number, date_scan, quantity, scan_in, scan_status, scan_retur, packer_no, batas_pengiriman, uniq_code, unit_price, total_price, loc, waktu_proses FROM awb WHERE date_scan BETWEEN ? AND ?";
$stmt = $db->prepare($query);
$stmt->bind_param("ss", $start_date, $end_date);
$stmt->execute();
$result = $stmt->get_result();
$data_found = $result->num_rows > 0;

if (!$data_found) {
    $msg = ['type' => 'info', 'message' => 'No data found for the selected date range.'];
}
?>

<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">Filter AWB Data</h3>
                <form id="dateFilterForm" class="form-inline">
                    <div class="form-group">
                        <label for="startDate">Start Date:</label>
                        <input type="date" id="startDate" name="start_date" class="form-control"
                            value="<?php echo htmlspecialchars($start_date); ?>">
                    </div>
                    <div class="form-group">
                        <label for="endDate">End Date:</label>
                        <input type="date" id="endDate" name="end_date" class="form-control"
                            value="<?php echo htmlspecialchars($end_date); ?>">
                    </div>
                    <button type="submit" class="btn btn-primary">Filter</button>
                    <button type="button" class="btn btn-success pull-right" id="exportToExcel">Export to Excel</button>
                </form>
            </div>
        </div>
    </div>
</div>

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

<style>
    .notification {
        display: none;
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background-color: #fff;
        border: 1px solid #ccc;
        padding: 10px 20px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        z-index: 9999;
    }
</style>
<script>
    $(document).ready(function() {
        $('#dateFilterForm').submit(function(event) {
            event.preventDefault();
            var startDate = $('#startDate').val();
            var endDate = $('#endDate').val();
            window.location.href = 'data_upload.php?start_date=' + startDate + '&end_date=' + endDate;
        });

        $('#exportToExcel').click(function() {
            if (<?php echo $data_found ? 'true' : 'false'; ?>) {
                exportDataToExcel();
            } else {
                alert('No data found to export.');
            }
        });

        function exportDataToExcel() {
            var data = [
                ["ID", "Tanggal Pesenan Dibuat", "Invoice", "Resi", "Kurir", "Part Number", "Date Scan", "Quantity",
                    "Scan In", "Scan Status", "Scan Retur", "Packer No", "Batas Pengiriman", "Waktu Proses", "Uniq Code",
                    "Unit Price", "Total Price", "Loc"
                ]
            ];

            <?php
            if ($data_found) {
                while ($row = $result->fetch_assoc()) {
                    $tanggal_pesenan_dibuat = $row['tanggal_pesenan_dibuat'];
                    $date_scan = $row['date_scan'];
                    $waktu_proses = $row['waktu_proses'];

                    // If waktu_proses is empty, calculate it  
                    if (empty($waktu_proses) && !empty($tanggal_pesenan_dibuat) && !empty($date_scan)) {
                        $datetime1 = new DateTime($tanggal_pesenan_dibuat);
                        $datetime2 = new DateTime($date_scan);
                        $interval = $datetime1->diff($datetime2);
                        $waktu_proses = $datetime1->add($interval)->format('Y-m-d H:i:s');
                    } else if (empty($waktu_proses)) {
                        $waktu_proses = 'N/A'; // If both dates are empty, set to N/A  
                    }

                    echo "data.push([";
                    echo "'" . htmlspecialchars($row['id']) . "',";
                    echo "'" . htmlspecialchars($row['tanggal_pesenan_dibuat']) . "',";
                    echo "'" . htmlspecialchars($row['invoice']) . "',";
                    echo "'" . htmlspecialchars($row['resi']) . "',";
                    echo "'" . htmlspecialchars($row['kurir']) . "',";
                    echo "'" . htmlspecialchars($row['part_number']) . "',";
                    echo "'" . htmlspecialchars($row['date_scan']) . "',";
                    echo "'" . htmlspecialchars($row['quantity']) . "',";
                    echo "'" . htmlspecialchars($row['scan_in']) . "',";
                    echo "'" . htmlspecialchars($row['scan_status']) . "',";
                    echo "'" . htmlspecialchars($row['scan_retur']) . "',";
                    echo "'" . htmlspecialchars($row['packer_no']) . "',";
                    echo "'" . htmlspecialchars($row['batas_pengiriman']) . "',";
                    echo "'" . htmlspecialchars($waktu_proses) . "',"; // Added waktu_proses here      
                    echo "'" . htmlspecialchars($row['uniq_code']) . "',";
                    echo "'" . htmlspecialchars($row['unit_price']) . "',";
                    echo "'" . htmlspecialchars($row['total_price']) . "',";
                    echo "'" . htmlspecialchars($row['loc']) . "'";
                    echo "]);";
                }
            }
            $stmt->close();
            ?>

            var ws = XLSX.utils.aoa_to_sheet(data);
            var wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "AWB Data");
            var wbout = XLSX.write(wb, {
                bookType: 'xlsx',
                type: 'binary',
                compression: true
            });
            saveAs(new Blob([s2ab(wbout)], {
                type: "application/octet-stream"
            }), 'awb_data.xlsx');
        }

        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;
        }
    });
</script>