<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/menu_config.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Handle stock movements
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['action'])) {
        $response = ['success' => false, 'message' => ''];
        
        switch ($_POST['action']) {
            case 'add_stock':
                try {
                    $item_id = $_POST['item_id'];
                    $quantity = $_POST['quantity'];
                    $unit_cost = $_POST['unit_cost'];
                    $reference_type = $_POST['reference_type'] ?? 'MANUAL';
                    $notes = $_POST['notes'] ?? '';
                    
                    // Get current stock
                    $current_stock_query = "SELECT current_stock FROM inventory_items WHERE item_id = ?";
                    $stmt = $conn->prepare($current_stock_query);
                    $stmt->bind_param("i", $item_id);
                    $stmt->execute();
                    $current_stock = $stmt->get_result()->fetch_assoc()['current_stock'];
                    
                    $new_balance = $current_stock + $quantity;
                    $total_value = $quantity * $unit_cost;
                    
                    // Insert stock movement
                    $insert_movement = "INSERT INTO stock_movements (item_id, movement_type, quantity, unit_cost, total_value, balance_after, notes, moved_by) 
                                       VALUES (?, 'IN', ?, ?, ?, ?, ?, ?)";
                    $stmt = $conn->prepare($insert_movement);
                    $stmt->bind_param("idddssi", $item_id, $quantity, $unit_cost, $total_value, $new_balance, $notes, $user_id);
                    
                    if ($stmt->execute()) {
                        $response['success'] = true;
                        $response['message'] = 'Stock added successfully';
                    } else {
                        $response['message'] = 'Failed to add stock';
                    }
                } catch (Exception $e) {
                    $response['message'] = 'Error: ' . $e->getMessage();
                }
                break;
                
            case 'remove_stock':
                try {
                    $item_id = $_POST['item_id'];
                    $quantity = $_POST['quantity'];
                    $reason = $_POST['reason'] ?? 'ADJUSTMENT';
                    $notes = $_POST['notes'] ?? '';
                    
                    // Get current stock
                    $current_stock_query = "SELECT current_stock FROM inventory_items WHERE item_id = ?";
                    $stmt = $conn->prepare($current_stock_query);
                    $stmt->bind_param("i", $item_id);
                    $stmt->execute();
                    $current_stock = $stmt->get_result()->fetch_assoc()['current_stock'];
                    
                    if ($current_stock < $quantity) {
                        $response['message'] = 'Insufficient stock available';
                        break;
                    }
                    
                    $new_balance = $current_stock - $quantity;
                    
                    // Insert stock movement
                    $insert_movement = "INSERT INTO stock_movements (item_id, movement_type, quantity, balance_after, notes, moved_by) 
                                       VALUES (?, ?, ?, ?, ?, ?)";
                    $stmt = $conn->prepare($insert_movement);
                    $stmt->bind_param("isdss", $item_id, $reason, $quantity, $new_balance, $notes, $user_id);
                    
                    if ($stmt->execute()) {
                        $response['success'] = true;
                        $response['message'] = 'Stock removed successfully';
                    } else {
                        $response['message'] = 'Failed to remove stock';
                    }
                } catch (Exception $e) {
                    $response['message'] = 'Error: ' . $e->getMessage();
                }
                break;
        }
        
        header('Content-Type: application/json');
        echo json_encode($response);
        exit();
    }
}

// Get inventory summary stats
$sql_total_items = "SELECT COUNT(*) as total_items FROM inventory_items WHERE is_active = 1";
$total_items = $conn->query($sql_total_items)->fetch_assoc()['total_items'];

$sql_low_stock = "SELECT COUNT(*) as low_stock_items FROM inventory_items 
                  WHERE current_stock <= reorder_point AND is_active = 1";
$low_stock_items = $conn->query($sql_low_stock)->fetch_assoc()['low_stock_items'];

$sql_total_value = "SELECT SUM(current_stock * unit_cost) as total_value FROM inventory_items WHERE is_active = 1";
$total_inventory_value = $conn->query($sql_total_value)->fetch_assoc()['total_value'] ?? 0;

$sql_categories = "SELECT COUNT(*) as total_categories FROM inventory_categories WHERE is_active = 1";
$total_categories = $conn->query($sql_categories)->fetch_assoc()['total_categories'];

// Get inventory items with categories
$sql_inventory = "SELECT 
    ii.item_id,
    ii.item_code,
    ii.item_name,
    ii.current_stock,
    ii.minimum_stock,
    ii.reorder_point,
    ii.unit_cost,
    ii.unit,
    ic.category_name,
    s.supplier_name,
    CASE 
        WHEN ii.current_stock <= ii.reorder_point THEN 'Low Stock'
        WHEN ii.current_stock <= ii.minimum_stock THEN 'Critical'
        ELSE 'Normal'
    END as stock_status
FROM inventory_items ii
LEFT JOIN inventory_categories ic ON ii.category_id = ic.category_id
LEFT JOIN suppliers s ON ii.supplier_id = s.supplier_id
WHERE ii.is_active = 1
ORDER BY ii.item_name";
$result_inventory = $conn->query($sql_inventory);

// Get recent stock movements
$sql_movements = "SELECT 
    sm.movement_id,
    sm.movement_type,
    sm.quantity,
    sm.unit_cost,
    sm.total_value,
    sm.balance_after,
    sm.notes,
    sm.movement_date,
    ii.item_name,
    ii.item_code,
    u.full_name as moved_by_name
FROM stock_movements sm
JOIN inventory_items ii ON sm.item_id = ii.item_id
JOIN users u ON sm.moved_by = u.user_id
ORDER BY sm.movement_date DESC
LIMIT 10";
$result_movements = $conn->query($sql_movements);

// Get categories for dropdown
$sql_categories_list = "SELECT category_id, category_name FROM inventory_categories WHERE is_active = 1 ORDER BY category_name";
$result_categories = $conn->query($sql_categories_list);

// Get suppliers for dropdown
$sql_suppliers_list = "SELECT supplier_id, supplier_name FROM suppliers WHERE is_active = 1 ORDER BY supplier_name";
$result_suppliers = $conn->query($sql_suppliers_list);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Stock Management - Laundry System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stats-row {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            transform: translateY(-1px);
        }
        
        .stat-title {
            font-size: 0.875rem;
            font-weight: 500;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin-bottom: 0.5rem;
        }
        
        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.5rem;
        }
        
        .stat-change {
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .table-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            overflow: hidden;
            margin-bottom: 2rem;
        }
        
        .table-header {
            padding: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            background: #f8fafc;
            display: flex;
            justify-content: between;
            align-items: center;
        }
        
        .table-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin: 0;
        }
        
        .data-table th {
            background: #f8fafc;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            font-size: 0.875rem;
            color: #64748b;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .data-table td {
            padding: 1rem;
            border-bottom: 1px solid #f1f5f9;
            font-size: 0.875rem;
        }
        
        .data-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-normal { background: #dcfce7; color: #166534; }
        .status-low { background: #fef3c7; color: #92400e; }
        .status-critical { background: #fee2e2; color: #991b1b; }
        .status-in { background: #dcfce7; color: #166534; }
        .status-out { background: #fee2e2; color: #991b1b; }
        .status-adjustment { background: #dbeafe; color: #1d4ed8; }
        .status-waste { background: #f3e8ff; color: #7c3aed; }
        
        .btn-primary {
            background: #667eea;
            border-color: #667eea;
        }
        
        .btn-primary:hover {
            background: #5a67d8;
            border-color: #5a67d8;
        }
        
        .btn-success {
            background: #059669;
            border-color: #059669;
        }
        
        .btn-warning {
            background: #d97706;
            border-color: #d97706;
        }
        
        .btn-danger {
            background: #dc2626;
            border-color: #dc2626;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .modal-header {
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .action-buttons {
            display: flex;
            gap: 0.5rem;
        }
        
        .action-btn {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            border: none;
            font-size: 0.75rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .progress-bar {
            background: #667eea;
        }
        
        .alert {
            border: none;
            border-radius: 8px;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .search-filter-bar {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
        }
        
        .filter-group {
            display: flex;
            gap: 1rem;
            align-items: end;
            flex-wrap: wrap;
        }
        
        @media (max-width: 768px) {
            .stats-row {
                grid-template-columns: 1fr;
            }
            
            .filter-group {
                flex-direction: column;
                align-items: stretch;
            }
            
            .action-buttons {
                flex-direction: column;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h2 class="mb-2">Stock Management</h2>
                                <p class="mb-0">Manage inventory levels, track stock movements, and monitor supplies</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addItemModal">
                                    <i class="bi bi-plus-circle me-2"></i>Add New Item
                                </button>
                                <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addStockModal">
                                    <i class="bi bi-box-arrow-in-down me-2"></i>Add Stock
                                </button>
                                <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#removeStockModal">
                                    <i class="bi bi-box-arrow-up me-2"></i>Remove Stock
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="stats-row">
                        <div class="stat-card">
                            <div class="stat-title">Total Items</div>
                            <div class="stat-value"><?php echo number_format($total_items); ?></div>
                            <div class="stat-change" style="color: #059669;">Active inventory items</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Low Stock Alerts</div>
                            <div class="stat-value" style="color: <?php echo $low_stock_items > 0 ? '#dc2626' : '#059669'; ?>;">
                                <?php echo number_format($low_stock_items); ?>
                            </div>
                            <div class="stat-change" style="color: #64748b;">Items need attention</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Inventory Value</div>
                            <div class="stat-value" style="color: #667eea;">KES <?php echo number_format($total_inventory_value); ?></div>
                            <div class="stat-change" style="color: #64748b;">Total stock value</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-title">Categories</div>
                            <div class="stat-value"><?php echo number_format($total_categories); ?></div>
                            <div class="stat-change" style="color: #64748b;">Item categories</div>
                        </div>
                    </div>

                    <!-- Search and Filter -->
                    <div class="search-filter-bar">
                        <div class="filter-group">
                            <div>
                                <label class="form-label">Search Items</label>
                                <input type="text" class="form-control" id="searchInput" placeholder="Search by name or code...">
                            </div>
                            <div>
                                <label class="form-label">Category</label>
                                <select class="form-select" id="categoryFilter">
                                    <option value="">All Categories</option>
                                    <?php
                                    $result_categories->data_seek(0);
                                    while($row = $result_categories->fetch_assoc()): ?>
                                        <option value="<?php echo $row['category_name']; ?>"><?php echo $row['category_name']; ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">Stock Status</label>
                                <select class="form-select" id="statusFilter">
                                    <option value="">All Status</option>
                                    <option value="Normal">Normal</option>
                                    <option value="Low Stock">Low Stock</option>
                                    <option value="Critical">Critical</option>
                                </select>
                            </div>
                            <div>
                                <label class="form-label">&nbsp;</label>
                                <button type="button" class="btn btn-primary d-block" onclick="filterTable()">
                                    <i class="bi bi-search"></i> Filter
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Inventory Table -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Inventory Items</h3>
                            <div>
                                <button type="button" class="btn btn-outline-primary btn-sm" onclick="exportData()">
                                    <i class="bi bi-download me-1"></i>Export
                                </button>
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table" id="inventoryTable">
                                <thead>
                                    <tr>
                                        <th>Item Code</th>
                                        <th>Item Name</th>
                                        <th>Category</th>
                                        <th>Current Stock</th>
                                        <th>Reorder Point</th>
                                        <th>Unit Cost</th>
                                        <th>Total Value</th>
                                        <th>Status</th>
                                        <th>Supplier</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($row = $result_inventory->fetch_assoc()): ?>
                                    <tr>
                                        <td>
                                            <span style="font-weight: 600; color: #667eea;"><?php echo $row['item_code']; ?></span>
                                        </td>
                                        <td>
                                            <div style="font-weight: 600;"><?php echo $row['item_name']; ?></div>
                                            <small style="color: #64748b;">Unit: <?php echo $row['unit']; ?></small>
                                        </td>
                                        <td>
                                            <span class="status-badge status-normal"><?php echo $row['category_name'] ?: 'Uncategorized'; ?></span>
                                        </td>
                                        <td>
                                            <span style="font-weight: 600; font-size: 1.1rem;">
                                                <?php echo number_format($row['current_stock'], 2); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php echo number_format($row['reorder_point'], 2); ?>
                                        </td>
                                        <td style="font-weight: 600;">
                                            KES <?php echo number_format($row['unit_cost'], 2); ?>
                                        </td>
                                        <td style="font-weight: 600; color: #059669;">
                                            KES <?php echo number_format($row['current_stock'] * $row['unit_cost'], 2); ?>
                                        </td>
                                        <td>
                                            <?php 
                                            $status_class = match($row['stock_status']) {
                                                'Normal' => 'status-normal',
                                                'Low Stock' => 'status-low',
                                                'Critical' => 'status-critical',
                                                default => 'status-normal'
                                            };
                                            ?>
                                            <span class="status-badge <?php echo $status_class; ?>">
                                                <?php echo $row['stock_status']; ?>
                                            </span>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo $row['supplier_name'] ?: 'No supplier'; ?>
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button class="action-btn btn btn-sm btn-primary" onclick="viewItem(<?php echo $row['item_id']; ?>)">
                                                    <i class="bi bi-eye"></i>
                                                </button>
                                                <button class="action-btn btn btn-sm btn-success" onclick="addStock(<?php echo $row['item_id']; ?>, '<?php echo addslashes($row['item_name']); ?>')">
                                                    <i class="bi bi-plus"></i>
                                                </button>
                                                <button class="action-btn btn btn-sm btn-warning" onclick="removeStock(<?php echo $row['item_id']; ?>, '<?php echo addslashes($row['item_name']); ?>')">
                                                    <i class="bi bi-dash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Recent Stock Movements -->
                    <div class="table-card">
                        <div class="table-header">
                            <h3 class="table-title">Recent Stock Movements</h3>
                            <a href="stock_movements.php" class="btn btn-outline-primary btn-sm">View All</a>
                        </div>
                        <div class="table-responsive">
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Item</th>
                                        <th>Movement Type</th>
                                        <th>Quantity</th>
                                        <th>Unit Cost</th>
                                        <th>Total Value</th>
                                        <th>Balance After</th>
                                        <th>Moved By</th>
                                        <th>Notes</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($row = $result_movements->fetch_assoc()): ?>
                                    <tr>
                                        <td style="color: #64748b;">
                                            <?php echo date('M j, Y g:i A', strtotime($row['movement_date'])); ?>
                                        </td>
                                        <td>
                                            <div style="font-weight: 600;"><?php echo $row['item_name']; ?></div>
                                            <small style="color: #64748b;"><?php echo $row['item_code']; ?></small>
                                        </td>
                                        <td>
                                            <?php 
                                            $movement_class = match($row['movement_type']) {
                                                'IN' => 'status-in',
                                                'OUT' => 'status-out',
                                                'ADJUSTMENT' => 'status-adjustment',
                                                'WASTE' => 'status-waste',
                                                default => 'status-normal'
                                            };
                                            ?>
                                            <span class="status-badge <?php echo $movement_class; ?>">
                                                <?php echo $row['movement_type']; ?>
                                            </span>
                                        </td>
                                        <td style="font-weight: 600;">
                                            <?php echo number_format($row['quantity'], 2); ?>
                                        </td>
                                        <td>
                                            <?php if($row['unit_cost']): ?>
                                                KES <?php echo number_format($row['unit_cost'], 2); ?>
                                            <?php else: ?>
                                                <span style="color: #64748b;">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="font-weight: 600;">
                                            <?php if($row['total_value']): ?>
                                                KES <?php echo number_format($row['total_value'], 2); ?>
                                            <?php else: ?>
                                                <span style="color: #64748b;">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="font-weight: 600; color: #059669;">
                                            <?php echo number_format($row['balance_after'], 2); ?>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo $row['moved_by_name']; ?>
                                        </td>
                                        <td style="color: #64748b;">
                                            <?php echo $row['notes'] ?: '-'; ?>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <!-- Add Stock Modal -->
    <div class="modal fade" id="addStockModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add Stock</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="addStockForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Select Item</label>
                            <select class="form-select" name="item_id" required>
                                <option value="">Choose item...</option>
                                <?php
                                $result_inventory->data_seek(0);
                                while($row = $result_inventory->fetch_assoc()): ?>
                                    <option value="<?php echo $row['item_id']; ?>">
                                        <?php echo $row['item_name'] . ' (' . $row['item_code'] . ')'; ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Unit Cost (KES)</label>
                                    <input type="number" class="form-control" name="unit_cost" step="0.01" required>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Reference Type</label>
                            <select class="form-select" name="reference_type">
                                <option value="MANUAL">Manual Entry</option>
                                <option value="PURCHASE">Purchase Order</option>
                                <option value="RETURN">Return</option>
                                <option value="TRANSFER">Transfer In</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Optional notes..."></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-success">Add Stock</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Remove Stock Modal -->
    <div class="modal fade" id="removeStockModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Remove Stock</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="removeStockForm">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Select Item</label>
                            <select class="form-select" name="item_id" required>
                                <option value="">Choose item...</option>
                                <?php
                                $result_inventory->data_seek(0);
                                while($row = $result_inventory->fetch_assoc()): ?>
                                    <option value="<?php echo $row['item_id']; ?>" data-stock="<?php echo $row['current_stock']; ?>">
                                        <?php echo $row['item_name'] . ' (' . $row['item_code'] . ') - Stock: ' . number_format($row['current_stock'], 2); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Quantity to Remove</label>
                                    <input type="number" class="form-control" name="quantity" step="0.01" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Reason</label>
                                    <select class="form-select" name="reason">
                                        <option value="OUT">Stock Out</option>
                                        <option value="WASTE">Waste/Damage</option>
                                        <option value="ADJUSTMENT">Adjustment</option>
                                        <option value="RETURN">Return to Supplier</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3" placeholder="Reason for removal..." required></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-warning">Remove Stock</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Alert Container -->
    <div id="alertContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
    // Form submission handlers
    document.getElementById('addStockForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'add_stock');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('addStockModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while adding stock');
        });
    });

    document.getElementById('removeStockForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        formData.append('action', 'remove_stock');
        
        fetch('', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showAlert('success', data.message);
                bootstrap.Modal.getInstance(document.getElementById('removeStockModal')).hide();
                setTimeout(() => window.location.reload(), 1000);
            } else {
                showAlert('error', data.message);
            }
        })
        .catch(error => {
            showAlert('error', 'An error occurred while removing stock');
        });
    });

    // Utility functions
    function showAlert(type, message) {
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertHtml = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        `;
        document.getElementById('alertContainer').innerHTML = alertHtml;
        
        setTimeout(() => {
            const alert = document.querySelector('#alertContainer .alert');
            if (alert) {
                bootstrap.Alert.getInstance(alert).close();
            }
        }, 5000);
    }

    function filterTable() {
        const searchTerm = document.getElementById('searchInput').value.toLowerCase();
        const categoryFilter = document.getElementById('categoryFilter').value;
        const statusFilter = document.getElementById('statusFilter').value;
        const table = document.getElementById('inventoryTable');
        const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

        for (let i = 0; i < rows.length; i++) {
            let show = true;
            const row = rows[i];
            const cells = row.getElementsByTagName('td');
            
            // Search filter
            if (searchTerm) {
                const itemCode = cells[0].textContent.toLowerCase();
                const itemName = cells[1].textContent.toLowerCase();
                if (!itemCode.includes(searchTerm) && !itemName.includes(searchTerm)) {
                    show = false;
                }
            }
            
            // Category filter
            if (categoryFilter && show) {
                const category = cells[2].textContent.trim();
                if (category !== categoryFilter) {
                    show = false;
                }
            }
            
            // Status filter
            if (statusFilter && show) {
                const status = cells[7].textContent.trim();
                if (status !== statusFilter) {
                    show = false;
                }
            }
            
            row.style.display = show ? '' : 'none';
        }
    }

    function addStock(itemId, itemName) {
        const modal = new bootstrap.Modal(document.getElementById('addStockModal'));
        const select = document.querySelector('#addStockModal select[name="item_id"]');
        select.value = itemId;
        modal.show();
    }

    function removeStock(itemId, itemName) {
        const modal = new bootstrap.Modal(document.getElementById('removeStockModal'));
        const select = document.querySelector('#removeStockModal select[name="item_id"]');
        select.value = itemId;
        modal.show();
    }

    function viewItem(itemId) {
        // Redirect to item details page
        window.location.href = `view_inventory_item.php?id=${itemId}`;
    }

    function exportData() {
        // Simple CSV export
        const table = document.getElementById('inventoryTable');
        const rows = table.querySelectorAll('tr');
        let csv = [];
        
        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];
            const cols = row.querySelectorAll('td, th');
            let csvRow = [];
            
            for (let j = 0; j < cols.length - 1; j++) { // Exclude actions column
                csvRow.push('"' + cols[j].textContent.trim().replace(/"/g, '""') + '"');
            }
            csv.push(csvRow.join(','));
        }
        
        const csvContent = csv.join('\n');
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'inventory_stock_' + new Date().toISOString().split('T')[0] + '.csv';
        a.click();
        window.URL.revokeObjectURL(url);
    }

    // Real-time search
    document.getElementById('searchInput').addEventListener('input', filterTable);
    document.getElementById('categoryFilter').addEventListener('change', filterTable);
    document.getElementById('statusFilter').addEventListener('change', filterTable);
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>