<?php

$page_title = 'Transfer Etalase Bali';
require_once('includes/load.php');
page_require_level(8); // Atur level akses sesuai kebutuhan

$msg = ''; // Inisialisasi pesan kosong

function transfer_to_online_products_bali($part_number, $quantity)
{
    global $db;

    // Cek apakah ada cukup quantity di wh_bali
    $sql_check = "SELECT quantity FROM wh_bali WHERE part_number = '{$part_number}'";
    $result_check = $db->query($sql_check);

    if ($result_check && $row_check = $result_check->fetch_assoc()) {
        // Jika quantity negatif, kita tidak perlu memeriksa jumlah yang ada
        if ($row_check['quantity'] < abs($quantity)) {
            return false; // Tidak cukup quantity jika quantity positif
        }
    } else {
        return false; // part_number tidak ditemukan di wh_bali
    }

    // Update quantity di wh_bali (mengurangi)
    insertStockHistory($part_number, 'Bali',  'OUT', $quantity, "Transfer WH To Etalase", 4, 'wh_bali', 'MOVE');
    $sql_update_wh = "UPDATE wh_bali SET quantity = quantity - {$quantity} WHERE part_number = '{$part_number}'";

    // Cek apakah part_number sudah ada di online_products_bali
    $sql_check_online = "SELECT quantity FROM online_products_bali WHERE part_number = '{$part_number}'";
    $result_check_online = $db->query($sql_check_online);

    if ($result_check_online && $row_check_online = $result_check_online->fetch_assoc()) {
        // Jika sudah ada, cukup update quantity

        insertStockHistory($part_number, 'Bali',  'IN', $quantity, "Transfer WH To Etalase", 4, 'online_products_bali', 'MOVE');
        $sql_update_online = "UPDATE online_products_bali SET quantity = quantity + {$quantity} WHERE part_number = '{$part_number}'";
        $db->query($sql_update_online);
    } else {
        return false; // part_number tidak ditemukan di online_products_bali
    }

    // Eksekusi query untuk mengurangi quantity di wh_bali
    if ($db->query($sql_update_wh)) {
        // Simpan record transfer ke tabel transfer_bali_record
        $sql_insert_record = "INSERT INTO transfer_bali_record (part_number, quantity) VALUES ('{$part_number}', {$quantity})";
        $db->query($sql_insert_record);

        return true; // Transfer berhasil
    } else {
        return false; // Transfer gagal
    }
}

if (isset($_POST['transfer'])) {
    $part_numbers = $_POST['part_number'];
    $quantities = $_POST['quantity'];
    $success = true;

    foreach ($part_numbers as $index => $part_number) {
        $quantity = (int)$quantities[$index];
        if (!transfer_to_online_products_bali($part_number, $quantity)) {
            $success = false; // Jika salah satu transfer gagal
        }
    }

    if ($success) {
        $session->msg('s', "Transfer berhasil dari wh_bali ke online_products_bali!");
    } else {
        $session->msg('d', "Transfer gagal. Pastikan quantity cukup di wh_bali dan part_number ditemukan.");
    }
    redirect('transfer_etalase_bali.php', false);
}

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

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Transfer Barang dari WH Bali ke Online Products Bali</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="transfer_etalase_bali.php" class="form" id="transferForm">
                    <div id="formInputs" class="mb-3">
                        <div class="input-group mb-2" style="width: 100%;">
                            <input type="text" class="form-control" name="part_number[]" placeholder="Part Number" required
                                style="flex: 2;">
                            <input type="number" class="form-control" name="quantity[]" placeholder="Quantity" required
                                style="flex: 1;">
                            <button type="button" class="btn btn-danger remove" style="margin-left: 10px;">Hapus</button>
                        </div>
                    </div>
                    <button type="button" class="btn btn-success mb-2" id="addMore">Tambah Form</button>
                    <button type="submit" name="transfer" class="btn btn-primary">Transfer</button>
                </form>
                <br>
                <div class="large-message">
                    <?php echo display_msg($msg); ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    document.getElementById('addMore').addEventListener('click', function() {
        var newFormGroup = document.createElement('div');
        newFormGroup.className = 'input-group mb-2';
        newFormGroup.style.width = '100%';
        newFormGroup.innerHTML = `
            <input type="text" class="form-control" name="part_number[]" placeholder="Part Number" required style="flex: 2;">
            <input type="number" class="form-control" name="quantity[]" placeholder="Quantity" required style="flex: 1;">
            <button type="button" class="btn btn-danger remove" style="margin-left: 10px;">Hapus</button>
        `;
        document.getElementById('formInputs').appendChild(newFormGroup);
    });

    document.getElementById('formInputs').addEventListener('click', function(e) {
        if (e.target.classList.contains('remove')) {
            e.target.parentElement.remove();
        }
    });
</script>

<style>
    .input-group {
        display: flex;
        width: 100%;
    }
</style>

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