<?php
$page_title = 'View BOM';
require_once('includes/load.php');
page_require_level(5);

// Initialize variables
$search_query = '';
if (isset($_POST['search'])) {
    $search_query = $_POST['search'];
}

// Fetch BOM data from bom_level_rnd table with optional search
$sql = "SELECT * FROM bom_level_rnd";
if ($search_query) {
    $sql .= " WHERE parent_bom LIKE '%" . $db->escape($search_query) . "%'";
}
$results = $db->query($sql);

// Handle Excel export
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    require 'vendor/autoload.php'; // Include the PHPSpreadsheet library

    // Create a new Spreadsheet object
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    // Set the column headers
    $headers = [
        'ID',
        'Parent BOM',
        'Child BOM',
        'Phantom BOM',
        'Level',
        'Quantity',
        'Location',
        'Buy Price',
        'Last Update',
        'Action'
    ];
    $sheet->fromArray($headers, NULL, 'A1');

    // Populate the data
    $row = 2; // Start from the second row
    while ($row_data = $results->fetch_assoc()) {
        $sheet->setCellValue('A' . $row, (int)$row_data['id']);
        $sheet->setCellValue('B' . $row, htmlspecialchars($row_data['parent_bom']));
        $sheet->setCellValue('C' . $row, htmlspecialchars($row_data['child_bom']));
        $sheet->setCellValue('D' . $row, $row_data['phantom_bom'] ? 'Yes' : 'No');
        $sheet->setCellValue('E' . $row, (int)$row_data['level']);
        $sheet->setCellValue('F' . $row, number_format((float)$row_data['qty'], 4));
        $sheet->setCellValue('G' . $row, htmlspecialchars($row_data['location']));
        $sheet->setCellValue('H' . $row, number_format((float)$row_data['buy_price'], 2));
        $sheet->setCellValue('I' . $row, htmlspecialchars($row_data['last_update']));
        $sheet->setCellValue('J' . $row, 'Edit/Delete'); // Placeholder for actions
        $row++;
    }

    // Set the content type and headers for the Excel file
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="bom_data.xlsx"');
    header('Cache-Control: max-age=0');

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

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

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">View BOM</h3>
                <!-- Add the export button -->
                <a href="?export=excel" class="btn btn-success btn-sm pull-right">Export to Excel</a>
            </div>
            <div class="panel-body">
                <!-- Search form -->
                <form method="POST" class="form-inline mb-3">
                    <input type="text" name="search" class="form-control" placeholder="Search Parent BOM" value="<?php echo htmlspecialchars($search_query); ?>">
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Parent BOM</th>
                            <th>Child BOM</th>
                            <th>Phantom BOM</th>
                            <th>Level</th>
                            <th>Quantity</th>
                            <th>Location</th>
                            <th>Buy Price</th>
                            <th>Last Update</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($results->num_rows > 0): ?>
                            <?php while($row = $results->fetch_assoc()): ?>
                                <tr>
                                    <td><?php echo (int)$row['id']; ?></td>
                                    <td><?php echo htmlspecialchars($row['parent_bom']); ?></td>
                                    <td><?php echo htmlspecialchars($row['child_bom']); ?></td>
                                    <td><?php echo $row['phantom_bom'] ? 'Yes' : 'No'; ?></td>
                                    <td><?php echo (int)$row['level']; ?></td>
                                    <td><?php echo number_format((float)$row['qty'], 4); ?></td>
                                    <td><?php echo htmlspecialchars($row['location']); ?></td>
                                    <td><?php echo number_format((float)$row['buy_price'], 2); ?></td>
                                    <td><?php echo htmlspecialchars($row['last_update']); ?></td>
                                    <td>
                                        <a href="edit_bom_rnd.php?id=<?php echo (int)$row['id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                                        <a href="delete_bom_rnd.php?id=<?php echo (int)$row['id']; ?>" class="btn btn-danger btn-sm">Delete</a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="10">No BOM records found.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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