# Dental Orders Management System

This document describes the comprehensive dental orders listing functionality with advanced filtering, pagination, and sorting capabilities.

## Overview

The orders section now displays a comprehensive table of dental orders with the following advanced features:

- **Sticky Table Header**: The table header remains visible when scrolling
- **Responsive Design**: Works on all screen sizes with horizontal scrolling on mobile
- **Real-time Loading**: Orders are loaded automatically when the page loads
- **Modern UI/UX**: Beautiful styling with hover effects and animations
- **Advanced Filtering**: Multiple filter types with real-time AJAX updates
- **Infinite Scroll Pagination**: Loads 15 items initially, then 15 more on scroll
- **Sortable Columns**: Clickable headers for sorting by ID, service type, and date
- **Active Filters Display**: Visual representation of applied filters with easy removal

## Features

### Table Columns

1. **Order ID** - Unique dental order identifier (e.g., d-1001) - **Sortable**
2. **Author Name** - Full name of the user who created the order
3. **Patient Name** - Name of the patient
4. **Service Type** - Main service + sub-services in one column - **Sortable**
5. **Date** - Order creation date in YYYY/MM/DD format (e.g., 2025/01/15) - **Sortable**
6. **Status** - Current order status with color-coded badges

### Advanced Filter System

#### 1. Search Filter
- **AJAX Search**: Real-time search with 500ms debouncing
- **Minimum Length**: Requires at least 3 characters
- **Search Scope**: Searches in author name, dental_id, and patient_name
- **Smart Debouncing**: Prevents excessive API calls while typing

#### 2. Service Type Filter
- **Checkbox Selection**: Multiple service types can be selected
- **Available Options**:
  - ارتودنسی (Orthodontics)
  - پروتز ثابت (Fixed Prosthesis)
  - پروتز متحرک (Removable Prosthesis)
- **Real-time Updates**: Results update immediately on selection

#### 3. Date Filter
- **Placeholder**: Ready for future custom datepicker integration
- **Future Features**: Date range selection (from/to dates)

#### 4. Status Filter
- **Dropdown Selection**: Single status selection
- **Available Statuses**:
  - همه وضعیت‌ها (All Statuses)
  - در انتظار (Pending)
  - در حال انجام (In Progress)
  - تکمیل شده (Completed)
  - لغو شده (Cancelled)

### Active Filters Display

- **Visual Tags**: Shows active filters as removable tags above the table
- **Filter Information**: Displays filter type and current value
- **Easy Removal**: Click the × button to remove individual filters
- **Dynamic Visibility**: Only shows when filters are active
- **Smart Formatting**: Proper Persian text for filter labels and values

### Sorting System

- **Clickable Headers**: Order ID, Service Type, and Date columns are sortable
- **Visual Indicators**: Arrow icons show current sort direction
- **Toggle Behavior**: Click same column to reverse sort order
- **Default Sorting**: Orders by creation date (newest first)

### Pagination & Performance

- **Initial Load**: Shows first 15 orders
- **Infinite Scroll**: Automatically loads 15 more orders when scrolling to bottom
- **Smart Loading**: Prevents duplicate requests and handles loading states
- **Memory Efficient**: Maintains order list without excessive memory usage

## Technical Implementation

### Files Created/Modified

1. **`inc/dental.php`** - Enhanced PHP functions for filtering, pagination, and sorting
2. **`css/orders.css`** - Comprehensive styling for filters, active filters, and sortable headers
3. **`js/orders.js`** - Complete rewrite with advanced filtering and pagination logic
4. **`templates/dashboard-p.php`** - Updated dashboard template with filter controls

### Security Features

- **User Isolation**: Orders are filtered by `author_id` to ensure users can only see their own orders
- **Authentication Required**: Only logged-in users can access the orders endpoint
- **Nonce Verification**: All AJAX requests are protected with WordPress nonces
- **Input Validation**: All filter parameters are validated and sanitized
- **SQL Injection Prevention**: Uses prepared statements for all database queries

### PHP Functions Enhanced

- `get_user_dental_orders()` - Now supports filtering, pagination, and sorting
- `handle_get_user_dental_orders()` - Enhanced AJAX handler with comprehensive parameters
- **New Features**:
  - Search functionality with LIKE queries
  - Service type filtering with IN clauses
  - Status filtering
  - Date range filtering (placeholder)
  - Dynamic sorting with validation
  - Pagination with offset/limit

### JavaScript Class - Complete Rewrite

- **OrdersManager** - Advanced class with comprehensive functionality
- **Filter Management**: Real-time filter updates with debouncing
- **Pagination**: Infinite scroll with smart loading
- **Sorting**: Dynamic column sorting with visual indicators
- **Active Filters**: Visual representation and management
- **Performance**: Efficient state management and API calls

## Usage

### For Users

1. **Navigate** to the "سفارشات" (Orders) tab in the dashboard
2. **Use Filters**: 
   - Type in search box (minimum 3 characters)
   - Check/uncheck service types
   - Select status from dropdown
   - Date filter coming soon
3. **Sort Results**: Click on Order ID, Service Type, or Date column headers
4. **View Active Filters**: See applied filters as tags above the table
5. **Remove Filters**: Click × on filter tags or use "پاک کردن فیلترها" button
6. **Load More**: Scroll down to automatically load more orders

### For Developers

The system is designed to be easily extensible:

```javascript
// Access the orders manager globally
window.ordersManager

// Get current filter state
const filters = ordersManager.currentFilters

// Get current sort state
const sorting = ordersManager.currentSort

// Manually trigger filter update
ordersManager.loadOrders(true)

// Add new filter types
// Extend the currentFilters object and updateActiveFilters method
```

## Database Requirements

The system expects a `dentals` table with the following structure:

- `id` - Auto increment primary key
- `dental_id` - Unique order identifier (e.g., d-1001)
- `author_id` - User ID who created the order
- `author_info` - JSON string with user information
- `patient_name` - Patient name
- `service_type` - Main service type
- `sub_services` - JSON string with sub-services
- `dental_status` - Order status
- `created_at` - Creation timestamp

## Styling Features

- **Gradient Header**: Beautiful gradient background for table header
- **Hover Effects**: Subtle animations on table rows and filter elements
- **Responsive Design**: Mobile-friendly with horizontal scrolling
- **Color-coded Badges**: Easy identification of status
- **Smooth Animations**: Fade-in effects for table rows and filter transitions
- **Custom Scrollbars**: Styled scrollbars for better UX
- **Filter Controls**: Modern form controls with focus states
- **Active Filter Tags**: Beautiful tag design with hover effects
- **Sort Indicators**: Visual arrows showing sort direction

## Browser Support

- Modern browsers with ES6+ support
- CSS Grid and Flexbox support
- CSS Custom Properties support
- Backdrop-filter support (with fallback)
- Intersection Observer API (for infinite scroll)

## Performance Features

- **Debounced Search**: 500ms delay prevents excessive API calls
- **Smart Pagination**: Only loads data when needed
- **Efficient DOM Updates**: Minimal DOM manipulation
- **Memory Management**: Proper cleanup of event listeners
- **Loading States**: Visual feedback during API calls

## Future Enhancements

- **Date Picker Integration**: Custom date range selection
- **Advanced Search**: Full-text search capabilities
- **Export Functionality**: CSV/Excel export of filtered results
- **Saved Filters**: User preference storage for common filter combinations
- **Real-time Updates**: WebSocket integration for live order updates
- **Bulk Actions**: Select multiple orders for batch operations
- **Advanced Analytics**: Filter result statistics and insights

## Troubleshooting

### Common Issues

1. **Orders not loading**: Check browser console for JavaScript errors
2. **Filters not working**: Verify AJAX endpoint and nonce validity
3. **Sorting issues**: Check column data-sort attributes in HTML
4. **Infinite scroll not working**: Ensure proper scroll event handling
5. **Styling issues**: Ensure CSS file is properly enqueued

### Debug Mode

Enable debug mode in WordPress to see detailed error messages:

```php
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', true);
```

### Console Logging

The system includes comprehensive console logging for debugging:

```javascript
// Check filter state
console.log(ordersManager.currentFilters)

// Check sort state
console.log(ordersManager.currentSort)

// Check pagination state
console.log(ordersManager.currentPage, ordersManager.hasMore)
```

## Support

For technical support or feature requests, please contact the development team.

## Changelog

### Version 2.0 (Current)
- Complete filter system rewrite
- Infinite scroll pagination
- Sortable table columns
- Active filters display
- Real-time AJAX updates
- Performance optimizations

### Version 1.0 (Previous)
- Basic orders listing
- Simple table display
- Basic styling
- Manual refresh functionality
