<?php
$page_title = 'Process Adjustment';
require_once('includes/load.php');
page_require_level(3); // Memastikan level akses sesuai

$msg = '';

// Fungsi untuk memperbarui kuantitas produk online berdasarkan part_number
function update_adjustment_online_products_quantity($part_number, $new_quantity)
{
    global $db;

    // Menghindari SQL injection dengan escape parameter
    $part_number = $db->escape($part_number);
    $new_quantity = (int) $new_quantity;

    // Query untuk memperbarui kuantitas produk online
    $sql = "UPDATE online_products SET quantity = {$new_quantity} WHERE part_number = '{$part_number}'";
    $result = $db->query($sql);

    // Mengembalikan true jika query berhasil dieksekusi, false jika gagal
    return ($result && $db->affected_rows() === 1) ? true : false;
}

// Import CSV dan update kuantitas jika CSV diunggah
if (isset($_POST['import_csv'])) {
    if ($_FILES['csv_file']['error'] == UPLOAD_ERR_OK && is_uploaded_file($_FILES['csv_file']['tmp_name'])) {
        $csv_file = $_FILES['csv_file']['tmp_name'];

        // Proses file CSV untuk menyesuaikan kuantitas
        $handle = fopen($csv_file, "r");
        while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
            $part_number = trim($data[0]);
            $quantity = (int) trim($data[1]);

            // Update kuantitas berdasarkan part_number dari CSV
            update_adjustment_online_products_quantity($part_number, $quantity);
        }
        fclose($handle);

        $msg = "File CSV berhasil diimpor dan kuantitas disesuaikan.";
        $_SESSION['msg'] = $msg;
        redirect('process_adjustment.php');
    } else {
        $msg = "Error saat mengunggah file CSV.";
        $_SESSION['msg'] = $msg;
        redirect('process_adjustment.php');
    }
}

// Variabel untuk pencarian
$search_query = "";
$search_option = "";

// Meng-handle pengiriman form pencarian
if (isset($_POST['search'])) {
    $search_query = $_POST['search_query'];
    $search_option = $_POST['search_option'];

    // Mencari produk online berdasarkan kriteria
    $online_products = search_online_products($search_query, $search_option);
} else {
    // Pengaturan pagination
    $per_page = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 200;
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

    // Mengambil semua produk online tanpa pagination
    $online_products = get_all_online_products();
}

?>

<?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-12">
        <div class="panel panel-default">
            <div class="panel-heading clearfix">
                <div class="pull-left">
                    <h2>Process Adjustment</h2>
                </div>
                <div class="pull-right">
                    <!-- Form untuk import CSV -->
                    <form action="process_adjustment.php" method="post" enctype="multipart/form-data" class="form-inline">
                        <div class="form-group">
                            <label for="csv_file">Upload CSV</label>
                            <input type="file" name="csv_file" id="csv_file" class="form-control-file" accept=".csv" required>
                        </div>
                        <button type="submit" name="import_csv" class="btn btn-primary ml-2">Import CSV</button>
                    </form>

                    <!-- Form Pencarian -->
                    <form action="process_adjustment.php" method="post" class="form-inline">
                        <div class="form-group">
                            <input type="text" class="form-control" name="search_query" placeholder="Cari">
                        </div>
                        <div class="form-group">
                            <select class="form-control" name="search_option">
                                <option value="name" <?php if ($search_option == 'name') echo 'selected'; ?>>Nama Produk</option>
                                <option value="part_number" <?php if ($search_option == 'part_number') echo 'selected'; ?>>Nomor Bagian</option>
                            </select>
                        </div>
                        <button type="submit" name="search" class="btn btn-primary">Cari</button>
                    </form>
                </div>
            </div>
            <div class="panel-body">
                <!-- Tabel Produk Online -->
                <div class="table-responsive">
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th class="text-center">#</th>
                                <th>Nomor Bagian</th>
                                <th>Produk</th>
                                <th class="text-center">Stok Tersedia</th>
                                <th class="text-center">UoM</th>
                                <th class="text-center">Harga Beli</th>
                                <th class="text-center">ID Lokasi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($online_products as $online_product) : ?>
                                <tr>
                                    <!-- Data Produk -->
                                    <td class="text-center"><?php echo count_id(); ?></td>
                                    <td><?php echo isset($online_product['part_number']) ? htmlspecialchars($online_product['part_number']) : 'N/A'; ?></td>
                                    <td><?php echo remove_junk($online_product['name']); ?></td>
                                    <td class="text-center"><?php echo $online_product['quantity']; ?></td>
                                    <td class="text-center"><?php echo remove_junk($online_product['UoM']); ?></td>
                                    <td class="text-center"><?php echo remove_junk($online_product['buy_price']); ?></td>
                                    <td class="text-center"><?php echo remove_junk($online_product['loc_id']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <!-- Akhir Tabel Produk Online -->
            </div>
        </div>
    </div>
</div>

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