<?php
$page_title = 'Edit BOM';
require_once('includes/load.php');
page_require_level(2); // Hanya izinkan user level 2 atau lebih tinggi

// Ambil ID BOM dari parameter URL
$bom_id = (int)$_GET['id'];

// Periksa apakah ID valid
if (!$bom_id) {
    $session->msg("d", "Missing BOM ID.");
    redirect('bom_list.php');
}

// Ambil data BOM berdasarkan ID
$bom = find_by_id('bom_level', $bom_id);
if (!$bom) {
    $session->msg("d", "BOM not found!");
    redirect('bom_list.php');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $parent_bom = $db->escape($_POST['parent_bom']);
    $phantom_bom = isset($_POST['phantom_bom']) ? '1' : '0';
    $level = (int)$_POST['level'];
    $location = $db->escape($_POST['location']);

    // Validate input
    if (empty($_POST['child_bom'])) {
        $errors[] = "Please enter at least one child BOM.";
    } else {
        $child_boms = $_POST['child_bom'];
        $qtys = $_POST['qty'];

        // Hapus semua BOM anak yang terkait dengan BOM ini
        $delete_sql = "DELETE FROM bom_level WHERE parent_bom = '{$parent_bom}'";
        $delete_result = $db->query($delete_sql);

        if (!$delete_result) {
            $errors[] = "Failed to update BOM. Please try again.";
        } else {
            // Insert BOM baru berdasarkan data yang di-posting
            foreach ($child_boms as $key => $child_bom) {
                $child_bom = $db->escape($child_bom);
                $qty = $db->escape($qtys[$key]);

                $sql = "INSERT INTO bom_level (parent_bom, child_bom, phantom_bom, level, qty, location)
                        VALUES ('$parent_bom', '$child_bom', '$phantom_bom', '$level', '$qty', '$location')";
                $result = $db->query($sql);

                if (!$result) {
                    $errors[] = "Failed to add BOM for child BOM: $child_bom";
                }
            }

            if (empty($errors)) {
                $session->msg('s', 'BOM updated successfully!');
                redirect('bom_list.php', false);
            } else {
                $session->msg('d', implode("<br>", $errors));
            }
        }
    }
}

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">Edit BOM</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="edit_bom.php?id=<?php echo (int)$bom['id']; ?>" class="clearfix">
                    <div class="form-group row">
                        <label for="parent_bom" class="col-sm-2 col-form-label">Parent BOM:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="parent_bom" id="parent_bom" value="<?php echo htmlspecialchars($bom['parent_bom']); ?>" readonly>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="level" class="col-sm-2 col-form-label">Level:</label>
                        <div class="col-sm-10">
                            <input type="number" class="form-control" name="level" value="<?php echo htmlspecialchars($bom['level']); ?>" required>
                        </div>
                    </div>
                    <div class="form-group row">
                        <label for="location" class="col-sm-2 col-form-label">Location:</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="location" value="<?php echo htmlspecialchars($bom['location']); ?>">
                        </div>
                    </div>
                    <div id="child_boms_container">
                        <!-- Dynamic child BOM entries will be added here -->
                        <?php
                        // Ambil semua BOM anak berdasarkan parent BOM yang dipilih
                        $child_boms = find_by_sql("SELECT * FROM bom_level WHERE parent_bom = '{$bom['parent_bom']}'");
                        foreach ($child_boms as $child_bom_item) :
                        ?>
                            <div class="form-group row child_bom_entry">
                                <label for="child_bom" class="col-sm-2 col-form-label">Child BOM:</label>
                                <div class="col-sm-4">
                                    <input type="text" class="form-control child-bom-autocomplete" name="child_bom[]" value="<?php echo htmlspecialchars($child_bom_item['child_bom']); ?>" readonly>
                                </div>
                                <label for="qty" class="col-sm-2 col-form-label">Quantity:</label>
                                <div class="col-sm-4">
                                    <input type="text" class="form-control" name="qty[]" value="<?php echo htmlspecialchars($child_bom_item['qty']); ?>" step="0.01" required>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <button type="button" id="add_child_bom" class="btn btn-secondary">Add Another Child BOM</button>
                    <div class="form-group row">
                        <div class="col-sm-10 offset-sm-2">
                            <label class="checkbox-inline">
                                <input type="checkbox" name="phantom_bom" value="1" <?php if ($bom['phantom_bom'] == '1') echo 'checked'; ?>> Phantom BOM
                            </label>
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-10 offset-sm-2">
                            <button type="submit" class="btn btn-primary">Update BOM</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<style>
    /* Styles for autocomplete suggestions */
    .suggestions {
        position: absolute;
        width: 100%;
        max-height: 200px;
        overflow-y: auto;
        border: 1px solid #ccc;
        background-color: white;
        z-index: 1;
    }

    .suggestion {
        padding: 10px;
        cursor: pointer;
        transition: background-color 0.2s;
    }

    .suggestion:hover {
        background-color: #f5f5f5;
    }
</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">

<script>
$(document).ready(function() {
    const addChildBomButton = document.getElementById('add_child_bom');
    const childBomsContainer = document.getElementById('child_boms_container');

    function addChildBomEntry() {
        const newChildBomEntry = document.createElement('div');
        newChildBomEntry.classList.add('form-group', 'row', 'child_bom_entry');
        newChildBomEntry.innerHTML = `
            <label for="child_bom" class="col-sm-2 col-form-label">Child BOM:</label>
            <div class="col-sm-4">
                <input type="text" class="form-control child-bom-autocomplete" name="child_bom[]" placeholder="Search for a product" required>
            </div>
            <label for="qty" class="col-sm-2 col-form-label">Quantity:</label>
            <div class="col-sm-4">
                <input type="text" class="form-control" name="qty[]" step="0.01" required>
            </div>
        `;
        childBomsContainer.appendChild(newChildBomEntry);
        
        // Enable autocomplete for the newly added child BOM input
        $( ".child-bom-autocomplete" ).autocomplete({
            source: "autocomplete.php", // Ganti dengan URL yang benar untuk sumber data autocomplete
            minLength: 1
        });
    }

    addChildBomButton.addEventListener('click', addChildBomEntry);
});
</script>

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