<?php
session_start();
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['role_id'], [1, 2])) {
    header("Location: ../../index.php");
    exit();
}

include('../../includes/config.php');
include('../../includes/header.php');

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) {
    header("Location: inventory.php");
    exit();
}

$error = '';
$success = '';

// Fetch existing inventory record
$stmt = $conn->prepare("SELECT * FROM inventory WHERE id = ? AND deleted_at IS NULL");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    // No record found
    header("Location: inventory.php");
    exit();
}

$inventory = $result->fetch_assoc();

// Fetch products and stores for dropdowns
$products = $conn->query("SELECT id, product_name FROM products ORDER BY product_name ASC");
$stores = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name ASC");

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = (int)($_POST['product_id'] ?? 0);
    $store_id = (int)($_POST['store_id'] ?? 0);
    $barcode = trim($_POST['barcode'] ?? '');
    $quantity = (int)($_POST['quantity'] ?? 0);
    $cost_price = floatval($_POST['cost_price'] ?? 0);
    $selling_price = floatval($_POST['selling_price'] ?? 0);

    if (!$product_id || !$store_id || !$barcode || $quantity < 0 || $cost_price <= 0 || $selling_price <= 0) {
        $error = "Please fill in all fields correctly.";
    } else {
        // Update record
        $stmt_update = $conn->prepare("
            UPDATE inventory SET
                product_id = ?,
                store_id = ?,
                barcode = ?,
                quantity = ?,
                cost_price = ?,
                selling_price = ?,
                updated_at = NOW(),
                modified_by = ?,
                modified_at = NOW()
            WHERE id = ?
        ");
        $stmt_update->bind_param(
            "iisiddii",
            $product_id,
            $store_id,
            $barcode,
            $quantity,
            $cost_price,
            $selling_price,
            $_SESSION['user_id'],
            $id
        );

        if ($stmt_update->execute()) {
            // Audit log after successful update
            $new_data = [
                'product_id' => $product_id,
                'store_id' => $store_id,
                'barcode' => $barcode,
                'quantity' => $quantity,
                'cost_price' => $cost_price,
                'selling_price' => $selling_price,
            ];

            $details = json_encode([
                'before' => $inventory,
                'after' => $new_data,
            ]);

            $action = 'edit_inventory';
            $module = 'Inventory';
            $device_info = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';

            $audit_stmt = $conn->prepare("INSERT INTO audit_log (user_id, action, details, created_at, module, role_id, device_info) VALUES (?, ?, ?, NOW(), ?, ?, ?)");
            $audit_stmt->bind_param("isssis", $_SESSION['user_id'], $action, $details, $module, $_SESSION['role_id'], $device_info);
            $audit_stmt->execute();
            $audit_stmt->close();

            $success = "Inventory updated successfully.";
            // Refresh to show updated data
            header("Refresh:2; url=inventory.php");
        } else {
            $error = "Database error: " . $stmt_update->error;
        }
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Edit Inventory - Digital POS</title>
    <link rel="stylesheet" href="../../css/dashboard.css" />
    <style>
        body, html {
            margin: 0; padding: 0;
            font-family: 'Segoe UI', sans-serif;
            background: url('../../images/bg.jpg') no-repeat center center fixed;
            background-size: cover;
            color: white;
        }
        .overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0,0,0,0.6);
            z-index: -1;
        }
        .content {
            margin: 100px auto;
            max-width: 600px;
            padding: 30px 40px;
            background: rgba(255,255,255,0.08);
            backdrop-filter: blur(15px);
            border-radius: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.5);
        }
        h2 {
            text-align: center;
            margin-bottom: 25px;
        }
        form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        label {
            font-weight: 600;
            margin-bottom: 6px;
        }
        select, input[type=text], input[type=number] {
            padding: 10px 12px;
            border-radius: 8px;
            border: none;
            background: rgba(255,255,255,0.2);
            color: white;
            font-size: 16px;
        }
        input::placeholder {
            color: rgba(255,255,255,0.7);
        }
        button {
            background: #ff6f00;
            border: none;
            padding: 12px;
            border-radius: 8px;
            font-weight: 700;
            cursor: pointer;
            color: white;
            font-size: 18px;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background: #e65c00;
        }
        .message {
            text-align: center;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
        .error {
            background-color: rgba(255, 77, 77, 0.8);
        }
        .success {
            background-color: rgba(77, 255, 77, 0.8);
        }
        a.back-link {
            display: block;
            margin-top: 15px;
            text-align: center;
            color: #ff6f00;
            text-decoration: none;
            font-weight: 600;
        }
        a.back-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>Edit Inventory Item</h2>

    <?php if ($error): ?>
        <div class="message error"><?= htmlspecialchars($error) ?></div>
    <?php elseif ($success): ?>
        <div class="message success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <form method="POST" action="">
        <label for="product_id">Product</label>
        <select name="product_id" id="product_id" required>
            <option value="">-- Select Product --</option>
            <?php
            // Rewind result pointer for products query
            $products->data_seek(0);
            while ($p = $products->fetch_assoc()):
            ?>
                <option value="<?= $p['id'] ?>" <?= ($p['id'] == ($_POST['product_id'] ?? $inventory['product_id'])) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($p['product_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <label for="store_id">Store</label>
        <select name="store_id" id="store_id" required>
            <option value="">-- Select Store --</option>
            <?php
            // Rewind result pointer for stores query
            $stores->data_seek(0);
            while ($s = $stores->fetch_assoc()):
            ?>
                <option value="<?= $s['id'] ?>" <?= ($s['id'] == ($_POST['store_id'] ?? $inventory['store_id'])) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['store_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

        <label for="barcode">Barcode</label>
        <input type="text" id="barcode" name="barcode" required value="<?= htmlspecialchars($_POST['barcode'] ?? $inventory['barcode']) ?>" />

        <label for="quantity">Quantity</label>
        <input type="number" id="quantity" name="quantity" min="0" required value="<?= htmlspecialchars($_POST['quantity'] ?? $inventory['quantity']) ?>" />

        <label for="cost_price">Cost Price (MK)</label>
        <input type="number" id="cost_price" name="cost_price" min="0.01" step="0.01" required value="<?= htmlspecialchars($_POST['cost_price'] ?? $inventory['cost_price']) ?>" />

        <label for="selling_price">Selling Price (MK)</label>
        <input type="number" id="selling_price" name="selling_price" min="0.01" step="0.01" required value="<?= htmlspecialchars($_POST['selling_price'] ?? $inventory['selling_price']) ?>" />

        <button type="submit">Update Inventory</button>
    </form>

    <a href="inventory.php" class="back-link">&larr; Back to Inventory</a>
</div>

<?php include('../../includes/footer.php'); ?>
</body>
</html>
