<?php
// Tampilkan semua error untuk debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

// MUAT PUSTAKA PHPSpreadsheet DENGAN COMPOSER
require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

// --- BAGIAN FUNGSI-FUNGSI BARU ---

/**
 * Mengambil struktur BOM satu tingkat di bawah parent BOM.
 * @param string $part_number
 * @return array
 */
function fetch_bom_components($part_number) {
    global $db;
    $sql = "SELECT 
                b.child_bom, 
                b.qty, 
                b.id AS bom_id, 
                p.name AS child_name,
                p.buy_price AS buy_price
            FROM bom_level b
            JOIN products p ON b.child_bom = p.part_number
            WHERE b.parent_bom = '{$db->escape($part_number)}'";
    return find_by_sql($sql);
}

/**
 * Mengambil daftar parent BOM di mana part_number tertentu digunakan.
 * @param string $part_number
 * @return array
 */
function fetch_parent_assemblies($part_number) {
    global $db;
    $sql = "SELECT 
                b.parent_bom, 
                b.qty,
                p.name AS parent_name
            FROM bom_level b
            JOIN products p ON b.parent_bom = p.part_number
            WHERE b.child_bom = '{$db->escape($part_number)}'";
    return find_by_sql($sql);
}

/**
 * Mencari nama produk berdasarkan part number.
 * @param string $part_number
 * @return string
 */
function lookup_product_name($part_number) {
    global $db;
    $sql = "SELECT name FROM products WHERE part_number = '{$db->escape($part_number)}' LIMIT 1";
    $result = $db->query($sql);
    if ($row = $db->fetch_assoc($result)) {
        return $row['name'];
    }
    return '';
}

// --- AKHIR BAGIAN FUNGSI-FUNGSI BARU ---

// Bagian 1: Logika Ekspor Excel
if (isset($_POST['export_excel'])) {
    $product_part_number = $_POST['product_for_export'];
    $bom_data = fetch_bom_components($product_part_number);
    $product_name = lookup_product_name($product_part_number);

    if (!empty($bom_data)) {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // Judul Kolom
        $sheet->setCellValue('A1', 'Child BOM');
        $sheet->setCellValue('B1', 'Nama Komponen');
        $sheet->setCellValue('C1', 'Jumlah');
        $sheet->setCellValue('D1', 'Harga Beli');

        $row = 2;
        $total_buy_price = 0;
        foreach ($bom_data as $item) {
            $sheet->setCellValue('A' . $row, $item['child_bom']);
            $sheet->setCellValue('B' . $row, $item['child_name']);
            $sheet->setCellValue('C' . $row, (float) $item['qty']);
            $sheet->setCellValue('D' . $row, (float) $item['buy_price'] * (float) $item['qty']);
            $total_buy_price += (float) $item['buy_price'] * (float) $item['qty'];
            $row++;
        }

        // Tambahkan total harga di bagian bawah
        $sheet->setCellValue('C' . ($row + 1), 'Total');
        $sheet->setCellValue('D' . ($row + 1), $total_buy_price);

        // Atur lebar kolom agar otomatis
        foreach (range('A', 'D') as $column) {
            $sheet->getColumnDimension($column)->setAutoSize(true);
        }

        // Siapkan untuk download
        $filename = "BOM_{$product_name}.xlsx";
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
        
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
}

// Bagian 2: Logika Autosuggestion (permintaan Ajax)
if (isset($_GET['term'])) {
    $search_term = $db->escape($_GET['term']);
    
    $sql = "SELECT part_number, name FROM products WHERE part_number LIKE '%{$search_term}%' OR name LIKE '%{$search_term}%' LIMIT 10";
    $result = find_by_sql($sql);
    
    $products = [];
    foreach ($result as $row) {
        $products[] = [
            'label' => htmlspecialchars($row['part_number']) . ' - ' . ($row['name']),
            'value' => htmlspecialchars($row['part_number']),
            'name'  => $row['name'] // Kirim nama produk asli untuk diisi di input
        ];
    }
    
    header('Content-Type: application/json');
    echo json_encode($products);
    exit;
}

// Bagian 3: Logika Pemrosesan Formulir (permintaan POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['view_bom']) && !empty($_POST['product'])) {
        $selected_product = $db->escape($_POST['product']);
        $bom_structure = fetch_bom_components($selected_product);
        $selected_product_name = lookup_product_name($selected_product);
    } elseif (isset($_POST['view_where_used']) && !empty($_POST['single_product'])) {
        $single_product = $db->escape($_POST['single_product']);
        $single_product_name = lookup_product_name($single_product);
        $where_used_list = fetch_parent_assemblies($single_product);
    }
}

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

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">BOM View</h3>
            </div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-6">
                        <form action="view_bom.php" method="post">
                            <div class="form-group">
                                <label for="product">View BOM for Product:</label>
                                <input type="text" class="form-control" name="product" id="product" placeholder="Cari Part Number/Nama Produk">
                            </div>
                            <button type="submit" name="view_bom" class="btn btn-primary">Lihat BOM</button>
                        </form>
                    </div>
                    <div class="col-md-6">
                        <form action="view_bom.php" method="post">
                            <div class="form-group">
                                <label for="single_product">Where Used for:</label>
                                <input type="text" class="form-control" name="single_product" id="single_product" placeholder="Cari Part Number/Nama Produk">
                            </div>
                            <button type="submit" name="view_where_used" class="btn btn-primary">Lihat Where Used</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php if (isset($bom_structure) && !empty($bom_structure)) : ?>
---
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Struktur BOM untuk **<?php echo htmlspecialchars($selected_product_name); ?>** (<?php echo htmlspecialchars($selected_product); ?>)</h3>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-hover" id="bomTable">
                    <thead>
                        <tr>
                            <th>Child BOM</th>
                            <th>Nama Komponen</th>
                            <th>Jumlah</th>
                            <th>Harga Beli</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $total_buy_price = 0;
                        foreach ($bom_structure as $bom_item) : 
                            $item_price = $bom_item['buy_price'] * $bom_item['qty'];
                            $total_buy_price += $item_price;
                        ?>
                            <tr>
                                <td><?php echo htmlspecialchars($bom_item['child_bom']); ?></td>
                                <td><?php echo htmlspecialchars($bom_item['child_name']); ?></td>
                                <td><?php echo number_format($bom_item['qty'], 2); ?></td>
                                <td><?php echo number_format($item_price, 2); ?></td>
                                <td>
                                    <a href="edit_bom.php?bom_id=<?php echo $bom_item['bom_id']; ?>" class="btn btn-warning btn-sm">Edit</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <div class="panel-footer">
                    <strong>Total Harga Komponen:</strong> <?php echo number_format($total_buy_price, 2); ?>
                </div>
                <form action="view_bom.php" method="post" style="display:inline;">
                    <input type="hidden" name="product_for_export" value="<?php echo htmlspecialchars($selected_product); ?>">
                    <button type="submit" name="export_excel" class="btn btn-success">Export ke Excel</button>
                </form>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<?php if (isset($where_used_list) && !empty($where_used_list)) : ?>
---
<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Digunakan pada **<?php echo htmlspecialchars($single_product_name); ?>** (<?php echo htmlspecialchars($single_product); ?>)</h3>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-hover" id="whereUsedTable">
                    <thead>
                        <tr>
                            <th>Parent BOM</th>
                            <th>Nama Parent</th>
                            <th>Jumlah</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($where_used_list as $where_item) : ?>
                            <tr>
                                <td><?php echo htmlspecialchars($where_item['parent_bom']); ?></td>
                                <td><?php echo htmlspecialchars($where_item['parent_name']); ?></td>
                                <td><?php echo number_format($where_item['qty'], 2); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
    $(document).ready(function() {
        function initAutocomplete(element) {
            $(element).autocomplete({
                source: "view_bom.php",
                minLength: 2,
                select: function(event, ui) {
                    if (ui.item) {
                        // Tidak perlu mengubah input nama produk di sini karena tidak ada
                        // Biarkan hanya input part number yang diisi
                        // `ui.item.value` sudah berisi part_number
                    }
                }
            });
        }
        
        initAutocomplete($("#product"));
        initAutocomplete($("#single_product"));
    });
</script>

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