<?php
// admin/inventory.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Handle Stock Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_stock'])) {
    $product_id = intval($_POST['product_id'] ?? 0);
    $quantity = intval($_POST['quantity'] ?? 0);
    $min_stock = intval($_POST['min_stock'] ?? 5);
    $max_stock = intval($_POST['max_stock'] ?? 100);
    $reorder_level = intval($_POST['reorder_level'] ?? 10);
    $location = sanitize($_POST['location'] ?? '');
    $note = sanitize($_POST['note'] ?? '');
    
    if ($product_id > 0) {
        try {
            // Get current stock
            $stmt = $pdo->prepare("SELECT stock FROM products WHERE id = ?");
            $stmt->execute([$product_id]);
            $current = $stmt->fetch();
            $previous_quantity = $current ? $current['stock'] : 0;
            
            // Update product stock
            $stmt = $pdo->prepare("UPDATE products SET stock = ?, min_stock = ?, max_stock = ?, reorder_level = ? WHERE id = ?");
            $stmt->execute([$quantity, $min_stock, $max_stock, $reorder_level, $product_id]);
            
            // Update or insert inventory
            $stmt = $pdo->prepare("INSERT INTO inventory (product_id, quantity, min_stock, max_stock, reorder_level, location) 
                                   VALUES (?, ?, ?, ?, ?, ?) 
                                   ON DUPLICATE KEY UPDATE 
                                   quantity = ?, min_stock = ?, max_stock = ?, reorder_level = ?, location = ?");
            $stmt->execute([$product_id, $quantity, $min_stock, $max_stock, $reorder_level, $location,
                           $quantity, $min_stock, $max_stock, $reorder_level, $location]);
            
            // Log stock movement
            if ($quantity != $previous_quantity) {
                $type = $quantity > $previous_quantity ? 'adjustment' : 'adjustment';
                $stmt = $pdo->prepare("INSERT INTO stock_movements 
                    (product_id, type, quantity, previous_quantity, new_quantity, note, created_by) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    $product_id,
                    $type,
                    abs($quantity - $previous_quantity),
                    $previous_quantity,
                    $quantity,
                    $note ?: 'Stock adjustment',
                    $_SESSION['admin_id']
                ]);
            }
            
            $_SESSION['success_msg'] = 'Stock updated successfully!';
            header('Location: inventory.php');
            exit;
            
        } catch (Exception $e) {
            $error_msg = 'Error: ' . $e->getMessage();
        }
    }
}

// Handle Bulk Stock Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_update'])) {
    $product_ids = $_POST['product_ids'] ?? [];
    $bulk_quantity = intval($_POST['bulk_quantity'] ?? 0);
    
    if (!empty($product_ids) && $bulk_quantity > 0) {
        $placeholders = implode(',', array_fill(0, count($product_ids), '?'));
        $stmt = $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id IN ($placeholders)");
        $stmt->execute(array_merge([$bulk_quantity], $product_ids));
        $_SESSION['success_msg'] = 'Bulk stock update completed!';
        header('Location: inventory.php');
        exit;
    }
}

// Get inventory with product details
$stmt = $pdo->query("SELECT p.id, p.name, p.sku, p.price, p.stock, p.min_stock, p.max_stock, p.reorder_level,
                     c.name as category_name,
                     (SELECT COUNT(*) FROM order_items WHERE product_id = p.id) as total_sold
                     FROM products p 
                     LEFT JOIN categories c ON p.category_id = c.id 
                     WHERE p.status = 1 
                     ORDER BY p.stock ASC");
$inventory = $stmt->fetchAll();

// Get low stock items
$low_stock = array_filter($inventory, function($item) {
    return $item['stock'] <= $item['reorder_level'];
});

// Get out of stock items
$out_of_stock = array_filter($inventory, function($item) {
    return $item['stock'] <= 0;
});

// Get total stock value
$total_value = 0;
foreach ($inventory as $item) {
    $total_value += $item['stock'] * $item['price'];
}

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

include 'header.php';
?>

<style>
.inventory-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-box {
    background: #fff;
    border-radius: 12px;
    padding: 18px 20px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0,0,0,0.08);
    transition: all 0.3s ease;
}

.stat-box:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.stat-box .stat-number {
    font-size: 28px;
    font-weight: 700;
}

.stat-box .stat-label {
    font-size: 13px;
    color: #64748b;
    margin-top: 2px;
}

.stat-box .stat-icon {
    font-size: 24px;
    margin-bottom: 5px;
}

.status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 500;
}

.status-badge.in-stock { background: #86efac; color: #166534; }
.status-badge.low-stock { background: #fcd34d; color: #92400e; }
.status-badge.out-of-stock { background: #fca5a5; color: #991b1b; }

.inventory-table td {
    vertical-align: middle;
}

.stock-input {
    width: 80px;
    display: inline-block;
}

.alert-container {
    margin-bottom: 20px;
}

.action-btns {
    display: flex;
    gap: 4px;
    flex-wrap: wrap;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-warehouse me-2"></i> Inventory Management</h2>
        <div>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#bulkModal">
                <i class="fa-solid fa-layer-group"></i> Bulk Update
            </button>
            <a href="low-stock.php" class="btn btn-warning">
                <i class="fa-solid fa-exclamation-triangle"></i> Low Stock (<?php echo count($low_stock); ?>)
            </a>
        </div>
    </div>
    
    <!-- Stats -->
    <div class="inventory-stats">
        <div class="stat-box">
            <div class="stat-icon text-primary"><i class="fa-solid fa-boxes"></i></div>
            <div class="stat-number text-primary"><?php echo count($inventory); ?></div>
            <div class="stat-label">Total Products</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-success"><i class="fa-solid fa-check-circle"></i></div>
            <div class="stat-number text-success">
                <?php 
                $in_stock = array_filter($inventory, function($item) {
                    return $item['stock'] > 0;
                });
                echo count($in_stock);
                ?>
            </div>
            <div class="stat-label">In Stock</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-warning"><i class="fa-solid fa-exclamation-triangle"></i></div>
            <div class="stat-number text-warning"><?php echo count($low_stock); ?></div>
            <div class="stat-label">Low Stock</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-danger"><i class="fa-solid fa-times-circle"></i></div>
            <div class="stat-number text-danger"><?php echo count($out_of_stock); ?></div>
            <div class="stat-label">Out of Stock</div>
        </div>
        <div class="stat-box">
            <div class="stat-icon text-info"><i class="fa-solid fa-dollar-sign"></i></div>
            <div class="stat-number text-info"><?php echo number_format($total_value); ?> TK</div>
            <div class="stat-label">Total Stock Value</div>
        </div>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success"><?php echo $success_msg; ?></div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger"><?php echo $error_msg; ?></div>
    <?php endif; ?>
    
    <!-- Inventory Table -->
    <div class="admin-card">
        <div class="table-responsive">
            <table class="table table-hover inventory-table">
                <thead>
                    <tr>
                        <th style="width:30px;">
                            <input type="checkbox" id="selectAll" onchange="toggleAll(this)">
                        </th>
                        <th>Product</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Stock</th>
                        <th>Min Stock</th>
                        <th>Reorder Level</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($inventory)): ?>
                    <tr>
                        <td colspan="9" class="text-center py-4">
                            <i class="fa-regular fa-box fa-2x text-muted d-block mb-2"></i>
                            No products found in inventory
                        </td>
                    </tr>
                    <?php else: ?>
                    <?php foreach ($inventory as $item): ?>
                    <tr id="invRow_<?php echo $item['id']; ?>">
                        <td>
                            <input type="checkbox" class="product-checkbox" value="<?php echo $item['id']; ?>">
                        </td>
                        <td>
                            <strong><?php echo htmlspecialchars($item['name']); ?></strong>
                            <?php if ($item['sku']): ?>
                            <br><small class="text-muted">SKU: <?php echo $item['sku']; ?></small>
                            <?php endif; ?>
                        </td>
                        <td><?php echo $item['category_name'] ?? 'N/A'; ?></td>
                        <td><?php echo number_format($item['price']); ?> TK</td>
                        <td>
                            <span class="fw-bold <?php echo $item['stock'] <= 0 ? 'text-danger' : ($item['stock'] <= $item['reorder_level'] ? 'text-warning' : 'text-success'); ?>">
                                <?php echo $item['stock']; ?>
                            </span>
                        </td>
                        <td><?php echo $item['min_stock']; ?></td>
                        <td><?php echo $item['reorder_level']; ?></td>
                        <td>
                            <?php if ($item['stock'] <= 0): ?>
                            <span class="status-badge out-of-stock">Out of Stock</span>
                            <?php elseif ($item['stock'] <= $item['reorder_level']): ?>
                            <span class="status-badge low-stock">Low Stock</span>
                            <?php else: ?>
                            <span class="status-badge in-stock">In Stock</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-btns">
                                <button onclick="editStock(<?php echo $item['id']; ?>)" class="btn btn-sm btn-warning">
                                    <i class="fa-solid fa-edit"></i>
                                </button>
                                <button onclick="viewMovements(<?php echo $item['id']; ?>)" class="btn btn-sm btn-info">
                                    <i class="fa-solid fa-history"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Edit Stock Modal -->
<div class="modal fade" id="stockModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-edit me-2"></i> Update Stock</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="update_stock" value="1">
                <input type="hidden" name="product_id" id="stock_product_id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Product</label>
                        <p id="stock_product_name" class="fw-bold"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Current Stock</label>
                        <p id="stock_current_stock" class="fw-bold text-primary"></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">New Quantity</label>
                        <input type="number" name="quantity" id="stock_quantity" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Minimum Stock Level</label>
                        <input type="number" name="min_stock" id="stock_min" class="form-control" value="5">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Maximum Stock Level</label>
                        <input type="number" name="max_stock" id="stock_max" class="form-control" value="100">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Reorder Level</label>
                        <input type="number" name="reorder_level" id="stock_reorder" class="form-control" value="10">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Location</label>
                        <input type="text" name="location" id="stock_location" class="form-control" placeholder="Warehouse location">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2" placeholder="Reason for stock update"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Stock</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Bulk Update Modal -->
<div class="modal fade" id="bulkModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-layer-group me-2"></i> Bulk Stock Update</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="bulk_update" value="1">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Selected Products</label>
                        <div id="bulk_selected_products" class="border p-2 rounded" style="max-height:150px; overflow-y:auto;"></div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Add Quantity</label>
                        <input type="number" name="bulk_quantity" class="form-control" required placeholder="Enter quantity to add">
                    </div>
                    <p class="text-muted small">This will add the specified quantity to all selected products.</p>
                    <input type="hidden" name="product_ids" id="bulk_product_ids">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update All</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Stock Movements Modal -->
<div class="modal fade" id="movementModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-history me-2"></i> Stock Movements</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="movementContent">
                <div class="text-center py-4">
                    <i class="fa-solid fa-spinner fa-spin fa-2x text-primary"></i>
                    <p class="mt-2">Loading...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// ========================================
// SELECT ALL CHECKBOXES
// ========================================
function toggleAll(master) {
    var checkboxes = document.querySelectorAll('.product-checkbox');
    checkboxes.forEach(function(cb) {
        cb.checked = master.checked;
    });
    updateBulkSelection();
}

// ========================================
// UPDATE BULK SELECTION
// ========================================
document.querySelectorAll('.product-checkbox').forEach(function(cb) {
    cb.addEventListener('change', updateBulkSelection);
});

function updateBulkSelection() {
    var checkboxes = document.querySelectorAll('.product-checkbox:checked');
    var selected = [];
    var names = [];
    
    checkboxes.forEach(function(cb) {
        var row = cb.closest('tr');
        var name = row.querySelector('td:nth-child(2) strong').textContent;
        selected.push(cb.value);
        names.push(name);
    });
    
    document.getElementById('bulk_product_ids').value = selected.join(',');
    document.getElementById('bulk_selected_products').innerHTML = names.map(function(name) {
        return '<span class="badge bg-secondary m-1">' + name + '</span>';
    }).join('') || '<span class="text-muted">No products selected</span>';
}

// ========================================
// EDIT STOCK
// ========================================
function editStock(id) {
    fetch('get-inventory-item.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data) {
                document.getElementById('stock_product_id').value = data.id;
                document.getElementById('stock_product_name').textContent = data.name;
                document.getElementById('stock_current_stock').textContent = data.stock + ' units';
                document.getElementById('stock_quantity').value = data.stock || 0;
                document.getElementById('stock_min').value = data.min_stock || 5;
                document.getElementById('stock_max').value = data.max_stock || 100;
                document.getElementById('stock_reorder').value = data.reorder_level || 10;
                document.getElementById('stock_location').value = data.location || '';
                
                var modal = new bootstrap.Modal(document.getElementById('stockModal'));
                modal.show();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', 'Failed to load product data');
        });
}

// ========================================
// VIEW MOVEMENTS
// ========================================
function viewMovements(id) {
    var modal = new bootstrap.Modal(document.getElementById('movementModal'));
    modal.show();
    
    fetch('get-stock-movements.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            var html = '';
            if (data.length > 0) {
                html = `
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th>Date</th>
                                    <th>Type</th>
                                    <th>Quantity</th>
                                    <th>Previous</th>
                                    <th>New</th>
                                    <th>Note</th>
                                </tr>
                            </thead>
                            <tbody>
                    `;
                data.forEach(function(m) {
                    var typeColors = {
                        purchase: 'success',
                        sale: 'danger',
                        return: 'info',
                        adjustment: 'warning',
                        transfer: 'primary'
                    };
                    html += `
                        <tr>
                            <td>${new Date(m.created_at).toLocaleString()}</td>
                            <td><span class="badge bg-${typeColors[m.type] || 'secondary'}">${m.type}</span></td>
                            <td class="fw-bold">${m.quantity}</td>
                            <td>${m.previous_quantity}</td>
                            <td>${m.new_quantity}</td>
                            <td>${m.note || '-'}</td>
                        </tr>
                    `;
                });
                html += `
                            </tbody>
                        </table>
                    </div>
                `;
            } else {
                html = '<p class="text-muted text-center">No stock movements found</p>';
            }
            document.getElementById('movementContent').innerHTML = html;
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('movementContent').innerHTML = '<div class="alert alert-danger">Failed to load movements</div>';
        });
}

// ========================================
// SHOW ALERT
// ========================================
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    alertContainer.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() { alert.remove(); }, 500);
        }
    }, 5000);
}
</script>

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