<?php
require 'vendor/autoload.php';
require_once('includes/load.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$page_title = 'Single Where Use List';
page_require_level(2);

// Query untuk mendapatkan semua produk dari tabel products
$products = find_all('products');

// Cek apakah tombol export Excel diklik
if (isset($_GET['export']) && $_GET['export'] === 'excel') {
    // Membuat objek Spreadsheet baru
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // Menambahkan header ke kolom
    $sheet->setCellValue('A1', 'Part Number');
    $sheet->setCellValue('B1', 'Name');
    $sheet->setCellValue('C1', 'Used In');

    // Menambahkan data produk ke dalam sheet
    $row = 2; // Mulai dari baris kedua
    foreach ($products as $product) {
        $sheet->setCellValue('A' . $row, $product['part_number']);
        $sheet->setCellValue('B' . $row, $product['name']);
        
        // Query untuk mendapatkan daftar parent BOM di mana produk ini digunakan
        $where_used_list = get_where_used_list($product['part_number']);
        $parent_boms = !empty($where_used_list) ? implode(', ', array_column($where_used_list, 'parent_bom')) : 'Not used in any BOM';
        $sheet->setCellValue('C' . $row, $parent_boms);

        $row++;
    }

    // Menyiapkan penulisan file Excel
    $writer = new Xlsx($spreadsheet);

    // Mengirim output sebagai file Excel
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="where_used_list.xlsx"');
    header('Cache-Control: max-age=0');

    $writer->save('php://output');
    exit;
}

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

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Single Where Use List</h3>
                <button type="button" class="btn btn-success pull-right" id="exportCsvBtn">Export to CSV</button>
                <a href="?export=excel" class="btn btn-primary pull-right" style="margin-right: 10px;">Export to Excel</a>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-hover" id="whereUsedListTable">
                    <thead>
                        <tr>
                            <th>Part Number</th>
                            <th>Name</th>
                            <th>Used In</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product) : ?>
                            <tr>
                                <td><?php echo htmlspecialchars($product['part_number']); ?></td>
                                <td><?php echo htmlspecialchars($product['name']); ?></td>
                                <td>
                                    <?php
                                    // Query untuk mendapatkan daftar parent BOM di mana produk ini digunakan
                                    $where_used_list = get_where_used_list($product['part_number']);
                                    if (!empty($where_used_list)) {
                                        $parent_boms = array_column($where_used_list, 'parent_bom');
                                        echo implode(', ', $parent_boms);
                                    } else {
                                        echo 'Not used in any BOM';
                                    }
                                    ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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

<script>
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('exportCsvBtn').addEventListener('click', function () {
        var table = document.getElementById('whereUsedListTable');
        var rows = table.querySelectorAll('tr');
        var csv = [];

        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll('td, th');
            for (var j = 0; j < cols.length; j++) {
                row.push(cols[j].innerText);
            }
            csv.push(row.join(','));
        }

        var csvContent = csv.join('\n');
        var blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        var link = document.createElement('a');
        var url = URL.createObjectURL(blob);
        link.setAttribute('href', url);
        link.setAttribute('download', 'where_used_list.csv');
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
});
</script>
