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

$msg = ""; // Initialize message variable

if (isset($_POST['upload'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['csv_file']['tmp_name'];
        $fileName = $_FILES['csv_file']['name'];
        $fileSize = $_FILES['csv_file']['size'];
        $fileType = $_FILES['csv_file']['type'];

        // Validate file type (CSV only)
        $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);
        if ($fileExtension !== 'csv') {
            $msg = "Please upload a valid CSV file.";
        } else {
            // Open the file for reading
            if (($handle = fopen($fileTmpPath, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
                    // Read part_number and new_code
                    $part_number = trim($data[0]);
                    $new_code = trim($data[1]);

                    // Prepare and execute the update query
                    $query = "UPDATE products SET new_code = ? WHERE part_number = ?";
                    $stmt = $db->prepare($query);

                    if ($stmt === false) {
                        $msg = "Database prepare failed: " . $db->error;
                        break;
                    }

                    $stmt->bind_param("ss", $new_code, $part_number);

                    if (!$stmt->execute()) {
                        $msg = "Error updating record for part_number: {$part_number} - " . $stmt->error;
                        break;
                    }
                }
                fclose($handle);
                if (empty($msg)) {
                    $msg = "File imported successfully!";
                }
            } else {
                $msg = "Error opening the file.";
            }
        }
    } else {
        $msg = "Error uploading file.";
    }
}

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

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

    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading clearfix">
                    <h3 class="panel-title">Import New Codes from CSV</h3>
                </div>
                <div class="panel-body">
                    <form method="post" 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" id="csv_file" accept=".csv">
                        </div>
                        <button type="submit" name="upload" class="btn btn-primary">Upload</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

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