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

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    die("Invalid stock entry ID.");
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_id = $_POST['product_id'] ?? '';
    $store_id = $_POST['store_id'] ?? '';
    $quantity = $_POST['quantity'] ?? '';
    $cost_price = $_POST['cost_price'] ?? '';
    $purchase_date = $_POST['purchase_date'] ?? '';
    $remarks = $_POST['remarks'] ?? '';

    // Basic validation
    if (!$product_id || !$store_id || !$quantity || !$cost_price || !$purchase_date) {
        $error = "Please fill all required fields.";
    } else {
        $updated_by = $_SESSION['user_id'];
        $updated_at = date('Y-m-d H:i:s');

        $stmt = $conn->prepare("
            UPDATE stock_entries SET
                product_id = ?,
                store_id = ?,
                quantity = ?,
                cost_price = ?,
                purchase_date = ?,
                remarks = ?,
                updated_by = ?,
                updated_at = ?
            WHERE id = ?
        ");

        if (!$stmt) {
            $error = "Prepare failed: " . $conn->error;
        } else {
            $stmt->bind_param(
                "iiidssisi",
                $product_id,
                $store_id,
                $quantity,
                $cost_price,
                $purchase_date,
                $remarks,
                $updated_by,
                $updated_at,
                $id
            );

            if ($stmt->execute()) {
                header("Location: stock_entries.php?msg=Stock+entry+updated+successfully");
                exit();
            } else {
                $error = "Execute failed: " . $stmt->error;
            }
            $stmt->close();
        }
    }
}

// Fetch current stock entry data
$stmt = $conn->prepare("SELECT * FROM stock_entries WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$result = $stmt->get_result();
$entry = $result->fetch_assoc();
$stmt->close();

if (!$entry) {
    die("Stock entry not found.");
}

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

include('../../includes/header.php');
?>

<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 {
        max-width: 600px;
        margin: 100px auto 40px;
        padding: 30px 40px;
        backdrop-filter: blur(15px);
        background: rgba(255, 255, 255, 0.08);
        border-radius: 20px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
    }
    h2 {
        text-align: center;
        margin-bottom: 25px;
    }
    form label {
        display: block;
        margin-bottom: 8px;
        font-weight: bold;
        color: #ffa500;
    }
    form input[type="text"],
    form input[type="number"],
    form input[type="date"],
    form select,
    form textarea {
        width: 100%;
        padding: 10px 12px;
        margin-bottom: 20px;
        border-radius: 10px;
        border: none;
        outline: none;
        background: rgba(255,255,255,0.15);
        color: white;
        font-size: 1rem;
        box-shadow: inset 0 0 6px rgba(255,255,255,0.2);
        resize: vertical;
    }
    form textarea {
        min-height: 80px;
    }
    form button {
        background-color: #ff6f00;
        color: white;
        padding: 12px 20px;
        border: none;
        border-radius: 25px;
        font-weight: bold;
        cursor: pointer;
        width: 100%;
        font-size: 1.1rem;
        transition: background 0.3s ease;
    }
    form button:hover {
        background-color: #e65c00;
    }
    .error {
        background-color: #f44336;
        padding: 10px;
        margin-bottom: 15px;
        border-radius: 8px;
        text-align: center;
    }
</style>

<div class="overlay"></div>
<div class="content">
    <h2>Edit Stock Entry</h2>

    <?php if ($error): ?>
        <div class="error"><?= htmlspecialchars($error) ?></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'] ?>" <?= $p['id'] == $entry['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 while ($s = $stores->fetch_assoc()): ?>
                <option value="<?= $s['id'] ?>" <?= $s['id'] == $entry['store_id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($s['store_name']) ?>
                </option>
            <?php endwhile; ?>
        </select>

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

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

        <label for="purchase_date">Purchase Date *</label>
        <input type="date" name="purchase_date" id="purchase_date" value="<?= htmlspecialchars($entry['purchase_date']) ?>" required>

        <label for="remarks">Remarks</label>
        <textarea name="remarks" id="remarks"><?= htmlspecialchars($entry['remarks']) ?></textarea>

        <button type="submit">Update Stock Entry</button>
    </form>
</div>

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