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

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

$user_role = $_SESSION['role_id'];
$user_store_id = $_SESSION['store_id'] ?? null;

$stores = $conn->query("SELECT id, store_name FROM stores ORDER BY store_name");
$products = $conn->query("SELECT id, product_name FROM products ORDER BY product_name");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Stock Transfer - Digital POS</title>
<link rel="stylesheet" href="../../css/dashboard.css" />
<style>
    body, html {
        margin: 0; padding: 10px; font-family: 'Segoe UI', sans-serif;
        background: url('../../images/profile.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: 80px auto; max-width: 600px; padding: 30px 40px;
        background: rgba(255,255,255,0.08); border-radius: 20px;
        backdrop-filter: blur(15px); box-shadow: 0 8px 32px rgba(0,0,0,0.5);
    }
    h2 { text-align: center; margin-bottom: 25px; }
    label { display: block; margin-top: 15px; font-weight: bold; }
    select, input[type="number"], textarea {
        width: 100%; padding: 8px 12px; border-radius: 8px; border: none;
        background: rgba(255,255,255,0.2); color: black; font-size: 14px;
        margin-top: 6px;
    }
    select:disabled {
        background: rgba(255,255,255,0.15);
        color: gray;
    }
    button {
        margin-top: 25px; width: 100%; padding: 12px 0;
        background: #ff6f00; border: none; border-radius: 10px;
        color: white; font-size: 16px; cursor: pointer;
    }
    #availableQty {
        margin-top: 5px; font-weight: normal; color: #ffb300;
    }
    .error, .success {
        margin-top: 20px; padding: 10px;
        border-radius: 6px;
        text-align: center;
        display: none;
    }
    .error { background-color: #c62828; }
    .success { background-color: #2e7d32; }
</style>
</head>
<body>
<div class="overlay"></div>
<div class="content">
    <h2>Stock Transfer</h2>
    <form id="transferForm">
        <?php if ($user_role == 1): ?>
            <!-- Admin: Full store access -->
            <label for="from_store">From Store:</label>
            <select id="from_store" name="from_store" required>
                <option value="">Select Store</option>
                <?php while($store = $stores->fetch_assoc()): ?>
                    <option value="<?= $store['id'] ?>"><?= htmlspecialchars($store['store_name']) ?></option>
                <?php endwhile; ?>
            </select>

            <?php $stores->data_seek(0); ?>
            <label for="to_store">To Store:</label>
            <select id="to_store" name="to_store" required>
                <option value="">Select Store</option>
                <?php while($store = $stores->fetch_assoc()): ?>
                    <option value="<?= $store['id'] ?>"><?= htmlspecialchars($store['store_name']) ?></option>
                <?php endwhile; ?>
            </select>
        <?php else: ?>
            <!-- Manager: Store fixed to own store -->
            <label for="from_store">From Store:</label>
            <select id="from_store" name="from_store" disabled>
                <option value="<?= $user_store_id ?>">Your Store</option>
            </select>
            <input type="hidden" name="from_store" value="<?= $user_store_id ?>">

            <label for="to_store">To Store:</label>
            <select id="to_store" name="to_store" disabled>
                <option value="<?= $user_store_id ?>">Your Store</option>
            </select>
            <input type="hidden" name="to_store" value="<?= $user_store_id ?>">
        <?php endif; ?>

        <label for="product">Product:</label>
        <select id="product" name="product" required>
            <option value="">Select Product</option>
            <?php while($product = $products->fetch_assoc()): ?>
                <option value="<?= $product['id'] ?>"><?= htmlspecialchars($product['product_name']) ?></option>
            <?php endwhile; ?>
        </select>
        <div id="availableQty"></div>

        <label for="quantity">Quantity to Transfer:</label>
        <input type="number" id="quantity" name="quantity" min="1" required />

        <label for="remarks">Remarks (optional):</label>
        <textarea id="remarks" name="remarks" rows="3" placeholder="Any notes..."></textarea>

        <button type="submit">Transfer Stock</button>
    </form>

    <div id="message" class=""></div>
</div>

<script>
const fromStore = document.getElementById('from_store');
const product = document.getElementById('product');
const availableQtyDiv = document.getElementById('availableQty');
const quantityInput = document.getElementById('quantity');
const form = document.getElementById('transferForm');
const messageDiv = document.getElementById('message');

function fetchAvailableQty() {
    availableQtyDiv.textContent = '';
    quantityInput.value = '';
    if (!fromStore.value || !product.value) return;

    fetch(`get_available_quantity.php?store_id=${fromStore.value}&product_id=${product.value}`)
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                availableQtyDiv.textContent = `Available quantity: ${data.quantity}`;
                quantityInput.max = data.quantity;
            } else {
                availableQtyDiv.textContent = 'Error fetching quantity';
                quantityInput.removeAttribute('max');
            }
        })
        .catch(() => {
            availableQtyDiv.textContent = 'Network error';
            quantityInput.removeAttribute('max');
        });
}

fromStore.addEventListener('change', fetchAvailableQty);
product.addEventListener('change', fetchAvailableQty);

form.addEventListener('submit', function(e) {
    e.preventDefault();
    messageDiv.style.display = 'none';
    messageDiv.className = '';

    const formData = new FormData(form);

    const qty = parseInt(formData.get('quantity'));
    const maxQty = parseInt(quantityInput.max || '0');
    if (qty <= 0 || qty > maxQty) {
        messageDiv.textContent = 'Quantity must be between 1 and available stock.';
        messageDiv.className = 'error';
        messageDiv.style.display = 'block';
        return;
    }

    fetch('stock_transfer_process.php', {
        method: 'POST',
        body: formData,
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            messageDiv.textContent = 'Stock transferred successfully!';
            messageDiv.className = 'success';
            form.reset();
            availableQtyDiv.textContent = '';
        } else {
            messageDiv.textContent = data.message || 'Transfer failed.';
            messageDiv.className = 'error';
        }
        messageDiv.style.display = 'block';
    })
    .catch(() => {
        messageDiv.textContent = 'Network error.';
        messageDiv.className = 'error';
        messageDiv.style.display = 'block';
    });
});
</script>
</body>
</html>
