<?php
session_start();
require_once('includes/vendor-security.php');
include_once('../includes/config.php');

$vendorId = $_SESSION['vendor_id'];

// Handle Stock Update
if (isset($_POST['update_stock'])) {
    $productId = intval($_POST['product_id']);
    $adjustmentType = $_POST['adjustment_type']; // 'add' or 'remove'
    $quantity = intval($_POST['quantity']);
    $reason = mysqli_real_escape_string($con, $_POST['reason']);
    $userId = $_SESSION['id']; // vendor user id (from security check)

    if ($quantity > 0) {
        // Verify ownership
        $checkProduct = mysqli_query($con, "SELECT stock_quantity FROM products WHERE id='$productId' AND vendor_id='$vendorId'");

        if (mysqli_num_rows($checkProduct) > 0) {
            $row = mysqli_fetch_assoc($checkProduct);
            $currentStock = intval($row['stock_quantity']);

            $adjustment = ($adjustmentType == 'add') ? $quantity : -$quantity;
            $newStock = $currentStock + $adjustment;

            // Prevent negative stock
            if ($newStock < 0) {
                $_SESSION['error'] = "Error: Cannot remove more stock than available.";
            } else {
                // Update Product Table
                $updateQuery = mysqli_query($con, "UPDATE products SET stock_quantity='$newStock', updationDate=NOW() WHERE id='$productId'");

                if ($updateQuery) {
                    // Log to Inventory Logs
                    $logQuery = mysqli_query($con, "INSERT INTO inventory_logs 
                        (product_id, vendor_id, adjustment, previous_stock, current_stock, reason, created_by) 
                        VALUES ('$productId', '$vendorId', '$adjustment', '$currentStock', '$newStock', '$reason', '$userId')");

                    if ($logQuery) {
                        $_SESSION['msg'] = "Stock updated successfully!";
                    } else {
                        $_SESSION['error'] = "Stock updated but log failed: " . mysqli_error($con);
                    }
                } else {
                    $_SESSION['error'] = "Failed to update stock.";
                }
            }
        } else {
            $_SESSION['error'] = "Unauthorized or product not found.";
        }
    } else {
        $_SESSION['error'] = "Quantity must be greater than zero.";
    }
    header("Location: inventory.php");
    exit();
}

// Fetch Vendor Products
$query = "SELECT id, productName, productImage1, sku, stock_quantity, productPrice, productAvailability FROM products WHERE vendor_id='$vendorId' ORDER BY id DESC";
$result = mysqli_query($con, $query);
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>Inventory Management - Vendor Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@latest/dist/style.css" rel="stylesheet" />
    <link href="../__admin__/css/styles.css" rel="stylesheet" />
    <link href="../__admin__/css/admin-professional.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/js/all.min.js"></script>
</head>

<body class="sb-nav-fixed">
    <?php include_once('includes/header.php'); ?>
    <div id="layoutSidenav">
        <?php include_once('includes/sidebar.php'); ?>
        <div id="layoutSidenav_content">
            <main>
                <div class="container-fluid px-4">
                    <div class="page-header mt-4">
                        <div>
                            <h1><i class="fas fa-boxes me-2"></i> Inventory Management</h1>
                            <p>Track and update your product stock levels.</p>
                        </div>
                    </div>

                    <?php if (isset($_SESSION['msg'])) { ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="fas fa-check-circle me-2"></i>
                            <?php echo $_SESSION['msg'];
                            unset($_SESSION['msg']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>
                    <?php if (isset($_SESSION['error'])) { ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            <?php echo $_SESSION['error'];
                            unset($_SESSION['error']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php } ?>

                    <div class="table-card">
                        <div class="card-header">
                            <h5 class="mb-0"><i class="fas fa-list me-2"></i>Current Stock</h5>
                        </div>
                        <div class="card-body">
                            <table id="datatablesSimple">
                                <thead>
                                    <tr>
                                        <th>Product</th>
                                        <th>SKU</th>
                                        <th>Current Stock</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = mysqli_fetch_array($result)) {
                                        $stock = intval($row['stock_quantity']);
                                        $statusClass = 'success';
                                        $statusText = 'In Stock';

                                        if ($stock == 0) {
                                            $statusClass = 'danger';
                                            $statusText = 'Out of Stock';
                                        } elseif ($stock < 10) {
                                            $statusClass = 'warning';
                                            $statusText = 'Low Stock';
                                        }
                                        ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <img src="../__admin__/productimages/<?php echo $row['id']; ?>/<?php echo $row['productImage1']; ?>"
                                                        style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; margin-right: 10px;">
                                                    <div>
                                                        <strong>
                                                            <?php echo htmlentities($row['productName']); ?>
                                                        </strong>
                                                        <div class="text-muted small">ID:
                                                            <?php echo $row['id']; ?>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <?php echo htmlentities($row['sku']); ?>
                                            </td>
                                            <td>
                                                <span class="fw-bold" style="font-size: 1.1em;">
                                                    <?php echo $stock; ?>
                                                </span>
                                            </td>
                                            <td><span class="badge bg-<?php echo $statusClass; ?>">
                                                    <?php echo $statusText; ?>
                                                </span></td>
                                            <td>
                                                <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal"
                                                    data-bs-target="#stockModal" data-id="<?php echo $row['id']; ?>"
                                                    data-name="<?php echo htmlentities($row['productName']); ?>"
                                                    data-stock="<?php echo $stock; ?>">
                                                    <i class="fas fa-sync-alt me-1"></i> Update Stock
                                                </button>
                                                <a href="inventory-history.php?pid=<?php echo $row['id']; ?>"
                                                    class="btn btn-outline-secondary btn-sm" title="View History">
                                                    <i class="fas fa-history"></i>
                                                </a>
                                            </td>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>
            <?php include_once('includes/footer.php'); ?>
        </div>
    </div>

    <!-- Update Stock Modal -->
    <div class="modal fade" id="stockModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="post">
                    <div class="modal-header">
                        <h5 class="modal-title">Update Stock</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="product_id" id="modal_product_id">

                        <div class="mb-3">
                            <label class="form-label">Product:</label>
                            <input type="text" class="form-control" id="modal_product_name" readonly>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Current Stock:</label>
                                <input type="text" class="form-control" id="modal_current_stock" readonly>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Action:</label>
                                <select name="adjustment_type" class="form-select" required>
                                    <option value="add">Add Stock (+)</option>
                                    <option value="remove">Remove Stock (-)</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Quantity to Adjust:</label>
                            <input type="number" name="quantity" class="form-control" min="1" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Reason (Optional):</label>
                            <input type="text" name="reason" class="form-control"
                                placeholder="e.g. New Shipment, Damaged, Correction">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="submit" name="update_stock" class="btn btn-primary">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../__admin__/js/scripts.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/simple-datatables@latest"></script>
    <script src="../__admin__/js/datatables-simple-demo.js"></script>

    <script>
        var stockModal = document.getElementById('stockModal');
        stockModal.addEventListener('show.bs.modal', function (event) {
            var button = event.relatedTarget;
            var id = button.getAttribute('data-id');
            var name = button.getAttribute('data-name');
            var stock = button.getAttribute('data-stock');

            var modalId = stockModal.querySelector('#modal_product_id');
            var modalName = stockModal.querySelector('#modal_product_name');
            var modalStock = stockModal.querySelector('#modal_current_stock');

            modalId.value = id;
            modalName.value = name;
            modalStock.value = stock;
        });
    </script>
</body>

</html>