<?php
// all_warehouse.php

// Aktifkan pelaporan error untuk debugging, bisa dinonaktifkan di production
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Konfigurasi koneksi database
define('DB_HOST', 'localhost');
define('DB_USER', 'wiselie_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'wiselie_inventory');

// Load PhpSpreadsheet library
require 'vendor/autoload.php';

// Inisialisasi variabel
$error = '';
$inventory_data = [];
$column_totals = [];
$keyword_summaries = [];
$all_products = [];
$sales_data = [];
$all_stock_data = [];

// Daftar gudang (nama tabel => nama lokasi)
$warehouses = [
    'products' => 'Surabaya',
    'wh_bali' => 'Bali',
    'wh_jakarta' => 'Jakarta',
    'wh_bandung' => 'Bandung',
    'wh_makassar' => 'Makassar',
    'wh_semarang' => 'Semarang'
];

// Keywords untuk ringkasan penjualan
$summary_keywords = ['250', '100', '60', '30', '1Liter', '5liter', '500', '1kg'];

// Ambil periode penjualan dari GET request, default bulan ini
$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-t');


// ========================================================================
// PROSES PENGAMBILAN & PENGOLAHAN DATA (DIJALANKAN SATU KALI)
// ========================================================================
try {
    // Membuat koneksi database
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        throw new Exception("Koneksi database gagal: " . $conn->connect_error);
    }

    // 1. Ambil semua part_number dan buy_price dari products dengan categorie_id = 7
    $products_query = "SELECT part_number, buy_price FROM products WHERE categorie_id = 7";
    $products_result = $conn->query($products_query);
    if ($products_result === false) {
        throw new Exception("Error mengambil data products: " . $conn->error);
    }
    if ($products_result->num_rows > 0) {
        while ($row = $products_result->fetch_assoc()) {
            $all_products[$row['part_number']] = [
                'part_number' => $row['part_number'],
                'buy_price' => $row['buy_price']
            ];
        }
    } else {
        $error = "Tidak ditemukan part_number dengan categorie_id = 7";
    }

    // 2. [OPTIMASI] Ambil semua data stok dari semua warehouse dalam satu query
    $stock_query_parts = [];
    foreach ($warehouses as $table => $location) {
        // Gunakan backtick (`) untuk nama tabel untuk menghindari error dengan keyword SQL
        $stock_query_parts[] = "(SELECT part_number, quantity, '{$location}' as location FROM `{$table}`)";
    }
    $stock_query = implode(" UNION ALL ", $stock_query_parts);
    
    $stock_result = $conn->query($stock_query);
    if ($stock_result === false) {
        throw new Exception("Error mengambil data stok gabungan: " . $conn->error);
    }
    while ($row = $stock_result->fetch_assoc()) {
        $all_stock_data[$row['part_number']][$row['location']] = (int)$row['quantity'];
    }

    // 3. Ambil data penjualan per lokasi
    $sales_query = "SELECT part_number,
                        SUM(CASE WHEN loc = 'Jakarta' THEN quantity ELSE 0 END) as jakarta,
                        SUM(CASE WHEN loc = 'Makassar' THEN quantity ELSE 0 END) as makassar,
                        SUM(CASE WHEN loc = 'Bali' THEN quantity ELSE 0 END) as bali,
                        SUM(CASE WHEN loc = 'Semarang' THEN quantity ELSE 0 END) as semarang,
                        SUM(CASE WHEN loc = 'Bandung' THEN quantity ELSE 0 END) as bandung,
                        SUM(CASE WHEN loc = 'Sidoarjo' THEN quantity ELSE 0 END) as surabaya
                      FROM awb
                      WHERE DATE(scan_in) BETWEEN ? AND ?
                      GROUP BY part_number";
    $stmt = $conn->prepare($sales_query);
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $sales_result = $stmt->get_result();
    while ($row = $sales_result->fetch_assoc()) {
        $sales_data[$row['part_number']] = [
            'Jakarta' => $row['jakarta'],
            'Makassar' => $row['makassar'],
            'Bali' => $row['bali'],
            'Semarang' => $row['semarang'],
            'Bandung' => $row['bandung'],
            'Surabaya' => $row['surabaya']
        ];
    }
    $stmt->close();

    // 4. Proses dan gabungkan semua data
    if (!empty($all_products)) {
        foreach ($all_products as $product) {
            $part_number = $product['part_number'];
            $buy_price = (float)$product['buy_price'];
            $part_data = ['part_number' => $part_number, 'buy_price' => $buy_price];

            $total_stock = 0;
            $total_sales = 0;

            foreach ($warehouses as $table => $location) {
                // Ambil quantity dari data stok yang sudah di-query
                $quantity = isset($all_stock_data[$part_number][$location]) ? $all_stock_data[$part_number][$location] : 0;
                $part_data[$location] = $quantity;
                $total_stock += $quantity;

                // Ambil data penjualan
                $sales_qty = isset($sales_data[$part_number][$location]) ? (int)$sales_data[$part_number][$location] : 0;
                $part_data[$location . '_sales'] = $sales_qty;
                $total_sales += $sales_qty;
            }

            $part_data['Total'] = $total_stock;
            $part_data['Total_sales'] = $total_sales;
            $part_data['Amount'] = $total_stock * $buy_price;
            $inventory_data[] = $part_data;
        }

        // 5. Hitung total per kolom
        $column_totals = array_fill_keys(array_keys($warehouses), 0);
        foreach ($warehouses as $location) {
            $column_totals[$location] = 0;
            $column_totals[$location . '_sales'] = 0;
        }
        $column_totals['Total'] = 0;
        $column_totals['Total_sales'] = 0;
        $column_totals['Amount'] = 0;

        foreach ($inventory_data as $part_data) {
            foreach ($warehouses as $location) {
                $column_totals[$location] += $part_data[$location];
                $column_totals[$location . '_sales'] += $part_data[$location . '_sales'];
            }
            $column_totals['Total'] += $part_data['Total'];
            $column_totals['Total_sales'] += $part_data['Total_sales'];
            $column_totals['Amount'] += $part_data['Amount'];
        }
        
        // 6. Hitung ringkasan berdasarkan keyword
        foreach ($summary_keywords as $keyword) {
            $keyword_summaries[$keyword] = ['total_sales' => 0, 'contribution_percentage' => 0];
        }
        foreach ($inventory_data as $item) {
            foreach ($summary_keywords as $keyword) {
                if (stripos($item['part_number'], $keyword) !== false) {
                    $keyword_summaries[$keyword]['total_sales'] += $item['Total_sales'];
                }
            }
        }
        $grand_total_sales_for_contribution = $column_totals['Total_sales'];
        if ($grand_total_sales_for_contribution > 0) {
            foreach ($keyword_summaries as &$data) {
                $data['contribution_percentage'] = ($data['total_sales'] / $grand_total_sales_for_contribution) * 100;
            }
            unset($data);
        }
    }

} catch (Exception $e) {
    $error = $e->getMessage();
} finally {
    if (isset($conn)) {
        $conn->close();
    }
}
// ========================================================================
// AKHIR DARI PROSES PENGAMBILAN & PENGOLAHAN DATA
// ========================================================================


// Cek apakah request export Excel
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    if (!empty($error)) {
        // Jika ada error, jangan lanjutkan ekspor
        die("Export failed due to an error: " . htmlspecialchars($error));
    }

    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // === [FIX] DEFINISIKAN STYLE YANG HILANG ===
    $headerStyle = [
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
        'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '3498DB']],
        'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER],
        'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
    ];
    $dataStyle = [
        'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
    ];
    $salesStyle = [
        'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => 'FFF2CC']]
    ];
    $totalStyle = [
        'font' => ['bold' => true],
        'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => 'E8F4FC']],
        'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
    ];
    // === AKHIR DARI FIX ===

    $sheet->setTitle('Inventory Report');

    // -- Bagian Summary Dashboard --
    $currentExcelRow = 1;
    $sheet->setCellValue('A' . $currentExcelRow, 'Sales Summary by Keywords (' . date('M Y', strtotime($start_date)) . ')');
    $sheet->mergeCells('A' . $currentExcelRow . ':C' . $currentExcelRow);
    $sheet->getStyle('A' . $currentExcelRow)->getFont()->setBold(true)->setSize(14);
    $sheet->getStyle('A' . $currentExcelRow)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
    $currentExcelRow++;
    
    $summaryHeaderRow = $currentExcelRow;
    $sheet->setCellValue('A' . $summaryHeaderRow, 'Keyword');
    $sheet->setCellValue('B' . $summaryHeaderRow, 'Total Sales');
    $sheet->setCellValue('C' . $summaryHeaderRow, 'Contribution %');
    $sheet->getStyle('A' . $summaryHeaderRow . ':C' . $summaryHeaderRow)->applyFromArray([
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF'], 'size' => 10],
        'fill' => ['fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID, 'startColor' => ['rgb' => '5cb85c']],
        'borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN]]
    ]);
    $currentExcelRow++;

    foreach ($summary_keywords as $keyword) {
        $sheet->setCellValue('A' . $currentExcelRow, $keyword);
        $sheet->setCellValue('B' . $currentExcelRow, $keyword_summaries[$keyword]['total_sales']);
        $sheet->setCellValue('C' . $currentExcelRow, $keyword_summaries[$keyword]['contribution_percentage'] / 100);
        $sheet->getStyle('C' . $currentExcelRow)->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_PERCENTAGE_00);
        $currentExcelRow++;
    }
    $sheet->getStyle('A'.($summaryHeaderRow+1).':C'.($currentExcelRow-1))->applyFromArray($dataStyle);


    // -- Bagian Laporan Utama --
    $currentExcelRow += 2; // Spasi
    $mainHeaderRow = $currentExcelRow;

    $sheet->setCellValue('A' . $mainHeaderRow, 'Part Number');
    $sheet->setCellValue('B' . $mainHeaderRow, 'Buy Price');
    $col = 'C';
    foreach ($warehouses as $location) {
        $sheet->setCellValue($col . $mainHeaderRow, $location . ' Stock'); $col++;
        $sheet->setCellValue($col . $mainHeaderRow, $location . ' Sales'); $col++;
    }
    $sheet->setCellValue($col . $mainHeaderRow, 'Total Stock'); $col++;
    $sheet->setCellValue($col . $mainHeaderRow, 'Total Sales'); $col++;
    $sheet->setCellValue($col . $mainHeaderRow, 'Amount');
    
    $lastCol = $col;
    $sheet->getStyle('A' . $mainHeaderRow . ':' . $lastCol . $mainHeaderRow)->applyFromArray($headerStyle);
    $currentExcelRow++;
    
    $firstDataRow = $currentExcelRow;
    foreach ($inventory_data as $part_data) {
        $sheet->setCellValue('A' . $currentExcelRow, $part_data['part_number']);
        $sheet->setCellValue('B' . $currentExcelRow, $part_data['buy_price'])->getStyle('B'.$currentExcelRow)->getNumberFormat()->setFormatCode('#,##0.00');
        
        $data_col = 'C';
        foreach ($warehouses as $location) {
            $sheet->setCellValue($data_col . $currentExcelRow, $part_data[$location]); $data_col++;
            $sheet->setCellValue($data_col . $currentExcelRow, $part_data[$location . '_sales']); $data_col++;
        }
        $sheet->setCellValue($data_col . $currentExcelRow, $part_data['Total']); $data_col++;
        $sheet->setCellValue($data_col . $currentExcelRow, $part_data['Total_sales']); $data_col++;
        $sheet->setCellValue($data_col . $currentExcelRow, $part_data['Amount'])->getStyle($data_col.$currentExcelRow)->getNumberFormat()->setFormatCode('#,##0.00');
        $currentExcelRow++;
    }
    $lastDataRow = $currentExcelRow - 1;

    // Total Row
    $totalRow = $currentExcelRow;
    $sheet->setCellValue('A' . $totalRow, 'GRAND TOTAL')->mergeCells('A'.$totalRow.':B'.$totalRow);

    $data_col = 'C';
    foreach ($warehouses as $location) {
        $sheet->setCellValue($data_col . $totalRow, $column_totals[$location]); $data_col++;
        $sheet->setCellValue($data_col . $totalRow, $column_totals[$location . '_sales']); $data_col++;
    }
    $sheet->setCellValue($data_col . $totalRow, $column_totals['Total']); $data_col++;
    $sheet->setCellValue($data_col . $totalRow, $column_totals['Total_sales']); $data_col++;
    $sheet->setCellValue($data_col . $totalRow, $column_totals['Amount'])->getStyle($data_col.$totalRow)->getNumberFormat()->setFormatCode('#,##0.00');
    
    // Apply styles to data and total rows
    $sheet->getStyle('A' . $firstDataRow . ':' . $lastCol . $lastDataRow)->applyFromArray($dataStyle);
    $sheet->getStyle('A' . $totalRow . ':' . $lastCol . $totalRow)->applyFromArray($totalStyle);
    
    // Apply sales cell styling
    $col_idx = 'D'; // Kolom sales pertama
    for ($i = 0; $i < count($warehouses); $i++) {
        $sheet->getStyle($col_idx . $firstDataRow . ':' . $col_idx . $totalRow)->applyFromArray($salesStyle);
        $col_idx = chr(ord($col_idx) + 2); // Loncat 2 kolom
    }
    // Total sales column
    $sheet->getStyle(chr(ord($lastCol)-1) . $firstDataRow . ':' . chr(ord($lastCol)-1) . $totalRow)->applyFromArray($salesStyle);

    // Set Column Widths
    $sheet->getColumnDimension('A')->setWidth(25);
    $sheet->getColumnDimension('B')->setWidth(15);
    $col = 'C';
    for ($i = 0; $i < count($warehouses) + 2; $i++) {
        $sheet->getColumnDimension($col)->setWidth(12);
        $col++;
    }
    $sheet->getColumnDimension($col)->setWidth(18); // Amount Column

    // Redirect output to a client's web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="inventory_report_with_sales_' . date('YmdHis') . '.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output');
    exit;
}

?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inventory All Warehouse with Sales Data</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 20px;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 10px;
            max-width: 100%;
            margin: 0 auto;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        h1, h2 {
            text-align: center;
            color: #2c3e50;
            margin-bottom: 20px;
        }
        .error-message {
            background-color: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            border: 1px solid #f5c6cb;
        }
        .table-container {
            max-height: 70vh;
            overflow: auto;
            margin-top: 20px;
            position: relative;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        thead {
            position: sticky;
            top: 0;
            z-index: 10;
        }
        th, td {
            padding: 12px 15px;
            text-align: center;
            border-bottom: 1px solid #ddd;
            white-space: nowrap;
        }
        th {
            background-color: #3498db;
            color: white;
        }
        tbody tr:hover {
            background-color: #f5f5f5;
        }
        .total-row {
            font-weight: bold;
            background-color: #e8f4fc;
        }
        .zero-stock { color: #e74c3c; }
        .search-box {
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        .search-box input {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            width: 300px;
            font-size: 16px;
        }
        .export-btn {
            background-color: #2ecc71;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            text-decoration: none;
            display: inline-block;
        }
        .export-btn:hover { background-color: #27ae60; }
        .no-data {
            text-align: center;
            padding: 20px;
            color: #6c757d;
            font-style: italic;
        }
        .amount, .buy-price { text-align: right; }
        .sales-cell { background-color: #fff2cc !important; }
        .date-filter {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        .date-filter label { font-weight: bold; }
        .date-filter input { padding: 8px; border: 1px solid #ddd; border-radius: 4px; }
        .date-filter button {
            padding: 8px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .date-filter button:hover { background-color: #2980b9; }
        .summary-dashboard {
            background-color: #e6f7ff;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 25px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            max-width: 600px;
            margin-left: auto;
            margin-right: auto;
        }
        .summary-dashboard h2 {
            color: #1a73e8;
            margin-top: 0;
            font-size: 1.3em;
            border-bottom: 2px solid #a0cff7;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }
        .summary-dashboard p { font-size: 0.9em; text-align: center; margin-bottom: 15px; color: #555; }
        .summary-table { width: 100%; border-collapse: collapse; font-size: 0.9em; }
        .summary-table th, .summary-table td { padding: 10px 12px; text-align: left; border: 1px solid #cceeff; }
        .summary-table th { background-color: #66b3ff; color: white; text-align: center;}
        .summary-table tr:nth-child(even) { background-color: #f0faff; }
        .summary-table .keyword-cell { font-weight: bold; color: #333; }
        .summary-table .sales-quantity-cell, .summary-table .percentage-cell { text-align: center; }

        @media (max-width: 768px) {
            body { padding: 10px; }
            .container { padding: 10px; }
            .date-filter, .search-box { flex-direction: column; gap: 10px; align-items: stretch;}
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Inventory Summary with Sales Data (Category ID: 7)</h1>

        <?php if (!empty($error)): ?>
            <div class="error-message">
                <strong>Error:</strong> <?= htmlspecialchars($error) ?>
            </div>
        <?php endif; ?>

        <div class="date-filter">
            <form method="GET" action="" style="display: contents;">
                <label for="start_date">Start Date:</label>
                <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>">

                <label for="end_date">End Date:</label>
                <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>">

                <button type="submit">Filter</button>
            </form>
            <a href="?export=excel&start_date=<?= urlencode($start_date) ?>&end_date=<?= urlencode($end_date) ?>" class="export-btn">Export to Excel</a>
        </div>
        
        <?php if (empty($error) && !empty($inventory_data)): ?>
            <div class="summary-dashboard">
                <h2>Total Sales Summary by Keywords</h2>
                <p>Periode: <strong><?= htmlspecialchars(date('d M Y', strtotime($start_date))) ?></strong> - <strong><?= htmlspecialchars(date('d M Y', strtotime($end_date))) ?></strong></p>
                <table class="summary-table">
                    <thead>
                        <tr>
                            <th>Keyword</th>
                            <th>Total Sales</th>
                            <th>Contribution %</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($summary_keywords as $keyword): ?>
                            <tr>
                                <td class="keyword-cell">"<?= htmlspecialchars($keyword) ?>"</td>
                                <td class="sales-quantity-cell"><?= number_format($keyword_summaries[$keyword]['total_sales']) ?></td>
                                <td class="percentage-cell"><?= number_format($keyword_summaries[$keyword]['contribution_percentage'], 2) ?>%</td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <div class="search-box">
                <input type="text" id="searchInput" placeholder="Cari berdasarkan part number..." onkeyup="searchTable()">
            </div>

            <div class="table-container">
                <table id="inventoryTable">
                    <thead>
                        <tr>
                            <th>Part Number</th>
                            <th>Buy Price</th>
                            <?php foreach ($warehouses as $location): ?>
                                <th><?= htmlspecialchars($location) ?> Stock</th>
                                <th class="sales-cell"><?= htmlspecialchars($location) ?> Sales</th>
                            <?php endforeach; ?>
                            <th>Total Stock</th>
                            <th class="sales-cell">Total Sales</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($inventory_data as $part_data): ?>
                            <tr>
                                <td><?= htmlspecialchars($part_data['part_number']) ?></td>
                                <td class="buy-price"><?= number_format($part_data['buy_price'], 2) ?></td>
                                <?php foreach ($warehouses as $location): ?>
                                    <td class="<?= $part_data[$location] <= 0 ? 'zero-stock' : '' ?>"><?= $part_data[$location] ?></td>
                                    <td class="sales-cell"><?= $part_data[$location.'_sales'] ?></td>
                                <?php endforeach; ?>
                                <td><?= $part_data['Total'] ?></td>
                                <td class="sales-cell"><?= $part_data['Total_sales'] ?></td>
                                <td class="amount"><?= number_format($part_data['Amount'], 2) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="total-row">
                            <td colspan="2">GRAND TOTAL</td>
                            <?php foreach ($warehouses as $location): ?>
                                <td><?= $column_totals[$location] ?></td>
                                <td class="sales-cell"><?= $column_totals[$location.'_sales'] ?></td>
                            <?php endforeach; ?>
                            <td><?= $column_totals['Total'] ?></td>
                            <td class="sales-cell"><?= $column_totals['Total_sales'] ?></td>
                            <td class="amount"><?= number_format($column_totals['Amount'], 2) ?></td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        <?php elseif(empty($error)): ?>
            <div class="no-data">
                Tidak ada data inventory yang ditemukan untuk kategori atau periode yang dipilih.
            </div>
        <?php endif; ?>
    </div>

    <script>
        function searchTable() {
            let input = document.getElementById("searchInput");
            let filter = input.value.toUpperCase();
            let table = document.getElementById("inventoryTable");
            let tr = table.getElementsByTagName("tr");

            // Loop melalui semua baris data (tbody), lewati header (thead) dan footer (tfoot)
            for (let i = 0; i < tr.length; i++) {
                if (tr[i].parentNode.nodeName === 'TBODY') {
                    let td = tr[i].getElementsByTagName("td")[0]; // Kolom Part Number
                    if (td) {
                        let txtValue = td.textContent || td.innerText;
                        if (txtValue.toUpperCase().indexOf(filter) > -1) {
                            tr[i].style.display = "";
                        } else {
                            tr[i].style.display = "none";
                        }
                    }
                }
            }
        }
    </script>
</body>
</html>