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

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

// Handle Stock Update (In or Out)
if (isset($_POST['action'])) {
    $id = (int)$_POST['item_id'];
    $quantity = floatval($_POST['quantity']);
    $action = $_POST['action']; // 'in' or 'out'

    if ($quantity <= 0) {
        $error = "Quantity must be greater than zero.";
    } else {
        // Get current stock
        $stmt = $conn->prepare("SELECT current_stock FROM inventory_master WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        $row = $result->fetch_assoc();
        $current = $row['current_stock'] ?? 0;

        if ($action === 'out' && $quantity > $current) {
            $error = "Cannot issue more than available stock ($current).";
        } else {
            $new_stock = ($action === 'in') ? $current + $quantity : $current - $quantity;

            $update_stmt = $conn->prepare("UPDATE inventory_master SET current_stock = ?, last_stock_update = NOW() WHERE id = ?");
            $update_stmt->bind_param("di", $new_stock, $id);

            if ($update_stmt->execute()) {
                $success = "Stock updated successfully! New stock: $new_stock";
            } else {
                $error = "Error updating stock.";
            }
            $update_stmt->close();
        }
        $stmt->close();
    }
}

// Search functionality
$search = trim($_GET['search'] ?? '');
$where = "";
$params = [];
$types = "";

if ($search !== '') {
    $where = "WHERE sku LIKE ? OR name LIKE ? OR supplier_vendor LIKE ?";
    $like = "%$search%";
    $params = [$like, $like, $like];
    $types = "sss";
}

// Fetch all items with stock info
$sql = "SELECT * FROM inventory_master $where ORDER BY id DESC";
$stmt = $conn->prepare($sql);
if ($where) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Stock</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;
            flex-direction: column;
            color: white;
            padding: 20px;
        }
        .glass-container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            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: 30px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        .header h1 {
            font-size: 2.2rem;
            margin-bottom: 8px;
        }
        .content {
            padding: 40px;
        }
        .search-bar {
            margin-bottom: 30px;
            display: flex;
            gap: 12px;
        }
        .search-bar input {
            flex: 1;
            padding: 14px 18px;
            background: rgba(255,255,255,0.15);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 12px;
            color: white;
            font-size: 1rem;
        }
        .search-bar input::placeholder { color: rgba(255,255,255,0.6); }
        .search-bar button {
            padding: 14px 24px;
            background: #8b5cf6;
            border: none;
            border-radius: 12px;
            color: white;
            cursor: pointer;
        }
        .message {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .success { background: rgba(34,197,94,0.3); border: 1px solid #4ade80; }
        .error { background: rgba(239,68,68,0.3); border: 1px solid #f87171; }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 16px;
            text-align: left;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        th {
            background: rgba(255,255,255,0.1);
            font-weight: 600;
        }
        .stock-low { color: #fb923c; font-weight: bold; }
        .stock-critical { color: #ef4444; font-weight: bold; }

        .action-form {
            display: flex;
            gap: 8px;
            align-items: center;
        }
        .action-form input[type="number"] {
            width: 80px;
            padding: 8px;
            background: rgba(255,255,255,0.15);
            border: 1px solid rgba(255,255,255,0.3);
            border-radius: 8px;
            color: white;
        }
        .btn-in { background: #22c55e; }
        .btn-out { background: #ef4444; }
        .btn-small {
            padding: 8px 12px;
            border: none;
            border-radius: 8px;
            color: white;
            cursor: pointer;
            font-size: 0.9rem;
        }

        @media (max-width: 992px) {
            table { font-size: 0.9rem; }
            th, td { padding: 12px; }
        }
        @media (max-width: 768px) {
            .content { padding: 20px; }
            table { display: block; overflow-x: auto; white-space: nowrap; }
            .search-bar { flex-direction: column; }
        }
        @media (max-width: 480px) {
            .header h1 { font-size: 1.8rem; }
            .action-form { flex-direction: column; }
            .action-form input[type="number"] { width: 100%; }
        }
    </style>
</head>
<body>
    <div class="glass-container">
        <div class="header">
            <h1>Manage Stock</h1>
            <p>Update incoming and outgoing stock quantities</p>
        </div>

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

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

            <form class="search-bar" method="GET">
                <input type="text" name="search" placeholder="Search by SKU, Name, or Supplier..." value="<?= htmlspecialchars($search) ?>">
                <button type="submit"><i class="fas fa-search"></i> Search</button>
            </form>

            <table>
                <thead>
                    <tr>
                        <th>SKU</th>
                        <th>Item Name</th>
                        <th>Supplier</th>
                        <th>UOM</th>
                        <th>Current Stock</th>
                        <th>Last Updated</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result->num_rows === 0): ?>
                        <tr>
                            <td colspan="7" style="text-align:center; padding: 40px;">
                                No items found.
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php while ($item = $result->fetch_assoc()): ?>
                            <?php
                                $stock_class = '';
                                if ($item['current_stock'] <= 0) {
                                    $stock_class = 'stock-critical';
                                } elseif ($item['current_stock'] <= ($item['reorder_level'] ?: 10)) {
                                    $stock_class = 'stock-low';
                                }
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($item['sku']) ?></td>
                                <td><?= htmlspecialchars($item['name']) ?></td>
                                <td><?= htmlspecialchars($item['supplier_vendor']) ?></td>
                                <td><?= htmlspecialchars($item['uom'] ?: '-') ?></td>
                                <td class="<?= $stock_class ?>">
                                    <?= number_format($item['current_stock'], 2) ?>
                                    <?php if ($stock_class === 'stock-critical'): ?>
                                        <i class="fas fa-exclamation-circle" title="Out of stock"></i>
                                    <?php elseif ($stock_class === 'stock-low'): ?>
                                        <i class="fas fa-bell" title="Low stock"></i>
                                    <?php endif; ?>
                                </td>
                                <td><?= $item['last_stock_update'] ? date('d M Y, h:i A', strtotime($item['last_stock_update'])) : '-' ?></td>
                                <td>
                                    <form class="action-form" method="POST">
                                        <input type="hidden" name="item_id" value="<?= $item['id'] ?>">
                                        <input type="number" name="quantity" step="0.01" min="0.01" placeholder="Qty" required>
                                        <button type="submit" name="action" value="in" class="btn-small btn-in" title="Add Stock">
                                            <i class="fas fa-plus"></i> In
                                        </button>
                                        <button type="submit" name="action" value="out" class="btn-small btn-out" title="Issue Stock">
                                            <i class="fas fa-minus"></i> Out
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</body>
</html>