<?php
session_start();

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

require 'db_connect.php';

$page_title = "View Serial Numbers | Admin";
$username   = $_SESSION['username'];
$message    = "";

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

// Get purchase details
$stmt = $conn->prepare("SELECT id, product_name, quantity, supplier_name FROM purchases WHERE id = ?");
$stmt->bind_param("i", $purchase_id);
$stmt->execute();
$purchase_result = $stmt->get_result();
$purchase = $purchase_result->fetch_assoc();
$stmt->close();

if (!$purchase) {
    header("Location: admin_purchases.php?error=notfound");
    exit();
}

// Fetch serial numbers for this purchase
$serial_stmt = $conn->prepare("SELECT id, serial_number FROM purchase_items WHERE purchase_id = ?");
$serial_stmt->bind_param("i", $purchase_id);
$serial_stmt->execute();
$serial_result = $serial_stmt->get_result();
$serials = [];
while ($row = $serial_result->fetch_assoc()) {
    $serials[] = $row;
}
$serial_stmt->close();

// Handle serial number deletion
if (isset($_GET['delete_serial_id'])) {
    $serial_id = intval($_GET['delete_serial_id']);
    if ($serial_id > 0) {
        $delete_stmt = $conn->prepare("DELETE FROM purchase_items WHERE id = ?");
        $delete_stmt->bind_param("i", $serial_id);
        if ($delete_stmt->execute()) {
            header("Location: view_serial_numbers.php?purchase_id=$purchase_id&deleted=1");
            exit();
        } else {
            $message = "<div class='alert alert-error'>❌ Error deleting serial number: " . htmlspecialchars($conn->error) . "</div>";
        }
        $delete_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">View and Edit Serial Numbers</div>
                <div class="page-subtitle">
                    Purchase #<?= (int)$purchase_id ?> ·
                    Supplier: <strong><?= htmlspecialchars($purchase['supplier_name'] ?? '-') ?></strong> ·
                    Product: <strong><?= htmlspecialchars($purchase['product_name']) ?></strong> ·
                    Qty: <?= (int)$purchase['quantity'] ?> ·
                    Assigned: <?= count($serials) ?>
                </div>
            </div>
        </div>

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

        <div class="page-card">
            <div class="page-card-title">Serial Numbers Assigned</div>
            <table class="pos-table">
                <thead>
                    <tr>
                        <th>Serial Number</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($serials) > 0): ?>
                        <?php foreach ($serials as $serial): ?>
                            <tr>
                                <td><?= htmlspecialchars($serial['serial_number']) ?></td>
                                <td>
                                    <a href="edit_serial_number.php?purchase_id=<?= $purchase_id ?>&serial_id=<?= $serial['id'] ?>" class="edit-btn">Edit</a>
                                    <a href="view_serial_numbers.php?purchase_id=<?= $purchase_id ?>&delete_serial_id=<?= $serial['id'] ?>" class="delete-btn" onclick="return confirm('Are you sure you want to delete this serial number?');">Delete</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="2" class="empty-row">No serial numbers found for this purchase.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <a href="admin_purchases.php" class="btn-primary">Back to Purchases</a>
        </div>
    </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>
