<?php
// Include library PHP Barcode Generator
require 'includes/load.php';

// Database connection
$host = 'localhost';
$username = 'robz3369_Rnanda';
$password = 'Clemira123';
$database = 'robz3369_inventory_system';

$conn = new mysqli($host, $username, $password, $database);

// Check koneksi
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Fungsi untuk mencetak barcode
function printBarcode($part_number, $product_name, $quantity, $printer_name) {
    $file_name = 'barcode_' . time() . '.png'; // Nama file barcode yang unik
    $barcode_value = $part_number; // Menggunakan part_number sebagai nilai barcode

    // Membuat objek barcode dengan PHP Barcode Generator
    $barcode = new \BarcodeBakery\Barcode\BCGcode128();
    $barcode->setScale(2);
    $barcode->setThickness(30);
    $barcode->setForegroundColor(new \BarcodeBakery\Common\BCGColor(0, 0, 0));
    $barcode->setBackgroundColor(new \BarcodeBakery\Common\BCGColor(255, 255, 255));
    $barcode->setFont(new \BarcodeBakery\Common\BCGFontFile(__DIR__ . '/barcode/font/Arial.ttf', 18));
    $barcode->parse($barcode_value);

    // Menghasilkan gambar barcode
    ob_start();
    $barcode->draw();
    $barcode_image = ob_get_clean();

    // Menyimpan gambar barcode sebagai file PNG
    file_put_contents($file_name, $barcode_image);

    // Menyimpan informasi cetakan ke database
    $print_date = date('Y-m-d');
    $sql = "INSERT INTO print_barcode (part_number, product_name, quantity, print_date, printer_name, barcode_image) VALUES ('$part_number', '$product_name', $quantity, '$print_date', '$printer_name', '$file_name')";
    global $conn;
    if ($conn->query($sql) === TRUE) {
        echo "Barcode berhasil dicetak dan disimpan dalam database.";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// Contoh penggunaan
$part_number = '123456';
$product_name = 'Produk A';
$quantity = 100;
$printer_name = 'Printer 1';

printBarcode($part_number, $product_name, $quantity, $printer_name);

// Tutup koneksi database
$conn->close();
?>
