<?php
include 'config.php';
checkLogin();

function generateUniqueSerial($model_id, $conn, &$new_id)
{
    $conn->query("LOCK TABLES laptop_models WRITE, laptop_serials WRITE");

    $stmt = $conn->prepare(
        "SELECT prefix, last_serial FROM laptop_models WHERE id=? FOR UPDATE"
    );
    $stmt->bind_param("i", $model_id);
    $stmt->execute();
    $stmt->bind_result($prefix, $last_serial);
    $stmt->fetch();
    $stmt->close();

    do {
        $next = $last_serial + 1;
        $serial = $prefix . '-' . str_pad($next, 6, '0', STR_PAD_LEFT);

        $check = $conn->prepare(
            "SELECT id FROM laptop_serials WHERE serial_number=?"
        );
        $check->bind_param("s", $serial);
        $check->execute();
        $check->store_result();

        $last_serial = $next;
    } while ($check->num_rows > 0);

    $insert = $conn->prepare(
        "INSERT INTO laptop_serials (model_id, serial_number)
         VALUES (?, ?)"
    );
    $insert->bind_param("is", $model_id, $serial);
    $insert->execute();
    $new_id = $insert->insert_id;
    $insert->close();

    $update = $conn->prepare(
        "UPDATE laptop_models SET last_serial=? WHERE id=?"
    );
    $update->bind_param("ii", $next, $model_id);
    $update->execute();
    $update->close();

    $conn->query("UNLOCK TABLES");

    return $serial;
}

$generated = [];
$generated_ids = [];

if (isset($_POST['bulk_generate'])) {
    $qty = (int)$_POST['qty'];
    $model_id = (int)$_POST['model_id'];

    for ($i = 0; $i < $qty; $i++) {
        $new_id = 0;
        $serial = generateUniqueSerial($model_id, $conn, $new_id);
        $generated[] = $serial;
        $generated_ids[] = $new_id;
    }
}

$models = $conn->query("SELECT * FROM laptop_models");

include 'layout/header.php';
include 'layout/sidebar.php';
?>

<h3 class="mb-4">Bulk Generate Serials</h3>

<div class="card p-4 mb-4">
<form method="post">
    <select name="model_id" class="form-select mb-3" required>
        <?php while ($m = $models->fetch_assoc()) { ?>
            <option value="<?= $m['id'] ?>">
                <?= $m['brand'] ?> - <?= $m['model'] ?>
            </option>
        <?php } ?>
    </select>

    <input type="number" name="qty" class="form-control mb-3"
           placeholder="Quantity (max 1000)" max="1000" required>

    <button class="btn btn-primary" name="bulk_generate">
        Bulk Generate
    </button>
</form>
</div>

<?php if (!empty($generated)) { ?>
<div class="card p-4">
    <h5>Generated Serials</h5>

    <textarea class="form-control mb-3" rows="8"><?php
        foreach ($generated as $s) echo $s . PHP_EOL;
    ?></textarea>

    <a target="_blank"
       href="bulk_print_selected.php?ids=<?= implode(',', $generated_ids) ?>"
       class="btn btn-success">
       🖨 Print These Barcodes
    </a>
</div>
<?php } ?>

<?php include 'layout/footer.php'; ?>
