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

$products = find_all('products'); // Retrieve distinct products for dropdown

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']);
    $buy_price = $db->escape($_POST['buy_price']);
    
    $errors = [];
    $child_boms = isset($_POST['child_bom']) ? $_POST['child_bom'] : [];
    $qtys = isset($_POST['qty']) ? $_POST['qty'] : [];

    // Validate input
    if (empty($child_boms)) {
        $errors[] = "Please enter at least one child BOM.";
    } else {
        // Iterate through each child BOM input
        foreach ($child_boms as $key => $child_bom) {
            $child_bom = $db->escape($child_bom);
            $qty = isset($qtys[$key]) ? $db->escape($qtys[$key]) : '0';

            // Insert into database
            $sql = "INSERT INTO bom_level_rnd (parent_bom, child_bom, phantom_bom, level, qty, location, buy_price) 
                    VALUES ('$parent_bom', '$child_bom', '$phantom_bom', '$level', '$qty', '$location', '$buy_price')";
            $result = $db->query($sql);

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

    if (empty($errors)) {
        // Send email notification
        require 'send_bom_email.php'; // Ensure this file is in the same directory
        $email_sent = send_bom_email($parent_bom, $phantom_bom, $level, $child_boms, $qtys, $location, $buy_price);

        if ($email_sent) {
            $session->msg('s', 'BOM added and email sent successfully!');
        } else {
            $session->msg('w', 'BOM added, but email could not be sent.');
        }

        redirect('create_bom_rnd.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">Create BOM</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="create_bom_rnd.php" class="clearfix">
                    <div class="form-group">
                        <label for="parent_bom">Product:</label>
                        <input type="text" class="form-control" name="parent_bom" id="parent_bom" placeholder="Search for a product">
                    </div>
                    <div class="form-group">
                        <label for="level">Level:</label>
                        <input type="number" class="form-control" name="level" required>
                    </div>
                    <div class="form-group">
                        <label for="location">Location:</label>
                        <input type="text" class="form-control" name="location">
                    </div>
                    <div class="form-group">
                        <label for="buy_price">Buy Price:</label>
                        <input type="text" class="form-control" name="buy_price">
                    </div>
                    <div id="child_boms_container">
                        <!-- Dynamic child BOM entries will be added here -->
                    </div>
                    <button type="button" id="add_child_bom" class="btn btn-secondary">Add Another Child BOM</button>
                    <div class="form-group">
                        <label class="checkbox-inline">
                            <input type="checkbox" name="phantom_bom" value="1"> Phantom BOM
                        </label>
                    </div>
                    <button type="submit" class="btn btn-primary">Create BOM</button>
                </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;
    }

    /* Additional styles for horizontal layout */
    .form-group {
        margin-bottom: 15px;
    }

    .form-row {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 10px;
    }
</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-row', 'child_bom_entry');
        newChildBomEntry.innerHTML = `
            <div class="col">
                <label for="child_bom">Child BOM:</label>
                <input type="text" class="form-control child-bom-autocomplete" name="child_bom[]" placeholder="Search for a product" required>
            </div>
            <div class="col">
                <label for="qty">Quantity:</label>
                <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'); ?>
