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

include 'db_connect.php';

if (!isset($_GET['id'])) {
    header("Location: manage_products.php");
    exit();
}

$id = intval($_GET['id']);
$message = "";

/* -----------------------------
   FETCH PRODUCT FIRST
------------------------------ */
$stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$product = $stmt->get_result()->fetch_assoc();

if (!$product) {
    header("Location: manage_products.php");
    exit();
}

/* -----------------------------
   UPDATE PRODUCT (Qty + Prices + Barcode)
------------------------------ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $name          = trim($_POST['name']);
    $category      = trim($_POST['category']);
    $barcode       = trim($_POST['barcode']);
    $selling_price = floatval($_POST['selling_price']);
    $quantity      = intval($_POST['quantity']);

    // Buying price is editable; if left empty, keep the existing weighted value
    $buying_price_input = isset($_POST['buying_price']) ? trim($_POST['buying_price']) : '';
    if ($buying_price_input === '') {
        $buying_price = (float)$product['buying_price'];
    } else {
        $buying_price = floatval($buying_price_input);
    }

    // Check if barcode is empty or NULL before processing
    if ($barcode === "" || $barcode === NULL) {
        $barcode = NULL; // Allow NULL barcode to stay empty or blank
    } else {
        // Check if barcode already exists in other products
        if ($barcode !== $product['barcode']) {  // Ignore self-update check
            $stmt = $conn->prepare("SELECT COUNT(*) FROM products WHERE barcode = ?");
            $stmt->bind_param("s", $barcode);
            $stmt->execute();
            $stmt->bind_result($count);
            $stmt->fetch();

            if ($count > 0) {
                $message = "❌ Error: Barcode already exists for another product.";
            }
        }
    }

    // If no duplicate barcode and barcode is valid, proceed with updating the product
    if (empty($message)) {
        $stmt = $conn->prepare("
            UPDATE products
            SET name = ?, category = ?, barcode = ?, selling_price = ?, quantity = ?, buying_price = ?
            WHERE id = ?
        ");

        // types: s (name), s (category), s (barcode), d (selling_price), i (quantity), d (buying_price), i (id)
        $stmt->bind_param("sssdidi", $name, $category, $barcode, $selling_price, $quantity, $buying_price, $id);

        if ($stmt->execute()) {
            header("Location: manage_products.php?success=Product updated successfully");
            exit();
        } else {
            $message = "❌ Error updating product.";
        }

        // Refresh product in case we stay on this page
        $stmt = $conn->prepare("SELECT * FROM products WHERE id=?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $product = $stmt->get_result()->fetch_assoc();
    }
}

// Page title used in <title> via head.php if needed
$page_title = "Edit Product";

include('head.php'); // brings in theme, base styles, JS like toggleAdminTheme()
?>

<body>

<?php include("sidebar.php"); ?>

<!-- MAIN CONTENT WRAPPER -->
<div class="content-wrapper" id="content-wrapper">

    <!-- TOP BAR (same style as manage_products) -->
    <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>

    <!-- PAGE HEADER -->
    <div class="page-header">
        <div>
            <div class="page-title">Edit Product</div>
            <div class="page-subtitle">
                Editing: <strong><?= htmlspecialchars($product['name']) ?></strong>
                · ID: <?= (int)$product['id'] ?>
            </div>
        </div>

        <div class="page-header-right">
            <div class="top-buttons">
                <a href="manage_products.php" class="btn">← Back to Products</a>
                <a href="batch_list.php?id=<?= (int)$product['id'] ?>" class="btn">View Stock Batches</a>
            </div>
        </div>
    </div>

    <!-- MAIN CARD -->
    <div class="page-card">

        <?php if ($message): ?>
            <div class="edit-message"><?= $message ?></div>
        <?php endif; ?>

        <form method="POST" class="edit-form">

            <!-- ONE COLUMN FORM -->
            <div class="form-single-column">

                <div class="form-group">
                    <label for="name">Product Name</label>
                    <input
                        type="text"
                        id="name"
                        name="name"
                        value="<?= htmlspecialchars($product['name']) ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label for="category">Category</label>
                    <input
                        type="text"
                        id="category"
                        name="category"
                        value="<?= htmlspecialchars($product['category']) ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label for="barcode">Barcode</label>
                    <input
                        type="text"
                        id="barcode"
                        name="barcode"
                        value="<?= htmlspecialchars($product['barcode'] ?? '') ?>"
                    >
                </div>

                <div class="form-group">
                    <label for="buying_price">
                        Average Buying Price (Weighted)
                        <span class="hint">Leave blank to keep current</span>
                    </label>
                    <input
                        type="number"
                        step="0.01"
                        id="buying_price"
                        name="buying_price"
                        value="<?= htmlspecialchars($product['buying_price']) ?>"
                    >
                </div>

                <div class="form-group">
                    <label for="selling_price">Default Selling Price</label>
                    <input
                        type="number"
                        step="0.01"
                        id="selling_price"
                        name="selling_price"
                        value="<?= htmlspecialchars($product['selling_price']) ?>"
                        required
                    >
                </div>

                <div class="form-group">
                    <label for="quantity">Stock Available</label>
                    <input
                        type="number"
                        id="quantity"
                        name="quantity"
                        value="<?= htmlspecialchars($product['quantity']) ?>"
                        required
                    >
                </div>

            </div>

            <!-- SUMMARY STRIP -->
            <div class="summary-strip">
                <div>
                    <span class="summary-label">Current Total Stock Value:</span>
                    <span class="summary-value" id="stockValue">
                        KES <?= number_format($product['buying_price'] * $product['quantity'], 2) ?>
                    </span>
                </div>
                <div class="summary-meta">
                    Created: <?= htmlspecialchars($product['date_added'] ?? '-') ?>
                </div>
            </div>

            <!-- ACTIONS -->
            <div class="form-actions">
                <button type="submit" class="btn">Save Changes</button>
                <a href="manage_products.php" class="btn btn-outline">Cancel</a>
            </div>
        </form>

    </div>

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

</div> <!-- END content-wrapper -->

<!-- Add your CSS here -->
<style>
    /* Same base layout as manage_products */

    .content-wrapper {
        margin-left: 250px;
        padding: 25px 30px;
        background: var(--bg-main);
        min-height: 100vh;
        box-sizing: border-box;
        transition: margin-left 0.25s ease;
    }

    body.sidebar-hidden .content-wrapper {
        margin-left: 0;
    }
    body.sidebar-hidden .sidebar {
        display: none;
    }

    .topbar {
        background: var(--bg-sidebar);
        padding: 14px 18px;
        margin: -5px -4px 18px -4px;
        border-radius: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #B8860B;
        border: 1px solid rgba(184,134,11,0.65);
        box-shadow: 0 6px 18px rgba(0,0,0,0.5);
        position: sticky;
        top: 0;
        z-index: 50;
    }

    .topbar-left {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .topbar-title {
        font-weight: 600;
        font-size: 15px;
        letter-spacing: 0.03em;
        color: var(--text-heading);
    }

    .topbar-right {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 13px;
    }

    .topbar-user strong {
        font-weight: 600;
    }

    .menu-btn {
        font-size: 22px;
        cursor: pointer;
        color: var(--accent-gold);
        transition: 0.3s;
        line-height: 1;
    }

    .menu-btn:hover {
        color: #e6c34b;
    }

    .theme-toggle {
        border-radius: 999px;
        border: 1px solid rgba(184,134,11,0.7);
        padding: 6px 12px;
        background: rgba(0,0,0,0.4);
        color: #f9f9f9;
        font-size: 12px;
        cursor: pointer;
    }

    .theme-toggle:hover {
        background: rgba(0,0,0,0.65);
    }

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        flex-wrap: wrap;
        margin-bottom: 18px;
        gap: 12px;
    }

    .page-title {
        font-size: 22px;
        font-weight: 600;
        color: var(--text-heading);
    }

    .page-subtitle {
        font-size: 13px;
        color: var(--accent-gold);
        margin-top: 4px;
    }

    .page-header-right {
        display: flex;
        flex-direction: column;
        gap: 10px;
        align-items: flex-end;
    }

    .top-buttons {
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        gap: 10px;
    }

    .btn {
        padding: 8px 14px;
        border-radius: 999px;
        border: none;
        background: var(--accent-gold);
        color: var(--bg-main);
        font-size: 13px;
        font-weight: 500;
        text-decoration: none;
        display: inline-block;
        cursor: pointer;
    }

    .btn:hover {
        background: var(--accent-gold-soft);
    }

    .btn.btn-outline {
        background: transparent;
        color: var(--accent-gold);
        border: 1px solid var(--accent-gold);
    }

    .btn.btn-outline:hover {
        background: var(--accent-gold);
        color: var(--bg-main);
    }

    .page-card {
        background: var(--bg-card);
        border-radius: 14px;
        padding: 18px 22px 22px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.25);
        border: 1px solid rgba(0,0,0,0.15);
        max-width: 640px;
        margin: 0 auto;
    }

    body:not([data-theme="light"]) .page-card {
        border-color: #0a4a85;
    }

    .edit-message {
        margin-bottom: 12px;
        padding: 10px 12px;
        border-radius: 8px;
        font-size: 13px;
        background: rgba(220,38,38,0.08);
        color: #f97316;
        border: 1px solid rgba(248,113,113,0.6);
    }

    .edit-form {
        margin-top: 6px;
    }

    /* ONE COLUMN FORM */
    .form-single-column {
        display: flex;
        flex-direction: column;
        gap: 14px;
    }

    .form-group label {
        font-size: 13px;
        font-weight: 500;
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        color: var(--text-heading);
    }

    .form-group .hint {
        font-size: 11px;
        color: var(--text-muted);
        font-weight: 400;
    }

    .form-group input {
        margin-top: 5px;
        width: 100%;
        padding: 9px 10px;
        border-radius: 7px;
        border: 1px solid rgba(148,163,184,0.7);
        background: var(--bg-input, #020617);
        color: var(--text-main);
        font-size: 13px;
        box-sizing: border-box;
    }

    body[data-theme="light"] .form-group input {
        background: #ffffff;
    }

    .form-group input:focus {
        outline: none;
        border-color: var(--accent-gold);
        box-shadow: 0 0 0 1px rgba(244,180,0,0.3);
    }

    .summary-strip {
        margin-top: 18px;
        padding: 12px 14px;
        border-radius: 10px;
        background: rgba(0,0,0,0.25);
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 10px;
        font-size: 13px;
    }

    body[data-theme="light"] .summary-strip {
        background: rgba(255,255,255,0.9);
        border: 1px solid rgba(229,231,235,0.9);
    }

    .summary-label {
        color: var(--text-muted);
        margin-right: 6px;
    }

    .summary-value {
        font-weight: 600;
        color: var(--accent-gold);
    }

    .summary-meta {
        font-size: 12px;
        color: var(--text-muted);
        text-align: right;
    }

    .form-actions {
        margin-top: 18px;
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
        justify-content: flex-end;
    }

    @media (max-width: 900px) {
        .content-wrapper {
            margin-left: 0;
            padding: 18px 14px;
        }

        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .page-header-right {
            align-items: flex-start;
        }
    }
</style>

</body>
</html>
