<?php
session_start();

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

require 'db_connect.php';

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

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

// -----------------------------
// Fetch purchase details
// -----------------------------
$stmt = $conn->prepare("SELECT id, product_name, quantity, supplier_name, purchase_date 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();
}

// -----------------------------
// Count already assigned serials
// -----------------------------
$assigned_stmt = $conn->prepare("SELECT COUNT(*) AS c FROM purchase_items WHERE purchase_id = ?");
$assigned_stmt->bind_param("i", $purchase_id);
$assigned_stmt->execute();
$assigned_res   = $assigned_stmt->get_result();
$assigned_row   = $assigned_res->fetch_assoc();
$assigned_count = (int)($assigned_row['c'] ?? 0);
$assigned_stmt->close();

$total_quantity = (int)$purchase['quantity'];
$remaining      = max(0, $total_quantity - $assigned_count);

// Build list of products only for remaining slots
$products = [];
if ($remaining > 0) {
    for ($i = 0; $i < $remaining; $i++) {
        $products[] = $purchase['product_name'];
    }
}

// -----------------------------
// Load serial numbers for editing
// -----------------------------
$existing_serials = [];
if ($assigned_count > 0) {
    $serial_stmt = $conn->prepare("SELECT serial_number FROM purchase_items WHERE purchase_id = ?");
    $serial_stmt->bind_param("i", $purchase_id);
    $serial_stmt->execute();
    $serial_res = $serial_stmt->get_result();
    while ($row = $serial_res->fetch_assoc()) {
        $existing_serials[] = $row['serial_number'];
    }
    $serial_stmt->close();
}

// -----------------------------
// Handle form submission
// -----------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Recalculate remaining inside POST too (safety in case of changes)
    $assigned_stmt = $conn->prepare("SELECT COUNT(*) AS c FROM purchase_items WHERE purchase_id = ?");
    $assigned_stmt->bind_param("i", $purchase_id);
    $assigned_stmt->execute();
    $assigned_res   = $assigned_stmt->get_result();
    $assigned_row   = $assigned_res->fetch_assoc();
    $assigned_count = (int)($assigned_row['c'] ?? 0);
    $assigned_stmt->close();

    $total_quantity = (int)$purchase['quantity'];
    $remaining      = max(0, $total_quantity - $assigned_count);

    $serial_numbers = $_POST['serial_numbers'] ?? []; // Array

    // If nothing remaining, block any insert
    if ($remaining <= 0) {
        $message = "<div class='alert alert-error'>❌ All serial numbers for this purchase are already assigned. You cannot add more.</div>";
    } else {

        // 1) Check count vs remaining
        if (count($serial_numbers) != $remaining) {
            $message = "<div class='alert alert-error'>❌ You must enter exactly $remaining serial number(s) for the remaining items.</div>";
        } else {
            // Trim all serials
            $clean_serials = [];
            foreach ($serial_numbers as $serial) {
                $clean_serials[] = trim($serial);
            }

            // 2) Check duplicates inside the form itself
            if (count($clean_serials) !== count(array_unique($clean_serials))) {
                $message = "<div class='alert alert-error'>❌ Duplicate serial numbers detected in the list. Each serial must be unique.</div>";
            } else {
                // 3) Check if any of these serials already exist in DB
                $exists_conflict = false;
                $check_stmt = $conn->prepare("SELECT id FROM purchase_items WHERE serial_number = ? LIMIT 1");

                foreach ($clean_serials as $serial) {
                    // Just in case someone bypasses HTML required
                    if ($serial === '') {
                        $exists_conflict = true;
                        break;
                    }
                    $check_stmt->bind_param("s", $serial);
                    $check_stmt->execute();
                    $res = $check_stmt->get_result();
                    if ($res->num_rows > 0) {
                        $exists_conflict = true;
                        break;
                    }
                }
                $check_stmt->close();

                if ($exists_conflict) {
                    $message = "<div class='alert alert-error'>❌ One or more serial numbers are already used in the system. Please enter unique serial numbers.</div>";
                } else {
                    // 4) All good – insert
                    $insert_stmt = $conn->prepare("
                        INSERT INTO purchase_items (purchase_id, product_name, serial_number)
                        VALUES (?, ?, ?)
                    ");

                    foreach ($clean_serials as $serial) {
                        $insert_stmt->bind_param("iss", $purchase_id, $purchase['product_name'], $serial);
                        $insert_stmt->execute();
                    }
                    $insert_stmt->close();

                    // Redirect to view page after success
                    header("Location: view_serial_numbers.php?purchase_id=" . $purchase_id . "&success=1");
                    exit();
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include 'head.php'; ?>
    <link rel="stylesheet" href="admin_purchases.css">
</head>
<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">Assign 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: <?= $total_quantity ?> ·
                    Assigned: <?= $assigned_count ?> ·
                    Remaining: <?= $remaining ?>
                </div>
            </div>
        </div>

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

        <div class="page-card">
            <div class="page-card-title">Enter one serial for each remaining unit</div>

            <?php if ($remaining <= 0): ?>
                <p class="empty-row">
                    ✅ All serial numbers for this purchase have already been assigned.
                </p>
                <a href="view_serial_numbers.php?purchase_id=<?= (int)$purchase_id ?>" class="btn-primary" style="text-decoration:none;">
                    View Serial Numbers
                </a>
                <a href="admin_purchases.php"
                   class="btn-primary"
                   style="margin-left: 8px; text-decoration:none; background:transparent; border:1px solid rgba(148,163,184,0.7); color:var(--text-main);">
                    ← Back to Purchases
                </a>
            <?php else: ?>
                <form method="POST" class="expense-form">
                    <div class="table-wrapper">
                        <table class="pos-table">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Product Name</th>
                                    <th>Serial Number</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($products as $index => $product): ?>
                                    <tr>
                                        <td><?= $assigned_count + $index + 1 ?></td>
                                        <td><?= htmlspecialchars($product) ?></td>
                                        <td>
                                            <input
                                                type="text"
                                                name="serial_numbers[]"
                                                required
                                                placeholder="Serial Number <?= $assigned_count + $index + 1 ?>"
                                            />
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <button type="submit" class="btn-primary" style="margin-top: 14px;">
                        Save Serial Numbers
                    </button>

                    <a href="view_serial_numbers.php?purchase_id=<?= (int)$purchase_id ?>"
                       class="btn-primary"
                       style="margin-top: 14px; margin-left: 8px; text-decoration:none; background:transparent; border:1px solid rgba(148,163,184,0.7); color:var(--text-main);">
                        View Existing Serial Numbers
                    </a>
                </form>
            <?php endif; ?>
        </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>
