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

$page_title = 'Create BOM';
require_once('includes/load.php');
page_require_level(1);

// Pastikan pustaka PhpSpreadsheet sudah diinstal via Composer
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;

// Bagian 1: Logika Autosuggestion (permintaan Ajax)
if (isset($_GET['term'])) {
    $search_term = $db->escape($_GET['term']);
    
    // Mengambil part_number DAN nama produk
    $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']) . ' - ' . remove_junk($row['name']),
            'value' => htmlspecialchars($row['part_number']),
            'name'  => htmlspecialchars($row['name'])
        ];
    }
    
    header('Content-Type: application/json');
    echo json_encode($products);
    exit;
}

// Bagian 2: Logika Pemrosesan Formulir Manual (permintaan POST)
if (isset($_POST['submit_bom'])) {
    $parent_bom = $_POST['parent_bom'];
    $child_boms = $_POST['child_bom'];
    $quantities = $_POST['quantity'];
    
    $errors = [];
    
    if (empty($parent_bom) || empty($child_boms)) {
        $errors[] = "Harap isi semua kolom parent BOM dan tambahkan setidaknya satu child BOM.";
    }

    try {
        $db->begin_transaction();

        for ($i = 0; $i < count($child_boms); $i++) {
            $child_bom = trim($child_boms[$i]);
            $quantity = (float)$quantities[$i];

            if (empty($child_bom) || !is_numeric($quantity) || $quantity <= 0) {
                $errors[] = "Baris ke-" . ($i + 1) . ": Nomor bagian anak dan jumlah harus valid.";
                continue;
            }

            // Memasukkan data ke tabel bom_level
            $sql_insert_bom = "INSERT INTO bom_level (parent_bom, child_bom, qty)
                               VALUES (
                                    '{$db->escape($parent_bom)}',
                                    '{$db->escape($child_bom)}',
                                    '{$quantity}'
                               )";
            $db->query($sql_insert_bom);
        }

        if (empty($errors)) {
            $db->commit();
            $session->msg('s', 'BOM berhasil dibuat.');
            redirect('create_bom.php', false);
        } else {
            $db->rollback();
            $session->msg('d', 'Gagal membuat BOM:<br>' . implode('<br>', $errors));
            redirect('create_bom.php', false);
        }

    } catch (Exception $e) {
        $db->rollback();
        $session->msg('d', 'Gagal memproses transaksi: ' . $e->getMessage());
        redirect('create_bom.php', false);
    }
}

// Bagian 3: Logika Pemrosesan Impor Excel (permintaan POST)
if (isset($_POST['import_excel'])) {
    if (empty($_FILES['excel_file']['name'])) {
        $session->msg('d', 'Harap pilih file Excel untuk diimpor.');
        redirect('create_bom.php', false);
    }

    $file_path = $_FILES['excel_file']['tmp_name'];
    $extension = pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION);

    if (!in_array($extension, ['xlsx', 'xls'])) {
        $session->msg('d', 'Format file tidak didukung. Harap unggah file .xlsx atau .xls.');
        redirect('create_bom.php', false);
    }

    try {
        $spreadsheet = IOFactory::load($file_path);
        $worksheet = $spreadsheet->getActiveSheet();
        $highestRow = $worksheet->getHighestRow();

        $db->begin_transaction();
        $imported_count = 0;
        $errors = [];

        // Membaca data dari baris ke-2 (mengabaikan header)
        for ($row = 2; $row <= $highestRow; $row++) {
            $parent_bom = trim($worksheet->getCell('A' . $row)->getValue());
            $child_bom = trim($worksheet->getCell('B' . $row)->getValue());
            $quantity = (float)$worksheet->getCell('C' . $row)->getValue();

            if (empty($parent_bom) || empty($child_bom) || !is_numeric($quantity) || $quantity <= 0) {
                $errors[] = "Baris " . $row . ": Data tidak valid (parent, child, atau quantity kosong/tidak valid).";
                continue;
            }

            $sql_insert_bom = "INSERT INTO bom_level (parent_bom, child_bom, qty)
                               VALUES (
                                    '{$db->escape($parent_bom)}',
                                    '{$db->escape($child_bom)}',
                                    '{$quantity}'
                               )";
            if ($db->query($sql_insert_bom)) {
                $imported_count++;
            } else {
                $errors[] = "Baris " . $row . ": Gagal menyimpan data ke database.";
            }
        }

        if (empty($errors)) {
            $db->commit();
            $session->msg('s', "Berhasil mengimpor " . $imported_count . " baris data BOM.");
        } else {
            $db->rollback();
            $session->msg('d', "Gagal mengimpor BOM. " . ($imported_count) . " baris berhasil diproses sebelum kesalahan:<br>" . implode('<br>', $errors));
        }

    } catch (Exception $e) {
        $db->rollback();
        $session->msg('d', 'Gagal memproses file Excel: ' . $e->getMessage());
    }

    redirect('create_bom.php', false);
}
?>

<?php 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">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-list-alt"></span>
                    <span>Buat Bill of Materials (BOM)</span>
                </strong>
            </div>
            <div class="panel-body">
                <form action="create_bom.php" method="POST" enctype="multipart/form-data" class="form-inline" style="margin-bottom: 20px;">
                    <div class="form-group">
                        <label for="excel_file">Impor BOM dari Excel:</label>
                        <input type="file" name="excel_file" id="excel_file" accept=".xlsx, .xls" required>
                    </div>
                    <button type="submit" name="import_excel" class="btn btn-info">Impor File</button>
                    <a href="templates/bom_template.xlsx" class="btn btn-success" download>
                        <i class="glyphicon glyphicon-download-alt"></i> Unduh Template
                    </a>
                </form>

                <hr>

                <form action="create_bom.php" method="POST">
                    <div class="form-group row">
                        <div class="col-md-6">
                            <label for="parent_bom">Produk (Parent BOM):</label>
                            <input type="text" class="form-control" name="parent_bom" id="parent_bom" placeholder="Ketik part number atau nama produk..." required>
                        </div>
                        <div class="col-md-6">
                            <label for="parent_bom_name">Nama Produk:</label>
                            <input type="text" class="form-control" id="parent_bom_name" readonly>
                        </div>
                    </div>

                    <hr>
                    
                    <h4 class="text-center" style="margin-bottom: 20px;">Daftar Komponen (Child BOM)</h4>
                    
                    <div class="row header-row" style="font-weight: bold; margin-bottom: 10px;">
                        <div class="col-md-4">Komponen (Part Number)</div>
                        <div class="col-md-4">Nama Produk</div>
                        <div class="col-md-2">Jumlah</div>
                        <div class="col-md-2">Aksi</div>
                    </div>
                    
                    <div id="form-container">
                        <div class="form-row row" style="margin-bottom: 10px;">
                            <div class="col-md-4">
                                <input type="text" class="form-control child-bom-input" name="child_bom[]" placeholder="Ketik part number atau nama produk..." required>
                            </div>
                            <div class="col-md-4">
                                <input type="text" class="form-control child-bom-name" readonly>
                            </div>
                            <div class="col-md-2">
                                <input type="number" step="0.01" class="form-control" name="quantity[]" placeholder="Jumlah" required>
                            </div>
                            <div class="col-md-2">
                                <button type="button" class="btn btn-danger btn-remove-row" style="display:none;">Hapus</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="clearfix">
                        <button type="button" id="add-row-btn" class="btn btn-success" style="margin-top: 15px;">Tambah Baris</button>
                        <button type="submit" name="submit_bom" class="btn btn-primary pull-right" style="margin-top: 15px;">Buat BOM</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<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: "create_bom.php",
            minLength: 2,
            select: function(event, ui) {
                // Cari input nama di dalam grup/baris yang sama
                if (ui.item) {
                    var $row = $(this).closest('.row');
                    $row.find('input[type="text"][readonly]').val(ui.item.name);
                }
            }
        });
    }

    // Inisialisasi autocomplete untuk parent BOM
    initAutocomplete($("#parent_bom"));

    // Inisialisasi autocomplete untuk baris pertama child BOM
    initAutocomplete($(".child-bom-input"));

    $("#add-row-btn").click(function() {
        var newRow = $(".form-row:first").clone();
        
        // Bersihkan nilai input dari baris yang baru
        newRow.find("input").val("");
        
        // Tampilkan tombol "Hapus" pada baris baru
        newRow.find(".btn-remove-row").show();

        $("#form-container").append(newRow);

        // Inisialisasi autocomplete untuk input di baris yang baru
        initAutocomplete(newRow.find(".child-bom-input"));
    });

    $(document).on("click", ".btn-remove-row", function() {
        if ($(".form-row").length > 1) {
            $(this).closest(".form-row").remove();
        } else {
            alert("Tidak bisa menghapus baris terakhir!");
        }
    });
});
</script>

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