<?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');

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize & validate inputs
    $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 {
        // Check if inventory for this product/store exists (optional, can be skipped if multiple entries allowed)
        // For now, we allow multiple inventory entries with same product/store since this is the stock record.

        $stmt = $conn->prepare("INSERT INTO inventory 
            (product_id, store_id, barcode, quantity, cost_price, selling_price, created_at, updated_at, modified_by, modified_at) 
            VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW(), ?, NOW())");
        $stmt->bind_param("iisiddi", $product_id, $store_id, $barcode, $quantity, $cost_price, $selling_price, $_SESSION['user_id']);
        if ($stmt->execute()) {
            $success = "Inventory item added successfully.";
            // Redirect to inventory.php after short delay
            header("Refresh:2; url=inventory.php");
        } else {
            $error = "Database error: " . $stmt->error;
        }
    }
}

// Fetch products and stores for dropdown
$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");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Add 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>Add 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 while ($p = $products->fetch_assoc()): ?>
                <option value="<?= $p['id'] ?>" <?= (isset($_POST['product_id']) && $_POST['product_id'] == $p['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 while ($s = $stores->fetch_assoc()): ?>
                <option value="<?= $s['id'] ?>" <?= (isset($_POST['store_id']) && $_POST['store_id'] == $s['id']) ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['store_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

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

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

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

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

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

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

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