<?php
session_start();

if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.html?error=unauthorized");
    exit();
}

require 'db_connect.php';

$page_title = "Edit Serial Number | Admin";
$username   = $_SESSION['username'];
$message    = "";

// -----------------------------
// Get purchase_id and serial_id from the query string
// -----------------------------
$purchase_id = isset($_GET['purchase_id']) ? intval($_GET['purchase_id']) : 0;
$serial_id = isset($_GET['serial_id']) ? intval($_GET['serial_id']) : 0;
if ($purchase_id <= 0 || $serial_id <= 0) {
    header("Location: admin_purchases.php");
    exit();
}

// -----------------------------
// Fetch serial number details for editing
// -----------------------------
$stmt = $conn->prepare("SELECT serial_number FROM purchase_items WHERE purchase_id = ? AND id = ?");
$stmt->bind_param("ii", $purchase_id, $serial_id);
$stmt->execute();
$serial_result = $stmt->get_result();
$serial = $serial_result->fetch_assoc();
$stmt->close();

if (!$serial) {
    header("Location: view_serial_numbers.php?purchase_id=$purchase_id&error=notfound");
    exit();
}

// -----------------------------
// Handle form submission for serial number edit
// -----------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new_serial_number = trim($_POST['serial_number'] ?? '');

    // Validate serial number
    if ($new_serial_number === '') {
        $message = "<div class='alert alert-error'>❌ Serial number cannot be empty.</div>";
    } else {
        // Check if the new serial number is already used
        $check_stmt = $conn->prepare("SELECT id FROM purchase_items WHERE serial_number = ? LIMIT 1");
        $check_stmt->bind_param("s", $new_serial_number);
        $check_stmt->execute();
        $check_res = $check_stmt->get_result();
        if ($check_res->num_rows > 0) {
            $message = "<div class='alert alert-error'>❌ Serial number is already used. Please use a unique serial number.</div>";
        } else {
            // Update serial number in the database
            $update_stmt = $conn->prepare("UPDATE purchase_items SET serial_number = ? WHERE purchase_id = ? AND id = ?");
            $update_stmt->bind_param("sii", $new_serial_number, $purchase_id, $serial_id);

            if ($update_stmt->execute()) {
                header("Location: view_serial_numbers.php?purchase_id=$purchase_id&updated=1");
                exit();
            } else {
                $message = "<div class='alert alert-error'>❌ Error updating serial number: " . htmlspecialchars($conn->error) . "</div>";
            }
            $update_stmt->close();
        }
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include 'head.php'; ?>
</head>
<link rel="stylesheet" href="admin_purchases.css">
<body>

<?php include 'sidebar.php'; ?>

<div class="content-wrapper" id="content-wrapper">
    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
            </span>
        </div>
    </div>

    <div class="content-inner">
        <div class="page-header">
            <div>
                <div class="page-title">Edit Serial Number</div>
                <div class="page-subtitle">Editing serial number for the product.</div>
            </div>
        </div>

        <?php if ($message): ?>
            <?= $message ?>
        <?php endif; ?>

        <div class="page-card">
            <form method="POST">
                <div class="form-group">
                    <label for="serial_number">Serial Number</label>
                    <input type="text" id="serial_number" name="serial_number" required value="<?= htmlspecialchars($serial['serial_number']) ?>" />
                </div>
                <button type="submit" class="btn-primary">Update Serial Number</button>
            </form>
        </div>

        <a href="view_serial_numbers.php?purchase_id=<?= $purchase_id ?>" class="btn-primary">Back to Serial Numbers</a>
    </div>
</div>

<script>
function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const wrapper = document.getElementById('content-wrapper');
    if (!sidebar || !wrapper) return;

    const isHidden = sidebar.classList.toggle('hidden');
    if (isHidden) {
        wrapper.classList.add('fullwidth');
    } else {
        wrapper.classList.remove('fullwidth');
    }
}
</script>

</body>
</html>
