<?php
/**
 * Product Inventory Management
 * XChange 2025 Registration System
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';
require_once 'product_helper.php';

// Get database connection
$conn = getDBConnection();

// Check authentication and permissions
$auth = new AdminAuth($conn);
$auth->requirePermission('registrations');

$productManager = new ProductManager($conn);
$currentPage = 'product-inventory';

// Handle stock adjustment actions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!$auth->hasPermission('payments')) {
        header('Location: access_denied.php');
        exit;
    }
    
    try {
        switch ($_POST['action']) {
            case 'adjust_stock':
                $productId = intval($_POST['product_id']);
                $adjustment = intval($_POST['adjustment']);
                $reason = trim($_POST['reason']);
                
                // Get current stock
                $sql = "SELECT name, total_stock, available_stock FROM products WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->execute([$productId]);
                $product = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($product && $product['total_stock'] !== null) {
                    $newTotal = $product['total_stock'] + $adjustment;
                    $newAvailable = $product['available_stock'] + $adjustment;
                    
                    if ($newTotal >= 0 && $newAvailable >= 0) {
                        // Update stock
                        $updateSql = "UPDATE products SET total_stock = ?, available_stock = ?, updated_at = NOW() WHERE id = ?";
                        $updateStmt = $conn->prepare($updateSql);
                        $updateStmt->execute([$newTotal, $newAvailable, $productId]);
                        
                        // Log stock movement
                        $productManager->logStockMovement($productId, $adjustment, 'manual_adjustment', $reason);
                        
                        $message = "Stock adjusted successfully for {$product['name']}.";
                        $messageType = "success";
                        
                        $auth->logActivity('adjust_stock', "Adjusted stock for product ID {$productId} by {$adjustment}. Reason: {$reason}");
                    } else {
                        $message = "Error: Stock adjustment would result in negative stock.";
                        $messageType = "error";
                    }
                } else {
                    $message = "Error: Product not found or has unlimited stock.";
                    $messageType = "error";
                }
                break;
        }
    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = "error";
    }
}

// Get inventory data
$inventoryData = getInventoryOverview();
$stockMovements = getRecentStockMovements();
$lowStockProducts = getLowStockProducts();

// Helper functions
function getInventoryOverview() {
    global $conn;
    
    $sql = "SELECT p.*, pc.name as category_name,
                   CASE 
                       WHEN p.total_stock IS NULL THEN 'unlimited'
                       WHEN p.available_stock > (p.total_stock * 0.5) THEN 'high'
                       WHEN p.available_stock > (p.total_stock * 0.2) THEN 'medium'
                       WHEN p.available_stock > 0 THEN 'low'
                       ELSE 'out'
                   END as stock_level,
                   COALESCE((SELECT COUNT(*) FROM registration_products rp WHERE rp.product_id = p.id AND rp.stock_status = 'reserved'), 0) as pending_reservations
            FROM products p
            LEFT JOIN product_categories pc ON p.category_id = pc.id
            WHERE p.is_active = 1
            ORDER BY pc.display_order, p.display_order, p.name";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getRecentStockMovements($limit = 20) {
    global $conn;
    
    $sql = "SELECT psm.*, p.name as product_name, p.product_code
            FROM product_stock_movements psm
            JOIN products p ON psm.product_id = p.id
            ORDER BY psm.created_at DESC
            LIMIT ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute([$limit]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getLowStockProducts() {
    global $conn;
    
    $sql = "SELECT p.*, pc.name as category_name
            FROM products p
            LEFT JOIN product_categories pc ON p.category_id = pc.id
            WHERE p.is_active = 1 
                  AND p.total_stock IS NOT NULL 
                  AND p.available_stock <= (p.total_stock * 0.2)
            ORDER BY (p.available_stock / p.total_stock) ASC";
    
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Inventory Management - XChange 2025 Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <link rel="stylesheet" href="product-inventory.css">
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>
    
    <div class="admin-content">
        <div class="page-header">
            <h1>Inventory Management</h1>
            <p>Monitor stock levels, reservations, and inventory movements</p>
        </div>

        <?php if ($message): ?>
            <div class="alert alert-<?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <!-- Inventory Overview -->
        <div class="inventory-overview">
            <div class="overview-cards">
                <div class="overview-card">
                    <div class="card-icon">📦</div>
                    <div class="card-content">
                        <div class="card-title">Total Products</div>
                        <div class="card-value"><?php echo count($inventoryData); ?></div>
                    </div>
                </div>
                <div class="overview-card">
                    <div class="card-icon">⚠️</div>
                    <div class="card-content">
                        <div class="card-title">Low Stock Alerts</div>
                        <div class="card-value"><?php echo count($lowStockProducts); ?></div>
                    </div>
                </div>
                <div class="overview-card">
                    <div class="card-icon">🔄</div>
                    <div class="card-content">
                        <div class="card-title">Pending Reservations</div>
                        <div class="card-value"><?php echo array_sum(array_column($inventoryData, 'pending_reservations')); ?></div>
                    </div>
                </div>
                <div class="overview-card">
                    <div class="card-icon">📈</div>
                    <div class="card-content">
                        <div class="card-title">Recent Movements</div>
                        <div class="card-value"><?php echo count($stockMovements); ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Low Stock Alerts -->
        <?php if (!empty($lowStockProducts)): ?>
            <div class="inventory-section">
                <h2>⚠️ Low Stock Alerts</h2>
                <div class="alert-products">
                    <?php foreach ($lowStockProducts as $product): ?>
                        <div class="alert-product">
                            <div class="alert-product-info">
                                <div class="product-name"><?php echo htmlspecialchars($product['name']); ?></div>
                                <div class="product-code"><?php echo htmlspecialchars($product['product_code']); ?></div>
                            </div>
                            <div class="alert-stock">
                                <div class="stock-numbers">
                                    <?php echo $product['available_stock']; ?> / <?php echo $product['total_stock']; ?>
                                </div>
                                <div class="stock-percentage">
                                    <?php echo round(($product['available_stock'] / $product['total_stock']) * 100); ?>%
                                </div>
                            </div>
                            <?php if ($auth->hasPermission('payments')): ?>
                                <button onclick="openStockAdjustment(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars($product['name']); ?>')" 
                                        class="btn-adjust">Adjust Stock</button>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Inventory Table -->
        <div class="inventory-section">
            <h2>📦 Product Inventory</h2>
            <div class="inventory-table-container">
                <table class="inventory-table">
                    <thead>
                        <tr>
                            <th>Product</th>
                            <th>Category</th>
                            <th>Stock Status</th>
                            <th>Available</th>
                            <th>Reserved</th>
                            <th>Sold</th>
                            <th>Total</th>
                            <?php if ($auth->hasPermission('payments')): ?>
                                <th>Actions</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($inventoryData as $product): ?>
                            <tr>
                                <td>
                                    <div class="product-info">
                                        <div class="product-name"><?php echo htmlspecialchars($product['name']); ?></div>
                                        <div class="product-code"><?php echo htmlspecialchars($product['product_code']); ?></div>
                                    </div>
                                </td>
                                <td><?php echo $product['category_name'] ?: 'Uncategorized'; ?></td>
                                <td>
                                    <span class="stock-badge stock-<?php echo $product['stock_level']; ?>">
                                        <?php echo ucfirst($product['stock_level']); ?>
                                    </span>
                                </td>
                                <td class="stock-number"><?php echo $product['total_stock'] === null ? '∞' : $product['available_stock']; ?></td>
                                <td class="stock-number"><?php echo $product['reserved_stock']; ?></td>
                                <td class="stock-number"><?php echo $product['sold_stock']; ?></td>
                                <td class="stock-number"><?php echo $product['total_stock'] === null ? '∞' : $product['total_stock']; ?></td>
                                <?php if ($auth->hasPermission('payments')): ?>
                                    <td>
                                        <?php if ($product['total_stock'] !== null): ?>
                                            <button onclick="openStockAdjustment(<?php echo $product['id']; ?>, '<?php echo htmlspecialchars($product['name']); ?>')" 
                                                    class="btn-adjust-small">Adjust</button>
                                        <?php endif; ?>
                                    </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Recent Stock Movements -->
        <div class="inventory-section">
            <h2>📈 Recent Stock Movements</h2>
            <div class="movements-table-container">
                <table class="movements-table">
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Product</th>
                            <th>Movement</th>
                            <th>Type</th>
                            <th>Reference</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($stockMovements as $movement): ?>
                            <tr>
                                <td><?php echo date('M j, Y H:i', strtotime($movement['created_at'])); ?></td>
                                <td>
                                    <div class="product-info">
                                        <div class="product-name"><?php echo htmlspecialchars($movement['product_name']); ?></div>
                                        <div class="product-code"><?php echo htmlspecialchars($movement['product_code']); ?></div>
                                    </div>
                                </td>
                                <td>
                                    <span class="movement-quantity <?php echo $movement['quantity_change'] > 0 ? 'positive' : 'negative'; ?>">
                                        <?php echo $movement['quantity_change'] > 0 ? '+' : ''; ?><?php echo $movement['quantity_change']; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="movement-type"><?php echo ucfirst(str_replace('_', ' ', $movement['movement_type'])); ?></span>
                                </td>
                                <td class="movement-reference"><?php echo htmlspecialchars(($movement['reference_id'] ?? '') ?: ($movement['notes'] ?? '') ?: '-'); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Stock Adjustment Modal -->
    <?php if ($auth->hasPermission('payments')): ?>
        <div id="stockAdjustmentModal" class="stock-modal">
            <div class="stock-modal-content">
                <div class="stock-modal-header">
                    <h3 class="stock-modal-title">Adjust Stock</h3>
                    <button onclick="closeStockAdjustment()" class="modal-close">&times;</button>
                </div>
                <form id="stockAdjustmentForm" method="POST">
                    <div class="stock-modal-body">
                        <input type="hidden" name="action" value="adjust_stock">
                        <input type="hidden" name="product_id" id="adjustProductId">
                        
                        <div class="form-group">
                            <label class="form-label">Product</label>
                            <div id="adjustProductName" class="product-display"></div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Stock Adjustment *</label>
                            <input type="number" name="adjustment" id="stockAdjustment" class="form-input" 
                                   placeholder="Enter positive or negative number" required>
                            <div class="form-help">Use positive numbers to add stock, negative to reduce</div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Reason *</label>
                            <textarea name="reason" id="adjustmentReason" class="form-textarea" 
                                      placeholder="Explain the reason for this adjustment" required></textarea>
                        </div>
                    </div>
                    <div class="stock-modal-footer">
                        <button type="button" onclick="closeStockAdjustment()" class="btn-cancel">Cancel</button>
                        <button type="submit" class="btn-save">Apply Adjustment</button>
                    </div>
                </form>
            </div>
        </div>
    <?php endif; ?>

    <script>
        function openStockAdjustment(productId, productName) {
            document.getElementById('adjustProductId').value = productId;
            document.getElementById('adjustProductName').textContent = productName;
            document.getElementById('stockAdjustment').value = '';
            document.getElementById('adjustmentReason').value = '';
            document.getElementById('stockAdjustmentModal').classList.add('active');
        }
        
        function closeStockAdjustment() {
            document.getElementById('stockAdjustmentModal').classList.remove('active');
        }
    </script>

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