<?php
$page_title = 'Add Incoming Production';
require_once('includes/sql.php');
page_require_level(3);

// Initialize error message
$error_msg = '';

// Function to find product_id by part_number
function find_product_id_by_part_number($partNumber) {
    global $db;
    $sql = "SELECT id FROM products WHERE part_number = '{$partNumber}' LIMIT 1";
    $result = $db->query($sql);
    return $db->fetch_assoc($result); // Mengembalikan baris hasil dengan 'id' sebagai product_id
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $transactionDate = $_POST['transactionDate'];

    // Loop through each incoming production data
    foreach ($_POST['data'] as $data) {
        // Escape and extract data
        $partNumber = $db->escape($data['partNumber']);
        $quantity = floatval($data['quantity']);
        $remark = $db->escape($data['remark']);
        $loc = $db->escape($data['loc']);

        // Find the product_id based on the part_number from products table
        $product = find_product_id_by_part_number($partNumber);

        if ($product) {
            // Extract product_id from the result
            $product_id = $product['id'];

            // Check if the part_number exists in prod_loc
            $prodLoc = find_prod_loc_by_part_number($partNumber);

            if ($prodLoc) {
                // Get the current quantity in prod_loc
                $existingQuantity = $prodLoc['quantity'];

                // Check if the existing quantity is enough to accommodate the incoming production
                if ($existingQuantity < $quantity) {
                    // If stock is insufficient, set the error message
                    $error_msg = "Insufficient stock for part number {$partNumber}. Available stock: {$existingQuantity}. Required: {$quantity}.";
                } else {
                    // Add the quantity to the existing quantity in products
                    $newQuantity = $existingQuantity + $quantity;

                    // Update product quantity in products table
                    $updateProductSql = "UPDATE products SET quantity = {$newQuantity} WHERE part_number = '{$partNumber}'";
                    if ($db->query($updateProductSql)) {
                        // Insert incoming production record
                        $sql = "INSERT INTO incoming_production (part_number, quantity, transaction_date, remark, loc) 
                                VALUES ('{$partNumber}', '{$quantity}', '{$transactionDate}', '{$remark}', '{$loc}')";

                        if ($db->query($sql)) {
                            // Insert into incoming_goods table after production record is added
                            $arrival_date = $transactionDate;
                            $categorie_id = $prodLoc['categorie_id'];  // Assuming categorie_id is available in prod_loc

                            $incomingGoodsSql = "INSERT INTO incoming_goods (product_id, part_number, quantity, arrival_date, categorie_id, remark, loc) 
                                                 VALUES ('{$product_id}', '{$partNumber}', '{$quantity}', '{$arrival_date}', '{$categorie_id}', '{$remark}', '{$loc}')";

                            if ($db->query($incomingGoodsSql)) {
                                $session->msg('s', 'Incoming production and goods data added successfully!');
                            } else {
                                $error_msg = 'Failed to insert into incoming_goods. ' . $db->error;  // Get the error from the database
                            }
                        } else {
                            $error_msg = 'Failed to add incoming production. ' . $db->error;
                        }
                    } else {
                        $error_msg = 'Failed to update product quantity. ' . $db->error;
                    }
                }
            } else {
                $error_msg = 'Part number not found in prod_loc.';
            }
        } else {
            $error_msg = 'Part number not found in products table.';
        }
    }

    // Redirect after processing if no errors
    if (empty($error_msg)) {
        redirect('add_incoming_production.php', false);
    }
}

// Display form
include_once('layouts/header.php');
echo display_msg($msg);

// Display error message if exists
if (!empty($error_msg)) {
    echo "<div class='alert alert-danger'>{$error_msg}</div>";
}
?>

<!-- Form for adding incoming production -->
<form method="post" action="add_incoming_production.php">
    <div class="form-group">
        <label for="transactionDate">Transaction Date:</label>
        <input type="date" name="transactionDate" id="transactionDate" class="form-control" required>
    </div>

    <div id="productionDataContainer">
        <div class="productionData">
            <div class="form-group">
                <label for="partNumber">Part Number:</label>
                <input type="text" name="data[0][partNumber]" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="quantity">Quantity:</label>
                <input type="number" name="data[0][quantity]" class="form-control" required>
            </div>
            <div class="form-group">
                <label for="remark">Remark:</label>
                <textarea name="data[0][remark]" class="form-control"></textarea>
            </div>
            <div class="form-group">
                <label for="loc">Location:</label>
                <input type="text" name="data[0][loc]" class="form-control" required>
            </div>
        </div>
    </div>

    <button type="button" id="addDataButton" class="btn btn-secondary">Add More Data</button>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

<script>
document.getElementById('addDataButton').addEventListener('click', function() {
    var container = document.getElementById('productionDataContainer');
    var newData = document.createElement('div');
    newData.classList.add('productionData');

    newData.innerHTML = `
        <div class="form-group">
            <label for="partNumber">Part Number:</label>
            <input type="text" name="data[${container.children.length}][partNumber]" class="form-control" required>
        </div>
        <div class="form-group">
            <label for="quantity">Quantity:</label>
            <input type="number" name="data[${container.children.length}][quantity]" class="form-control" required>
        </div>
        <div class="form-group">
            <label for="remark">Remark:</label>
            <textarea name="data[${container.children.length}][remark]" class="form-control"></textarea>
        </div>
        <div class="form-group">
            <label for="loc">Location:</label>
            <input type="text" name="data[${container.children.length}][loc]" class="form-control" required>
        </div>
    `;

    container.appendChild(newData);
});
</script>

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