# Stock Report - Excel-like Editable Grid

## Overview
The Stock Report is an interactive, Excel-like grid interface that allows you to view and edit your inventory stock levels in real-time. All changes are automatically saved to the database.

## Features

### 📊 Excel-like Interface
- **Editable Grid**: Click on any highlighted cell to edit values directly in the table
- **Real-time Updates**: Changes are saved immediately to the database via AJAX
- **Visual Feedback**: Color-coded columns show which fields are editable
- **Responsive Design**: Works seamlessly on desktop and mobile devices

### ✏️ Inline Editing
The following columns are editable (highlighted in green):
- **Current Stock**: Update stock quantities
- **Purchase Price**: Modify purchase prices
- **Sales Price**: Update selling prices
- **MRP**: Change maximum retail prices

**How to Edit:**
1. Click on any cell in the editable columns
2. Enter the new value
3. Press Enter or click outside the cell to save
4. Press Escape to cancel editing

### 🔍 Advanced Filtering
Filter your stock report by:
- **Search**: Search by item name, code, SKU, or barcode
- **Category**: Filter by product category
- **Brand**: Filter by brand
- **Location**: Filter by storage location
- **Stock Status**: View items by stock level (Low Stock, Out of Stock, Sufficient Stock)

### 📈 Real-time Calculations
- **Stock Value**: Automatically calculated as (Current Stock × Purchase Price)
- **Total Stock**: Sum of all stock quantities
- **Total Value**: Sum of all stock values
- **Stock Status**: Auto-updated based on alert quantities

### 📤 Export Functionality
- **Export to Excel**: Download the entire report as CSV file
- **Date-stamped**: Exports include the current date in filename
- **Clean Data**: Exported data is formatted for easy Excel import

## File Structure

```
items/
├── stock-report.php           # Main stock report page
├── api/
│   ├── get-stock-report.php   # API to fetch stock data
│   └── update-stock.php       # API to update stock values
├── css/
│   └── stock-report.css       # Excel-like styling
└── js/
    └── stock-report.js        # Interactive editing logic
```

## Database Tables

### Main Table: `tblitems`
Stores all inventory items with stock and pricing information.

### Audit Table: `tblstockaudit` (Optional)
Tracks all changes made through the stock report:
- Item ID
- User ID (who made the change)
- Field name
- Old value
- New value
- Timestamp

**To enable audit logging:**
```sql
-- Run this SQL file to create the audit table
source database/create_stock_audit_table.sql
```

## Installation

1. **Files are already created** in your items folder
2. **Optional**: Run the audit table creation script:
   ```sql
   mysql -u root uzrs-inventorydb < database/create_stock_audit_table.sql
   ```
3. **Access the report**: Navigate to `items/stock-report.php`

## Usage Guide

### Viewing Stock Report
1. Navigate to `items/stock-report.php` in your browser
2. The report loads all active items by default
3. Use filters to narrow down the view

### Editing Stock Values
1. **Click** on any green-highlighted cell
2. **Type** the new value
3. **Press Enter** or click outside to save
4. **Press Escape** to cancel without saving

### Filtering Data
1. Use the filter dropdowns at the top
2. Enter search terms in the search box
3. Click "Clear" to reset all filters
4. Click "Refresh" to reload data

### Exporting Data
1. Click the "Export to Excel" button
2. CSV file will download automatically
3. Open in Excel, Google Sheets, or any spreadsheet software

## Stock Status Indicators

The report automatically categorizes items by stock level:

| Status | Indicator | Condition |
|--------|-----------|-----------|
| **In Stock** | Green badge | Current Stock > Alert Quantity |
| **Low Stock** | Yellow badge | Current Stock ≤ Alert Quantity |
| **Out of Stock** | Red badge | Current Stock = 0 |

## Color Coding

- **Green columns**: Editable fields (Current Stock, Purchase Price, Sales Price, MRP)
- **Blue header**: Regular (non-editable) columns
- **Cyan footer**: Totals and summary information

## Technical Details

### API Endpoints

#### GET `/items/api/get-stock-report.php`
Fetches stock data with optional filters.

**Parameters:**
- `search`: Search term
- `category`: Category ID
- `brand`: Brand ID
- `location`: Location ID
- `stockStatus`: low|out|sufficient

**Response:**
```json
{
  "success": true,
  "items": [...],
  "count": 15,
  "totals": {
    "totalStock": "1250.00",
    "totalValue": "125000.00"
  }
}
```

#### POST `/items/api/update-stock.php`
Updates a single field value for an item.

**Request:**
```json
{
  "itemId": 5,
  "field": "CurrentStock",
  "value": 100.50
}
```

**Response:**
```json
{
  "success": true,
  "message": "Stock updated successfully",
  "data": {
    "itemId": 5,
    "currentStock": "100.50",
    "stockValue": "10050.00",
    "stockStatus": "In Stock"
  }
}
```

### Security Features

1. **Session Validation**: Requires active user session
2. **SQL Injection Prevention**: Uses prepared statements
3. **Field Whitelisting**: Only allowed fields can be updated
4. **Input Validation**: Numeric validation and negative value prevention
5. **Audit Trail**: Optional logging of all changes

### Browser Compatibility

- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+
- Mobile browsers supported

## Troubleshooting

### Issue: Cells not editable
**Solution**: Ensure JavaScript is enabled and check browser console for errors

### Issue: Changes not saving
**Solution**: 
- Check database connection in `includes/config.php`
- Verify user has active session
- Check browser console for AJAX errors

### Issue: Filters not working
**Solution**: Clear browser cache and reload the page

### Issue: Export button not working
**Solution**: Allow pop-ups for the site in browser settings

## Future Enhancements

Potential additions for future versions:
- Bulk edit functionality
- Import from Excel
- Print-friendly view
- Stock movement history
- Low stock alerts email notifications
- Barcode scanning integration
- Advanced analytics and charts

## Support

For issues or questions:
1. Check the browser console for errors
2. Verify database connection
3. Ensure all required files are in place
4. Check user permissions

## Credits

Built for UZRS Inventory Management System
