<?php
$page_title = 'Import Buy Price';
require_once('includes/load.php');
page_require_level(3);

if (isset($_POST['import'])) {
    $file = $_FILES['csv_file']['tmp_name'];
    if (is_uploaded_file($file)) {
        $handle = fopen($file, "r");
        if ($handle !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { // Menggunakan titik koma sebagai pemisah
                $part_number = $data[0];
                // Replace comma with dot for buy_price
                $buy_price = str_replace(',', '.', $data[1]);

                // Update the buy price based on part number
                $sql = "UPDATE products SET buy_price = '{$buy_price}' WHERE part_number = '{$part_number}'";
                $result = $db->query($sql);
                if ($result) {
                    $msg[] = "Updated: {$part_number} with Buy Price: {$buy_price}";
                } else {
                    $errors[] = "Failed to update: {$part_number}";
                }
            }
            fclose($handle);
            $session->msg('s', "CSV file successfully imported.");
        } else {
            $session->msg('d', "Unable to open CSV file.");
        }
    } else {
        $session->msg('d', "No file uploaded or invalid file.");
    }
}
?>

<?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">
                <strong>
                    <span class="glyphicon glyphicon-upload"></span>
                    <span>Import Buy Price</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="import_buy_price.php" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="csv_file">CSV File:</label>
                        <input type="file" name="csv_file" class="form-control" required>
                    </div>
                    <button type="submit" name="import" class="btn btn-primary">Import</button>
                </form>
            </div>
        </div>
    </div>
</div>

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