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

$id = (int)($_GET['id'] ?? 0);

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

if (!$brand) {
    die("Invalid model");
}

/* UPDATE */
if (isset($_POST['update'])) {
    $brand  = clean($_POST['brand']);
    $model  = clean($_POST['model']);
    $prefix = clean($_POST['prefix']);

    $up = $conn->prepare(
        "UPDATE laptop_models
         SET brand=?, model=?, prefix=?
         WHERE id=?"
    );
    $up->bind_param("sssi", $brand, $model, $prefix, $id);
    $up->execute();
    $up->close();

    header("Location: add_model.php");
    exit;
}

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

<h3 class="mb-4">Edit Laptop Model</h3>

<div class="card p-4">
<form method="post">
    <div class="mb-3">
        <label>Brand</label>
        <input class="form-control" name="brand" value="<?= $brand ?>" required>
    </div>
    <div class="mb-3">
        <label>Model</label>
        <input class="form-control" name="model" value="<?= $model ?>" required>
    </div>
    <div class="mb-3">
        <label>Prefix</label>
        <input class="form-control" name="prefix" value="<?= $prefix ?>" required>
    </div>
    <button class="btn btn-primary" name="update">Update</button>
    <a href="add_model.php" class="btn btn-secondary">Cancel</a>
</form>
</div>

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