<?php
// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Database connection constants
define('DB_HOST', 'localhost');
define('DB_USER', 'wiselie_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'wiselie_inventory');

// Establish database connection
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// Check connection
if ($db->connect_error) {
    die("Connection failed: " . $db->connect_error);
}

// Include Picqer Barcode library
require 'vendor/autoload.php';
use Picqer\Barcode\BarcodeGeneratorPNG;

// Initialize search variables
$searchPartNumber = '';
$searchName = '';

// Check if search form is submitted
if (isset($_GET['search'])) {
    $searchPartNumber = trim($_GET['part_number']);
    $searchName = trim($_GET['name']);
}

// Handle quantity update
if (isset($_POST['update_quantity'])) {
    $id = $_POST['id'];
    $newQuantity = $_POST['quantity'];
    
    // Validate quantity
    if (!is_numeric($newQuantity) || $newQuantity <= 0) {
        $updateError = "Quantity must be a positive number";
    } else {
        $updateStmt = $db->prepare("UPDATE generate_barcode SET quantity = ? WHERE id = ?");
        $updateStmt->bind_param("di", $newQuantity, $id);
        if ($updateStmt->execute()) {
            $updateSuccess = "Quantity updated successfully!";
        } else {
            $updateError = "Error updating quantity: " . $updateStmt->error;
        }
        $updateStmt->close();
    }
}

// Fetch all data from the generate_barcode table with search functionality
$query = "SELECT * FROM generate_barcode WHERE 1=1";
$params = [];
$types = '';

// Add search conditions
if (!empty($searchPartNumber)) {
    $query .= " AND part_number LIKE ?";
    $params[] = '%' . $searchPartNumber . '%';
    $types .= 's';
}
if (!empty($searchName)) {
    $query .= " AND name LIKE ?";
    $params[] = '%' . $searchName . '%';
    $types .= 's';
}

// Prepare and execute the query
$stmt = $db->prepare($query);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

$allData = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $allData[] = $row;
    }
}

// Function to generate ITF-14 barcode from part number
function generateITF14($partNumber) {
    $baseNumber = str_pad($partNumber, 13, '0', STR_PAD_LEFT); // Pad to 13 digits
    $checksum = calculateITF14Checksum($baseNumber);
    return $baseNumber . $checksum; // Return full ITF-14 barcode
}

// Function to calculate ITF-14 checksum
function calculateITF14Checksum($digits) {
    $oddSum = 0;
    $evenSum = 0;
    for ($i = 0; $i < strlen($digits); $i++) {
        $digit = (int) $digits[$i];
        if (($i + 1) % 2 === 0) {
            $evenSum += $digit;
        } else {
            $oddSum += $digit;
        }
    }
    $totalSum = $oddSum * 3 + $evenSum;
    $checksum = (10 - ($totalSum % 10)) % 10; // Return checksum
    return $checksum;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage ITF-14 Carton</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .uom-select {
            max-width: 120px;
        }
        .reminder-box {
            background-color: #fff3cd;
            border-left: 5px solid #ffc107;
            padding: 15px;
            margin-bottom: 20px;
            font-weight: bold;
            font-size: 1.1em;
        }
        .edit-quantity-form {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .edit-quantity-form input {
            max-width: 80px;
        }
    </style>
</head>
<body>
<div class="container">
    <h2 class="mt-4">Manage ITF-14 Carton</h2>
    
    <?php if (isset($updateSuccess)): ?>
        <div class="alert alert-success"><?php echo $updateSuccess; ?></div>
    <?php endif; ?>
    <?php if (isset($updateError)): ?>
        <div class="alert alert-danger"><?php echo $updateError; ?></div>
    <?php endif; ?>
    
    <div class="reminder-box">
        ⚠️ PASTIKAN QUANTITY LABEL DAN ACTUAL DI KARDUS SUDAH SESUAI
    </div>

    <h3>Search Barcodes</h3>
    <form method="GET" class="mb-4">
        <div class="form-row">
            <div class="form-group col-md-5">
                <label for="search_part_number">Part Number</label>
                <input type="text" name="part_number" id="search_part_number" class="form-control" value="<?php echo htmlspecialchars($searchPartNumber); ?>">
            </div>
            <div class="form-group col-md-5">
                <label for="search_name">Product Name</label>
                <input type="text" name="name" id="search_name" class="form-control" value="<?php echo htmlspecialchars($searchName); ?>">
            </div>
            <div class="form-group col-md-2">
                <label>&nbsp;</label>
                <button type="submit" name="search" class="btn btn-primary btn-block">Search</button>
            </div>
        </div>
    </form>

    <h3>All Generated ITF-14 Barcodes</h3>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th>ID</th>
                <th>Part Number</th>
                <th>ITF-14 Barcode</th>
                <th>Name</th>
                <th>Quantity</th>
                <th>UOM</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php if (!empty($allData)): ?>
                <?php foreach ($allData as $data): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($data['id']); ?></td>
                        <td><?php echo htmlspecialchars($data['part_number']); ?></td>
                        <td><?php echo htmlspecialchars($data['barcode']); ?></td>
                        <td><?php echo htmlspecialchars($data['name']); ?></td>
                        <td>
                            <form method="POST" class="edit-quantity-form">
                                <input type="hidden" name="id" value="<?php echo htmlspecialchars($data['id']); ?>">
                                <input type="number" name="quantity" class="form-control form-control-sm" 
                                       value="<?php echo htmlspecialchars($data['quantity']); ?>" min="1" step="1" required>
                                <button type="submit" name="update_quantity" class="btn btn-sm btn-success">Update</button>
                            </form>
                        </td>
                        <td><?php echo htmlspecialchars($data['uom']); ?></td>
                        <td>
                            <a href="print_itf14.php?id=<?php echo htmlspecialchars($data['id']); ?>" class="btn btn-sm btn-secondary" target="_blank">Print</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7" class="text-center">No data available</td>
                </tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>