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

/* ========= UNIQUE SERIAL FUNCTION ========= */
function generateUniqueSerial($model_id, $conn)
{
    $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();

    if (!$prefix) {
        $conn->query("UNLOCK TABLES");
        return false;
    }

    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();
    $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;
}

/* ========= HANDLE GENERATE ========= */
if (isset($_POST['generate'])) {
    $generated = generateUniqueSerial((int)$_POST['model_id'], $conn);
}

$models = $conn->query("SELECT * FROM laptop_models ORDER BY brand, model");
$serials = $conn->query(
    "SELECT s.id, s.serial_number, s.printed, m.brand, m.model
     FROM laptop_serials s
     JOIN laptop_models m ON s.model_id = m.id
     ORDER BY s.id DESC LIMIT 20"
);

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

<h3 class="mb-4">Generate Serial</h3>

<?php if (isset($generated)) { ?>
<div class="alert alert-success">
    Generated Serial: <b><?= $generated ?></b>
</div>
<?php } ?>

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

<div class="card p-4">
<table class="table table-bordered">
<tr>
<th>ID</th><th>Brand</th><th>Model</th><th>Serial</th><th>Status</th><th>Print</th>
</tr>
<?php while ($row = $serials->fetch_assoc()) { ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['brand'] ?></td>
<td><?= $row['model'] ?></td>
<td><?= $row['serial_number'] ?></td>
<td><?= $row['printed'] ? 'Printed' : 'New' ?></td>
<td>
<a target="_blank" href="print_barcode.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-secondary">
Print
</a>
</td>
</tr>
<?php } ?>
</table>
</div>

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