<?php
$page_title = 'Add Production Output';
require_once('includes/load.php');
page_require_level(3); // Only level 3 access is allowed

// Handle form submission to add production output
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $errors = array();

    $required_fields = array('no_order', 'part_number', 'quantity_produced', 'production_date', 'categorie_id');
    foreach ($required_fields as $field) {
        if (empty($_POST[$field])) {
            $errors[] = ucfirst(str_replace('_', ' ', $field)) . ' is required.';
        }
    }

    if (empty($errors)) {
        $no_order = $db->escape($_POST['no_order']);
        $part_number = $db->escape($_POST['part_number']);
        $categorie_id = (int)$_POST['categorie_id'];
        $quantity_produced = (int)$_POST['quantity_produced'];
        $production_date = $db->escape($_POST['production_date']);
        $input_date = date('Y-m-d');

        $query = "INSERT INTO production_output (no_order, part_number, categorie_id, quantity_produced, production_date, input_date) ";
        $query .= "VALUES ('{$no_order}', '{$part_number}', '{$categorie_id}', '{$quantity_produced}', '{$production_date}', '{$input_date}')";

        if ($db->query($query)) {
            $session->msg('s', "Production output added successfully.");
            redirect('production_output.php', false);
        } else {
            $session->msg('d', "Failed to add production output.");
            redirect('production_output.php', false);
        }
    } else {
        $session->msg('d', $errors);
        redirect('production_output_add.php', false);
    }
}

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

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
    <div class="col-md-6">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-plus"></span>
                    <span>Add Production Output</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="production_output_add.php">
                    <div class="form-group">
                        <label for="no_order">No Order</label>
                        <input type="text" class="form-control" id="no_order" name="no_order" required>
                    </div>
                    <div class="form-group">
                        <label for="part_number">Part Number</label>
                        <input type="text" class="form-control" id="part_number" name="part_number" required 
                               onchange="getCategoryId(this.value)" onblur="getCategoryId(this.value)">
                        <input type="hidden" id="categorie_id" name="categorie_id">
                        <small id="category_info" class="form-text text-muted"></small>
                    </div>
                    <div class="form-group">
                        <label for="quantity_produced">Quantity Produced</label>
                        <input type="number" class="form-control" id="quantity_produced" name="quantity_produced" required>
                    </div>
                    <div class="form-group">
                        <label for="production_date">Production Date</label>
                        <input type="date" class="form-control" id="production_date" name="production_date" required>
                    </div>
                    <button type="submit" class="btn btn-primary">Submit</button>
                    <a href="production_output.php" class="btn btn-default">Cancel</a>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function getCategoryId(partNumber) {
    if(partNumber) {
        fetch(`get_category_id.php?part_number=${encodeURIComponent(partNumber)}`)
            .then(response => response.json())
            .then(data => {
                if(data.success) {
                    document.getElementById('categorie_id').value = data.categorie_id;
                    // Tampilkan info kategori
                    fetch(`get_category_name.php?id=${data.categorie_id}`)
                        .then(response => response.json())
                        .then(catData => {
                            if(catData.success) {
                                document.getElementById('category_info').textContent = `Category: ${catData.category_name}`;
                            } else {
                                document.getElementById('category_info').textContent = 'Category not found';
                            }
                        });
                } else {
                    document.getElementById('categorie_id').value = '';
                    document.getElementById('category_info').textContent = 'Part number not found!';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('category_info').textContent = 'Error fetching data';
            });
    }
}
</script>

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