<?php
require_once('includes/load.php');
page_require_level(3);

if(isset($_POST['import_csv'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['csv_file']['tmp_name'];

        // Validasi ekstensi file
        $file_ext = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));
        if ($file_ext !== 'csv') {
            $session->msg('d', 'Please upload a valid CSV file.');
            redirect('import_csv_wh.php', false);
        }

        if (($handle = fopen($file, "r")) !== FALSE) {
            fgetcsv($handle, 1000, ";"); // Membaca header CSV

            while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
                $part_number = remove_junk($data[0]);
                $quantity = (int)$data[1];
                $location = remove_junk($data[2]);
                $remark = remove_junk($data[3]);

                // Cari produk berdasarkan part_number
                $product = find_by_field('products', 'part_number', $part_number);

                if($product) {
                    // Memastikan jumlah transfer tidak melebihi stok yang tersedia
                    if($quantity > $product['quantity']) {
                        $session->msg('d', "Jumlah transfer untuk part number {$part_number} melebihi stok yang tersedia.");
                        redirect('import_csv_wh.php', false);
                    } else {
                        // Mengurangi jumlah stok di tabel products
                        $new_quantity = $product['quantity'] - $quantity;
                        $query1 = "UPDATE products SET quantity = '{$new_quantity}' WHERE id = '{$product['id']}'";

                        // Menambahkan stok ke WH yang dipilih
                        $existing_product = find_by_field($location, 'part_number', $product['part_number']);
                        
                        if($existing_product) {
                            // Jika produk sudah ada di WH tujuan, update quantity
                            $new_wh_quantity = $existing_product['quantity'] + $quantity;
                            $query2 = "UPDATE {$location} SET quantity = '{$new_wh_quantity}' WHERE part_number = '{$product['part_number']}'";
                        } else {
                            // Jika produk belum ada, tambahkan data baru
                            $query2 = "INSERT INTO {$location} (product_id, part_number, quantity) 
                                       VALUES ('{$product['id']}', '{$product['part_number']}', '{$quantity}')";
                        }

                        // Menyimpan transfer ke tabel wh_transfer
                        $query3 = "INSERT INTO wh_transfer (product_id, part_number, quantity, location, remark, transfer_date) 
                                   VALUES ('{$product['id']}', '{$part_number}', '{$quantity}', '{$location}', '{$remark}', NOW())";

                        // Menjalankan query
                        if(!$db->query($query1) || !$db->query($query2) || !$db->query($query3)) {
                            $session->msg('d', "Transfer gagal untuk part number {$part_number}.");
                            redirect('import_csv_wh.php', false);
                        }
                    }
                } else {
                    $session->msg('d', "Produk dengan part number {$part_number} tidak ditemukan.");
                    redirect('import_csv_wh.php', false);
                }
            }
            fclose($handle);
        } else {
            $session->msg('d', 'Failed to open the file.');
            redirect('import_csv_wh.php', false);
        }

        $session->msg('s', "Transfer berhasil.");
        redirect('import_csv_wh.php', false);
    } else {
        $session->msg('d', 'Error uploading file.');
        redirect('import_csv_wh.php', false);
    }
}
?>

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

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

<div class="row">
    <div class="col-md-8">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Import CSV for Product Transfer</h3>
            </div>
            <div class="panel-body">
                <form method="post" action="import_csv_wh.php" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="csv_file">Upload CSV File</label>
                        <input type="file" class="form-control" name="csv_file" required>
                    </div>

                    <button type="submit" name="import_csv" class="btn btn-primary">Import CSV</button>
                </form>
            </div>
        </div>
    </div>
</div>

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