# Select2 Dropdown Component Guide

This project now uses a standardized, searchable Select2 dropdown component throughout the application. This component provides a consistent user experience with enhanced search functionality across all forms and filters.

## Component Location
```
resources/views/components/warehouse/select2-dropdown.blade.php
```

## Basic Usage

### Simple Dropdown
```blade
<x-warehouse.select2-dropdown
    name="status"
    id="status"
    label="Status"
    placeholder="Select Status"
    :options="[
        ['value' => 'active', 'text' => 'Active'],
        ['value' => 'inactive', 'text' => 'Inactive']
    ]"
    required="true"
/>
```

### Dropdown with Database Data
```blade
@php
    $categoryOptions = [['value' => '', 'text' => 'Select Category']];
    foreach($categories as $category) {
        $categoryOptions[] = [
            'value' => $category->id,
            'text' => $category->category_name
        ];
    }
@endphp

<x-warehouse.select2-dropdown
    name="category_id"
    id="category_id"
    label="Category"
    placeholder="Select Category"
    :options="$categoryOptions"
    required="true"
/>
```

## Component Parameters

### Required Parameters
- `name` - The form field name
- `options` - Array of options (see format below)

### Optional Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `id` | string | `$name` | HTML id attribute |
| `label` | string | `''` | Display label above dropdown |
| `required` | boolean | `false` | Makes field required |
| `placeholder` | string | `'Please select...'` | Placeholder text |
| `selected` | string/int | `null` | Pre-selected value |
| `allowClear` | boolean | `true` | Shows clear button |
| `multiple` | boolean | `false` | Enables multiple selection |
| `disabled` | boolean | `false` | Disables the dropdown |
| `help` | string | `''` | Help text below dropdown |
| `errorField` | string | `$name` | Laravel validation error field |
| `class` | string | `''` | Additional CSS classes |
| `data` | array | `[]` | Additional data attributes |
| `theme` | string | `'default'` | Select2 theme |

## Options Format

### Simple Options Array
```php
[
    ['value' => 'option1', 'text' => 'Option 1'],
    ['value' => 'option2', 'text' => 'Option 2'],
]
```

### Options with Data Attributes
```php
[
    [
        'value' => 'AED',
        'text' => 'AED',
        'data' => ['rate' => 1.0000]
    ],
    [
        'value' => 'USD',
        'text' => 'USD (3.6725 د.إ)',
        'data' => ['rate' => 3.6725]
    ]
]
```

### Eloquent Collection Options
```php
// For simple collections
:options="$projects"  // Uses id and name properties

// For custom mapping
@php
    $projectOptions = $projects->map(function($project) {
        return [
            'value' => $project->id,
            'text' => $project->project_name
        ];
    })->toArray();
@endphp
:options="$projectOptions"
```

## Advanced Examples

### Dropdown with Event Handler
```blade
<x-warehouse.select2-dropdown
    name="currency"
    id="currency"
    label="Currency"
    :options="$currencyOptions"
    :data="['onchange' => 'updateExchangeRate()']"
/>
```

### Multiple Selection
```blade
<x-warehouse.select2-dropdown
    name="categories[]"
    id="categories"
    label="Categories"
    :options="$categoryOptions"
    multiple="true"
/>
```

### Filter Dropdown (Small Size)
```blade
<div class="col-md-3">
    <div style="font-size: 12px; margin-bottom: 8px;">
        <x-warehouse.select2-dropdown
            name="filter-status"
            id="filter-status"
            label="Status"
            placeholder="All Statuses"
            :options="$statusOptions"
            class="form-control-sm"
        />
    </div>
</div>
```

### Cascading Dropdowns (Project → Material Requests)
```blade
<!-- Project Dropdown -->
<x-warehouse.select2-dropdown
    name="project_id_select"
    id="project_id_select"
    label="Project"
    placeholder="Select Project First"
    :options="$projectOptions"
    required="true"
/>

<!-- Material Request Dropdown (populated via AJAX) -->
<x-warehouse.select2-dropdown
    name="material_request_id"
    id="material_request_id"
    label="Material Request"
    placeholder="Select Project First"
    :options="[]"
    disabled="true"
    required="true"
/>

<script>
$('#project_id_select').change(function() {
    const projectId = $(this).val();
    if (projectId) {
        // AJAX call to load material requests
        loadMaterialRequestsForProject(projectId);
    }
});
</script>
```

## Styling and Themes

The component includes comprehensive CSS styling:
- Bootstrap 5 compatibility
- Consistent height (38px for single, min 38px for multiple)
- Error state styling
- Disabled state styling
- Responsive design

### Custom Styling
```blade
<x-warehouse.select2-dropdown
    class="custom-dropdown"
    :options="$options"
    theme="bootstrap-5"
/>
```

## JavaScript Integration

The component automatically:
- Initializes Select2 with proper settings
- Handles multiple selection events
- Provides search functionality
- Manages placeholder text
- Supports custom event handlers

### Manual JavaScript Access
```javascript
// Access the Select2 instance
$('#dropdown-id').select2('val', 'new-value');

// Listen for changes
$('#dropdown-id').on('select2:select', function(e) {
    console.log('Selected:', e.params.data);
});
```

## Migration Guide

### Old Format
```blade
<select name="category_id" class="form-control">
    <option value="">Select Category</option>
    @foreach($categories as $category)
        <option value="{{ $category->id }}">{{ $category->name }}</option>
    @endforeach
</select>
```

### New Format
```blade
@php
    $options = [['value' => '', 'text' => 'Select Category']];
    foreach($categories as $category) {
        $options[] = ['value' => $category->id, 'text' => $category->name];
    }
@endphp

<x-warehouse.select2-dropdown
    name="category_id"
    label="Category"
    :options="$options"
/>
```

## Benefits

1. **Consistent User Experience**: All dropdowns have the same look, feel, and behavior
2. **Enhanced Search**: Users can search within dropdown options
3. **Better Accessibility**: Proper ARIA attributes and keyboard navigation
4. **Responsive Design**: Works well on mobile devices
5. **Easy Maintenance**: Centralized styling and behavior
6. **Laravel Integration**: Built-in validation error handling
7. **Flexible Configuration**: Supports all common dropdown scenarios

## Implementation Status

✅ **Completed Pages:**
- Warehouse Item Categories (filters + modals)
- Warehouse Items (filters + modals + import)
- Incoming Operations Create (supplier, currency, received_by)
- Site Return Create (project + material request cascading dropdowns)

⏳ **Remaining Pages:**
- Outgoing Transactions Create
- Supplier Delivery
- All other pages with dropdowns (39 files total)

## Best Practices

1. **Always provide placeholder text** that describes what the user should select
2. **Use consistent option formatting** across similar dropdowns
3. **Include empty/default options** for non-required dropdowns
4. **Group related options** logically
5. **Provide helpful labels** that clearly indicate the field purpose
6. **Use appropriate validation** with Laravel error handling
7. **Consider performance** for large option lists (use AJAX for 100+ items)

## Support and Troubleshooting

### Common Issues
1. **Options not showing**: Check the options array format
2. **Select2 not initializing**: Ensure component is properly included
3. **Styling issues**: Check for CSS conflicts with existing styles
4. **Validation errors**: Verify errorField parameter matches form field name

### Debug Mode
Add this to see component data:
```blade
<x-warehouse.select2-dropdown
    name="test"
    :options="$options"
    :debug="true"
/>
```

This component significantly improves the user experience across the entire application while maintaining consistency and reducing development time for future forms.