<?php
$page_title = 'Transfer to Etalase';
require_once('includes/load.php');
page_require_level(3);

if (isset($_POST['transfer'])) {
    // Loop through each product entry submitted
    foreach ($_POST['part_number'] as $index => $part_number) {
        $quantity = (int)$_POST['quantity'][$index];

        if ($quantity != 0) {
            $product = find_product_by_part_number($part_number);

            if ($product) {
                // If quantity is positive, reduce stock in products and add to online_products
                if ($quantity > 0) {
                    if ((int)$product['quantity'] >= $quantity) {
                        // Update quantity in products (reduce stock)
                        $new_quantity = (int)$product['quantity'] - $quantity;
                        insertStockHistory($part_number, 'Sidoarjo',  'OUT', $quantity, "Transfer WH To Etalase", 1, 'products', 'MOVE');
                        if (update_product_quantity($product['id'], $new_quantity)) {
                            // Check if product already exists in online_products
                            $online_product = find_online_product_by_part_number($part_number);
                            if ($online_product) {
                                // Increase quantity in online_products
                                $new_online_quantity = (int)$online_product['quantity'] + $quantity;
                                insertStockHistory($part_number, 'Sidoarjo Etalase',  'IN', $quantity, "Transfer WH To Etalase", 1, 'online_products', 'MOVE');
                                if (update_online_product_quantity($online_product['id'], $new_online_quantity)) {
                                    // Insert into transfer_online table
                                    $sql = "INSERT INTO transfer_online (part_number, quantity) VALUES (?, ?)";
                                    $stmt = $db->prepare($sql);
                                    $stmt->bind_param("si", $part_number, $quantity);
                                    $stmt->execute();

                                    $_SESSION['message'] = 'Product transferred successfully!';
                                    $_SESSION['message_type'] = 'success';
                                } else {
                                    $_SESSION['message'] = 'Failed to update online product quantity!';
                                    $_SESSION['message_type'] = 'danger';
                                }
                            } else {
                                // Insert new product into online_products
                                if (insert_online_product($product, $quantity)) {
                                    // Insert into transfer_online table
                                    $sql = "INSERT INTO transfer_online (part_number, quantity) VALUES (?, ?)";
                                    $stmt = $db->prepare($sql);
                                    $stmt->bind_param("si", $part_number, $quantity);
                                    $stmt->execute();

                                    $_SESSION['message'] = 'Product transferred successfully!';
                                    $_SESSION['message_type'] = 'success';
                                } else {
                                    $_SESSION['message'] = 'Failed to insert product into online etalase!';
                                    $_SESSION['message_type'] = 'danger';
                                }
                            }
                        } else {
                            $_SESSION['message'] = 'Failed to update product quantity!';
                            $_SESSION['message_type'] = 'danger';
                        }
                    } else {
                        $_SESSION['message'] = 'Insufficient quantity in stock!';
                        $_SESSION['message_type'] = 'danger';
                    }
                }
                // If quantity is negative, increase stock in products and reduce in online_products
                else {
                    $online_product = find_online_product_by_part_number($part_number);
                    if ($online_product && (int)$online_product['quantity'] >= abs($quantity)) {
                        // Increase stock in products
                        $new_quantity = (int)$product['quantity'] + abs($quantity);
                        if (update_product_quantity($product['id'], $new_quantity)) {
                            // Reduce quantity in online_products
                            $new_online_quantity = (int)$online_product['quantity'] - abs($quantity);
                            if (update_online_product_quantity($online_product['id'], $new_online_quantity)) {
                                // Insert into transfer_online table
                                $sql = "INSERT INTO transfer_online (part_number, quantity) VALUES (?, ?)";
                                $stmt = $db->prepare($sql);
                                $stmt->bind_param("si", $part_number, $quantity);
                                $stmt->execute();

                                $_SESSION['message'] = 'Product transferred successfully!';
                                $_SESSION['message_type'] = 'success';
                            } else {
                                $_SESSION['message'] = 'Failed to update online product quantity!';
                                $_SESSION['message_type'] = 'danger';
                            }
                        } else {
                            $_SESSION['message'] = 'Failed to update product quantity!';
                            $_SESSION['message_type'] = 'danger';
                        }
                    } else {
                        $_SESSION['message'] = 'Insufficient quantity in online etalase!';
                        $_SESSION['message_type'] = 'danger';
                    }
                }
            } else {
                $_SESSION['message'] = 'Product not found!';
                $_SESSION['message_type'] = 'danger';
            }
        } else {
            $_SESSION['message'] = 'Invalid quantity!';
            $_SESSION['message_type'] = 'danger';
        }
    }
    header('Location: transfer_etalase.php'); // Refresh the page to display the message
    exit();
}
?>

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

<div class="row">
    <div class="col-md-12">
        <?php if (isset($_SESSION['message'])): ?>
            <div class="alert alert-<?php echo $_SESSION['message_type']; ?>">
                <?php echo $_SESSION['message']; ?>
                <?php unset($_SESSION['message']);
                unset($_SESSION['message_type']); ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <h2>Transfer Product to Online Etalase</h2>
        <form method="post" action="transfer_etalase.php" id="transferForm">
            <div id="inputFields">
                <div class="form-group row mb-3">
                    <div class="col-md-6">
                        <label for="part_number[]">Part Number:</label>
                        <input type="text" class="form-control" name="part_number[]" required>
                    </div>
                    <div class="col-md-6">
                        <label for="quantity[]">Quantity:</label>
                        <input type="number" class="form-control" name="quantity[]" required>
                    </div>
                </div>
            </div>
            <button type="button" class="btn btn-secondary" id="addMore">Add More</button>
            <button type="submit" name="transfer" class="btn btn-primary">Transfer</button>
        </form>
    </div>
</div>

<script>
    document.getElementById('addMore').addEventListener('click', function() {
        const inputFields = document.getElementById('inputFields');
        const newFields = document.createElement('div');
        newFields.classList.add('form-group', 'row', 'mb-3');
        newFields.innerHTML = `
            <div class="col-md-6">
                <label for="part_number[]">Part Number:</label>
                <input type="text" class="form-control" name="part_number[]" required>
            </div>
            <div class="col-md-6">
                <label for="quantity[]">Quantity:</label>
                <input type="number" class="form-control" name="quantity[]" required>
            </div>
        `;
        inputFields.appendChild(newFields);
    });
</script>

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