<?php
$page_title = 'Import Volume Products';
require_once('includes/load.php');
page_require_level(5);

// Handle file upload and processing
if (isset($_POST['upload'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] == UPLOAD_ERR_OK) {
        $file = $_FILES['csv_file']['tmp_name'];
        $handle = fopen($file, 'r');

        if ($handle !== FALSE) {
            // Skip the first row if it contains headers
            fgetcsv($handle, 1000, ';');

            // Process each row of the CSV
            while (($data = fgetcsv($handle, 1000, ';')) !== FALSE) {
                $part_number = $db->escape($data[0]);
                $volume = $db->escape($data[1]);

                // Check if part_number exists
                $sql = "SELECT * FROM products WHERE part_number = '{$part_number}'";
                $result = $db->query($sql);

                if ($db->num_rows($result) > 0) {
                    // Update volume if part_number exists
                    $update_sql = "UPDATE products SET volume = '{$volume}' WHERE part_number = '{$part_number}'";
                    if ($db->query($update_sql)) {
                        $session->msg('s', "Volume updated for part number: $part_number");
                    } else {
                        $session->msg('d', "Error updating volume for part number: $part_number");
                    }
                } else {
                    $session->msg('d', "Part number not found: $part_number");
                }
            }
            fclose($handle);
        } else {
            $session->msg('d', "Failed to open CSV file.");
        }
    } else {
        $session->msg('d', "No file uploaded or upload error.");
    }
    redirect('import_volume_product.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-12">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Import Volume Products</h3>
            </div>
            <div class="panel-body">
                <form method="post" enctype="multipart/form-data" action="import_volume_product.php">
                    <div class="form-group">
                        <label for="csv_file">Upload CSV File:</label>
                        <input type="file" class="form-control" id="csv_file" name="csv_file" required>
                    </div>
                    <button type="submit" name="upload" class="btn btn-primary">Upload and Import</button>
                </form>
            </div>
        </div>
    </div>
</div>

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