<?php
// Tampilkan semua error untuk debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$page_title = 'Transfer Stok Internal';
require_once('includes/load.php');
page_require_level(5);

// ====================================================================================
// Bagian 1: Logika untuk Fitur Autosuggestion Produk (permintaan Ajax GET)
// ====================================================================================
if (isset($_GET['term'])) {
    $search_term = $db->escape($_GET['term']);
    
    // Query untuk mencari produk berdasarkan part number atau nama
    $sql = "SELECT part_number, name, quantity FROM products WHERE part_number LIKE '%{$search_term}%' OR name LIKE '%{$search_term}%' LIMIT 10";
    $result = find_by_sql($sql);
    
    $products = [];
    foreach ($result as $row) {
        $products[] = [
            'label' => htmlspecialchars($row['part_number']) . ' - ' . remove_junk($row['name']) . ' (Stok Gudang: ' . number_format($row['quantity'], 2) . ')',
            'value' => htmlspecialchars($row['part_number'])
        ];
    }
    
    header('Content-Type: application/json');
    echo json_encode($products);
    exit;
}

// ====================================================================================
// Bagian 2: Logika Pemrosesan Formulir (permintaan POST)
// ====================================================================================
if (isset($_POST['submit_transfer'])) {
    $part_numbers   = $_POST['part_number'];
    $movement_types = $_POST['movement_type'];
    $quantities     = $_POST['quantity'];
    $notes          = $_POST['notes'];
    
    $errors = [];
    
    try {
        $db->begin_transaction();

        // Mapping yang aman untuk nama tabel tujuan
        $location_mappings = [
            'transfer' => 'inventory', 
            'reject'   => 'reject_area'
        ];

        // Ambil semua konfigurasi COA untuk menghindari query berulang di dalam loop
        $coa_configs = find_all('coa_settings');
        $coa_map = [];
        foreach ($coa_configs as $config) {
            $coa_map[$config['movement_type']] = [
                'debit'  => $config['debit_coa_code'],
                'kredit' => $config['kredit_coa_code']
            ];
        }

        for ($i = 0; $i < count($part_numbers); $i++) {
            $part_number   = trim($part_numbers[$i]);
            $movement_type = $movement_types[$i];
            $quantity      = (float)$quantities[$i];
            $note          = trim($notes[$i]);

            // Validasi input dasar
            if (empty($part_number) || !is_numeric($quantity) || $quantity == 0) {
                $errors[] = "Baris ke-" . ($i + 1) . ": Semua kolom harus diisi dengan benar dan jumlah tidak boleh 0.";
                continue;
            }

            // Validasi jenis pergerakan
            if (!isset($location_mappings[$movement_type])) {
                 $errors[] = "Baris ke-" . ($i + 1) . ": Jenis transaksi tidak valid.";
                continue;
            }

            // Dapatkan info produk
            $product_info = find_by_sql("SELECT name, quantity, buy_price FROM products WHERE part_number = '{$db->escape($part_number)}' LIMIT 1");
            if (!$product_info) {
                $errors[] = "Baris ke-" . ($i + 1) . ": Part number '{$part_number}' tidak ditemukan.";
                continue;
            }
            $current_warehouse_quantity = $product_info[0]['quantity'];
            $unit_cost = $product_info[0]['buy_price'];

            // Validasi stok jika kuantitas positif (pengurangan stok gudang)
            if ($quantity > 0 && $current_warehouse_quantity < $quantity) {
                $errors[] = "Baris ke-" . ($i + 1) . ": Stok di gudang tidak mencukupi untuk '{$part_number}'. Stok saat ini: " . $current_warehouse_quantity;
                continue;
            }

            // Validasi harga beli produk
            if (!is_numeric($unit_cost) || $unit_cost <= 0) {
                $errors[] = "Baris ke-" . ($i + 1) . ": Harga beli ('buy_price') untuk produk '{$part_number}' tidak valid. Jurnal tidak bisa dibuat.";
                continue;
            }

            // Cek konfigurasi COA
            if (!isset($coa_map[$movement_type])) {
                $errors[] = "Baris ke-" . ($i + 1) . ": Konfigurasi akun (COA) untuk jenis pergerakan '{$movement_type}' belum diset di halaman pengaturan.";
                continue;
            }
            
            $debit_coa  = $coa_map[$movement_type]['debit'];
            $kredit_coa = $coa_map[$movement_type]['kredit'];
            $transaction_value = abs($quantity * $unit_cost);

            // Tentukan deskripsi jurnal
            $deskripsi_jurnal = ($quantity > 0) ? 
                                "Transfer ke " . $movement_type . ": {$product_info[0]['name']}" : 
                                "Pengembalian dari " . $movement_type . ": {$product_info[0]['name']}";

            // === Pencatatan Jurnal ===
            if ($quantity > 0) {
                // Jurnal normal (stok keluar gudang)
                $sql_jurnal_debit = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (NOW(), '{$db->escape($deskripsi_jurnal)}', '{$debit_coa}', '{$transaction_value}', 0)";
                $db->query($sql_jurnal_debit);
                $sql_jurnal_kredit = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (NOW(), '{$db->escape($deskripsi_jurnal)}', '{$kredit_coa}', 0, '{$transaction_value}')";
                $db->query($sql_jurnal_kredit);
            } else {
                // Jurnal pembalikan (stok kembali ke gudang)
                $sql_jurnal_debit = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (NOW(), '{$db->escape($deskripsi_jurnal)}', '{$kredit_coa}', '{$transaction_value}', 0)";
                $db->query($sql_jurnal_debit);
                $sql_jurnal_kredit = "INSERT INTO jurnal (tanggal, deskripsi, coa_kode, debit, kredit) VALUES (NOW(), '{$db->escape($deskripsi_jurnal)}', '{$debit_coa}', 0, '{$transaction_value}')";
                $db->query($sql_jurnal_kredit);
            }
            
            // === Update stok di tabel products ===
            $new_warehouse_quantity = $current_warehouse_quantity - $quantity;
            $sql_update_products = "UPDATE products SET quantity = '{$new_warehouse_quantity}' WHERE part_number = '{$db->escape($part_number)}'";
            $db->query($sql_update_products);
            
            // === Tambahkan/update stok di tabel tujuan ===
            $location_to_update = $location_mappings[$movement_type];
            $check_item = find_by_sql("SELECT quantity FROM {$db->escape($location_to_update)} WHERE part_number = '{$db->escape($part_number)}' LIMIT 1");
            $current_location_quantity = $check_item ? $check_item[0]['quantity'] : 0;
            $new_location_quantity = $current_location_quantity + $quantity;

            if ($check_item) {
                $sql_update_location = "UPDATE {$db->escape($location_to_update)} SET quantity = '{$new_location_quantity}', last_updated = NOW() WHERE part_number = '{$db->escape($part_number)}'";
                $db->query($sql_update_location);
            } else {
                $sql_insert_location = "INSERT INTO {$db->escape($location_to_update)} (part_number, quantity, last_updated) VALUES ('{$db->escape($part_number)}', '{$new_location_quantity}', NOW())";
                $db->query($sql_insert_location);
            }

            // === Catat pergerakan stok di tabel stock_movement ===
            $sql_insert_movement = "INSERT INTO stock_movement (part_number, movement_type, quantity_changed, movement_date, notes)
                                    VALUES (
                                        '{$db->escape($part_number)}',
                                        '{$db->escape($movement_type)}',
                                        '{$quantity}',
                                        NOW(),
                                        '{$db->escape($note)}'
                                    )";
            $db->query($sql_insert_movement);
        }

        if (empty($errors)) {
            $db->commit();
            $session->msg('s', 'Semua transaksi stok berhasil dicatat.');
            redirect('transfer_posting.php', false);
        } else {
            $db->rollback();
            $session->msg('d', 'Gagal memproses beberapa transaksi:<br>' . implode('<br>', $errors));
            redirect('transfer_posting.php', false);
        }

    } catch (Exception $e) {
        $db->rollback();
        $session->msg('d', 'Gagal memproses transaksi: ' . $e->getMessage());
        redirect('transfer_posting.php', false);
    }
}
?>

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

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <strong>
                    <span class="glyphicon glyphicon-transfer"></span>
                    <span>Multi-Transfer Stok Internal</span>
                </strong>
            </div>
            <div class="panel-body">
                <div class="alert alert-info">
                    <p><strong>Legenda Jenis Transaksi:</strong></p>
                    <ul>
                        <li><span class="label label-success">Transfer ke Produksi:</span> Mengurangi stok gudang dan menambah stok di area **produksi**.</li>
                        <li><span class="label label-danger">Transfer ke Reject Area:</span> Mengurangi stok gudang dan memindahkannya ke area barang **rusak**.</li>
                    </ul>
                    <p class="text-danger"><strong>Peringatan:</strong> Masukkan kuantitas positif untuk transfer keluar gudang. Masukkan kuantitas **negatif** (misalnya, `-10`) untuk mengembalikan stok dari area tujuan kembali ke gudang.</p>
                </div>
                
                <form action="transfer_posting.php" method="POST">
                    <div class="row header-row" style="font-weight: bold; margin-bottom: 10px;">
                        <div class="col-md-4">Part Number / Nama Produk</div>
                        <div class="col-md-2">Jenis Transaksi</div>
                        <div class="col-md-2">Jumlah</div>
                        <div class="col-md-3">Catatan</div>
                        <div class="col-md-1">Aksi</div>
                    </div>
                    
                    <div id="form-container">
                        <div class="form-row row">
                            <div class="col-md-4">
                                <input type="text" class="form-control part-number-input" name="part_number[]" placeholder="Ketik part number atau nama produk..." required>
                            </div>
                            <div class="col-md-2">
                                <select class="form-control" name="movement_type[]">
                                    <option value="transfer">Transfer ke Produksi</option>
                                    <option value="reject">Transfer ke Reject Area</option>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <input type="number" step="0.01" class="form-control" name="quantity[]" required>
                            </div>
                            <div class="col-md-3">
                                <textarea class="form-control" name="notes[]" rows="1"></textarea>
                            </div>
                            <div class="col-md-1">
                                <button type="button" class="btn btn-danger btn-remove-row" style="display:none;">Hapus</button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="clearfix">
                        <button type="button" id="add-row-btn" class="btn btn-success" style="margin-top: 15px;">Tambah Baris</button>
                        <button type="submit" name="submit_transfer" class="btn btn-primary pull-right" style="margin-top: 15px;">Submit Semua Transaksi</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function() {
    function initAutocomplete(element) {
        $(element).autocomplete({
            source: "transfer_posting.php",
            minLength: 2
        });
    }

    initAutocomplete($(".part-number-input"));

    $("#add-row-btn").click(function() {
        var newRow = $(".form-row:first").clone();
        
        newRow.find("input").val("");
        newRow.find("textarea").val("");
        
        newRow.find(".btn-remove-row").show();

        $("#form-container").append(newRow);

        initAutocomplete(newRow.find(".part-number-input"));
    });

    $(document).on("click", ".btn-remove-row", function() {
        if ($(".form-row").length > 1) {
            $(this).closest(".form-row").remove();
        } else {
            alert("Tidak bisa menghapus baris terakhir!");
        }
    });
});
</script>

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