<?php
$page_title = 'Upload Volume for Products';
require_once('includes/load.php');
page_require_level(2);

include_once('layouts/header.php');

// Handle CSV file upload and process the data
if (isset($_POST['upload'])) {
    // Get the uploaded file
    $file = $_FILES['file']['tmp_name'];

    // Check if a file is uploaded
    if (!is_file($file)) {
        $session->msg('d', "Please upload a valid CSV file.");
    } else {
        // Open the CSV file
        $handle = fopen($file, "r");

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

            // Initialize a counter for successful updates
            $updated_count = 0;

            // Loop through each row of the CSV file
            while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
                // Extract part_number and volume from CSV
                $part_number = $db->escape($data[0]);
                $volume = (float)$data[1];

                // Update volume in products table based on part_number
                $sql = "UPDATE products SET volume = '{$volume}' WHERE part_number = '{$part_number}'";
                $result = $db->query($sql);

                // Check if the update was successful
                if ($db->affected_rows() > 0) {
                    $updated_count++;
                }
            }

            // Close the CSV file after processing
            fclose($handle);

            // Display success message with count of updated records
            if ($updated_count > 0) {
                $session->msg('s', "{$updated_count} product(s) updated successfully.");
            } else {
                $session->msg('w', "No products were updated. Please check if the part numbers exist.");
            }
        } else {
            $session->msg('d', "Unable to open the file. Please try again.");
        }
    }
}
?>

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

<div class="row">
    <div class="col-md-6">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-upload"></span>
                    <span>Upload CSV for Volume</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="POST" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="file">Choose CSV File (with part_number and volume):</label>
                        <input type="file" name="file" class="form-control" required />
                    </div>
                    <button type="submit" name="upload" class="btn btn-primary">Upload CSV</button>
                </form>
            </div>
        </div>
    </div>
</div>

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