<?php
session_start();
require_once("../config/config.php");

$sku = trim($_GET['sku'] ?? '');
if (empty($sku)) {
    die("Invalid access. No SKU provided.");
}

// Fetch item details
$sql = "SELECT * FROM inventory_master WHERE sku = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $sku);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Item not found.");
}

$item = $result->fetch_assoc();
$stmt->close();

$success = "";
$error = "";

// Handle form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $quantity = trim($_POST['quantity'] ?? '');
    $type = $_POST['type'] ?? ''; // INBOUND or OUTBOUND
    $reason = trim($_POST['reason'] ?? '');

    $errors = [];

    if (!is_numeric($quantity) || $quantity <= 0) {
        $errors[] = "Quantity must be a positive number.";
    }

    if (!in_array($type, ['INBOUND', 'OUTBOUND'])) {
        $errors[] = "Invalid transaction type.";
    }

    // Check if enough stock for outbound
    if ($type === 'OUTBOUND' && $quantity > $item['current_stock']) {
        $errors[] = "Cannot deduct {$quantity}. Current stock is only {$item['current_stock']}.";
    }

    if (empty($errors)) {
        // Determine new stock
        $new_stock = $type === 'INBOUND'
            ? $item['current_stock'] + $quantity
            : $item['current_stock'] - $quantity;

        // Update current stock
        $update_sql = "UPDATE inventory_master SET current_stock = ? WHERE sku = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("ds", $new_stock, $sku);

        if ($update_stmt->execute()) {
            // Log transaction
            $trans_sql = "INSERT INTO inventory_transactions 
                          (sku, transaction_type, quantity, reason) 
                          VALUES (?, ?, ?, ?)";
            $trans_stmt = $conn->prepare($trans_sql);
            $trans_type = $type;
            $trans_stmt->bind_param("ssds", $sku, $trans_type, $quantity, $reason);
            $trans_stmt->execute();
            $trans_stmt->close();

            $success = "Stock updated successfully! New stock: " . number_format($new_stock, 3);
            $item['current_stock'] = $new_stock; // Update local variable for display
        } else {
            $error = "Failed to update stock.";
        }
        $update_stmt->close();
    } else {
        $error = implode("<br>", $errors);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Adjust Stock - <?= htmlspecialchars($item['sku']) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
            background: linear-gradient(rgba(0,0,0,0.6), rgba(0,0,0,0.7)),
                        url('../background.jpeg') center/cover no-repeat fixed;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            color: white;
        }
        .glass-container {
            width: 100%;
            max-width: 800px;
            background: rgba(255, 255, 255, 0.12);
            backdrop-filter: blur(16px);
            border-radius: 24px;
            border: 1px solid rgba(255, 255, 255, 0.25);
            box-shadow: 0 25px 50px rgba(0,0,0,0.4);
            overflow: hidden;
        }
        .header {
            background: rgba(255, 255, 255, 0.15);
            padding: 40px 30px;
            text-align: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        .header h1 { font-size: 2.2rem; margin-bottom: 0.5rem; }
        .header p { opacity: 0.9; }

        .content { padding: 40px; }

        .item-info {
            background: rgba(255, 255, 255, 0.08);
            padding: 20px;
            border-radius: 16px;
            margin-bottom: 30px;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }
        .info-item strong { display: block; font-size: 0.9rem; opacity: 0.8; margin-bottom: 5px; }
        .current-stock {
            font-size: 2rem;
            font-weight: bold;
            color: #a78bfa;
            text-align: center;
            padding: 20px;
            background: rgba(167, 139, 250, 0.15);
            border-radius: 16px;
            border: 2px dashed rgba(167, 139, 250, 0.4);
        }

        .message {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 30px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 500;
        }
        .success { background: rgba(34, 197, 94, 0.3); border: 1px solid #4ade80; }
        .error   { background: rgba(239, 68, 68, 0.3); border: 1px solid #f87171; }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 24px;
        }
        .form-group { display: flex; flex-direction: column; }
        label {
            margin-bottom: 8px;
            font-weight: 600;
            font-size: 0.95rem;
        }
        input, select, textarea {
            padding: 14px 16px;
            background: rgba(255, 255, 255, 0.15);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 12px;
            color: white;
            font-size: 1rem;
        }
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #a78bfa;
            background: rgba(255, 255, 255, 0.22);
            box-shadow: 0 0 0 4px rgba(167, 139, 250, 0.3);
        }
        textarea { min-height: 100px; resize: vertical; }

        .full-width { grid-column: span 2; }

        .submit-btn {
            margin-top: 20px;
            padding: 16px;
            background: linear-gradient(135deg, #7c3aed, #a78bfa);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 30px rgba(139, 92, 246, 0.5);
        }

        .back-link {
            display: block;
            text-align: center;
            margin-top: 30px;
            color: #a78bfa;
            text-decoration: none;
        }

        @media (max-width: 768px) {
            .form-grid { grid-template-columns: 1fr; }
            .full-width { grid-column: span 1; }
            .item-info { grid-template-columns: 1fr; }
            .header { padding: 30px 20px; }
            .header h1 { font-size: 1.8rem; }
        }
    </style>
</head>
<body>
    <div class="glass-container">
        <div class="header">
            <h1>Adjust Stock</h1>
            <p>Manage stock for item: <strong><?= htmlspecialchars($item['sku']) ?></strong></p>
        </div>

        <div class="content">
            <div class="item-info">
                <div>
                    <strong>Item Name</strong>
                    <?= htmlspecialchars($item['name']) ?>
                </div>
                <div>
                    <strong>Model No</strong>
                    <?= htmlspecialchars($item['model_no']) ?>
                </div>
                <div>
                    <strong>Supplier</strong>
                    <?= htmlspecialchars($item['supplier_vendor']) ?>
                </div>
                <div>
                    <strong>UOM</strong>
                    <?= htmlspecialchars($item['uom'] ?? 'N/A') ?>
                </div>
                <div class="current-stock">
                    Current Stock<br>
                    <span><?= number_format($item['current_stock'], 3) ?></span>
                </div>
                <div>
                    <strong>Reorder Level</strong>
                    <?= number_format($item['reorder_level'], 3) ?>
                    <?php if ($item['current_stock'] <= $item['reorder_level']): ?>
                        <span style="color:#f87171; display:block; margin-top:5px;">⚠️ Low Stock!</span>
                    <?php endif; ?>
                </div>
            </div>

            <?php if ($success): ?>
                <div class="message success">
                    <i class="fas fa-check-circle"></i>
                    <?= $success ?>
                </div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="message error">
                    <i class="fas fa-exclamation-triangle"></i>
                    <?= $error ?>
                </div>
            <?php endif; ?>

            <form method="POST">
                <div class="form-grid">
                    <div class="form-group">
                        <label for="type">Transaction Type</label>
                        <select name="type" id="type" required>
                            <option value="">Select Type</option>
                            <option value="INBOUND">Add Stock (Inbound)</option>
                            <option value="OUTBOUND">Deduct Stock (Outbound)</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="quantity">Quantity</label>
                        <input type="number" name="quantity" id="quantity" step="0.001" min="0.001" required placeholder="e.g., 50">
                    </div>

                    <div class="form-group full-width">
                        <label for="reason">Reason / Note (Optional)</label>
                        <textarea name="reason" id="reason" placeholder="e.g., Received from supplier, Used in production, Damaged item, etc."></textarea>
                    </div>
                </div>

                <button type="submit" class="submit-btn">
                    <i class="fas fa-exchange-alt"></i> Update Stock
                </button>
            </form>

            <a href="inventory_list.php" class="back-link">
                <i class="fas fa-arrow-left"></i> Back to Inventory List
            </a>
        </div>
    </div>
</body>
</html>