# EmployeePage

**Namespace:** `FrymasterBadgeApp`  
**Base Class:** `ContentPage`  
**Purpose:** Primary employee management interface. Handles list filtering, dynamic badge preview generation, photo editing, database CRUD operations, and badge printing.

## 🔑 Fields & Collections
| Name | Type | Access | Description |
|------|------|--------|-------------|
| `_db` | `SqlService` | `private readonly` | Database access service. |
| `_printerService` | `PrinterService` | `private readonly` | Printing service. |
| `_selectedEmployee` | `Dictionary<string, object>?` | `private` | Currently selected employee record. |
| `_currentCompany` | `Dictionary<string, object>` | `private readonly` | Company context passed via DI. |
| `_allEmployees` | `ObservableCollection<Dictionary<string, object>>` | `private` | Master list of employees. |
| `_filteredEmployees` | `ObservableCollection<Dictionary<string, object>>` | `private` | Filtered view for UI binding. |
| `_photosBasePath`, `_logosBasePath`, `_imagesBasePath` | `string` | `private readonly` | Storage paths from Preferences. |
| `_currentBadgeType` | `string` | `private` | Tracks active badge style (`OFFICE`, `GUEST`, `PLANT`, etc.) |
| `_showActiveOnly` | `bool` | `private` | Active-only filter state. |

## 🛠 Constructor
### `EmployeePage(SqlService db, PrinterService printerService, Dictionary<string, object> company)`
- **Access:** `public`
- **Behavior:** Initializes UI, resolves XAML controls via `FindByName`, sets up event handlers (`ActiveFilter`, `Search`, `Guest/Badge Pickers`), ensures directories exist, loads company logo, fetches employees, and displays placeholder message.

## 📦 Methods

### UI & State Management
| Method | Access | Behavior |
|--------|--------|----------|
| `ShowNoSelectionMessage()` | `private` | Renders placeholder `VerticalStackLayout` in `PreviewFrame`. |
| `ResetPageToDefault()` | `private` | Clears selection, search text, filtered list, and resets preview. Prevents filter triggers during reset. |
| `OnAppearing()` | `protected override async void` | Resets UI, loads printers, and refreshes employee data. |
| `LoadCompanyLogo()` | `private` | Resolves logo path via `GetCompanyLogoPath()`. |
| `GetCompanyLogoPath()` | `private` | Combines `_logosBasePath` with DB filename. Validates existence, logs warnings. |

### Data Loading & Filtering
| Method | Access | Behavior |
|--------|--------|----------|
| `LoadEmployeesAsync()` | `private async Task` | Runs DB query on background thread. Marshals to main thread to populate `_allEmployees` and trigger filters. |
| `LoadEmployees()` | `private` | Synchronous variant (legacy). |
| `ApplyFilters()` | `private` | Filters `_allEmployees` by `_showActiveOnly` and search bar text. Updates `_filteredEmployees` on main thread. |
| `OnSearchTextChanged()` | `private` | Positions dropdown, shows list, triggers filters. |
| `PositionSearchResultsDropdown()` | `private` | Sets `TranslationY` and `ZIndex` for search results list. |

### Employee Selection & Navigation
| Method | Access | Behavior |
|--------|--------|----------|
| `OnEmployeeSelected()` | `private` | Updates search bar, resolves badge type (case-insensitive), toggles guest selector, renders preview. |
| `SelectAndShowEmployee(Dictionary)` | `private` | Helper to find record in collection, update UI, and scroll `ListView` to item. |
| `OnAddEmployeeClicked()` | `private async void` | Opens `EmployeeFormPage` modally. Sets callback to reload list and auto-select new record. |
| `OnEditEmployeeClicked()` | `private async void` | Opens form in edit mode. Refreshes data and preview if `IsSaved` is true. |

### Badge Rendering & Photo Editing
| Method | Access | Behavior |
|--------|--------|----------|
| `RenderBadgePreview(Dictionary)` | `private` | **Core method.** Dynamically builds front/back badge UI based on `_currentBadgeType`. Handles company logo, employee photo, barcode, medical indicators, and company details. |
| `AddStandardFront()` | `private` | UI builder for badge front (logo, photo container, name, barcode, medical icons). |
| `AddStandardBackDetails()` | `private` | UI builder for badge back (property text, address, ID, issue date, medical icons). |
| `OnTakePhotoClicked()` | `private async void` | Captures photo, saves to cache, resets editor transforms, shows overlay. |
| `OnPanUpdated()` | `private` | Updates photo `TranslationX/Y` during pan. Commits offsets on completion. |
| `OnApplyPhoto()` | `private async void` | Copies temp photo to `_photosBasePath`, updates DB (`picCode`, `cropScale`, `cropX`, `cropY`), refreshes preview. |
| `OnCancelPhoto()` | `private` | Hides photo editor overlay. |
| `InitialiseDefaultImages()` | `private async Task` | Deploys `Guest.png`/`WelBilt.png` from `Resources/Raw` to images directory if missing. |

### Utilities & Printing
| Method | Access | Behavior |
|--------|--------|----------|
| `SafeToDouble(object?, double)` | `private` | Safe parsing helper. Returns `defaultValue` on null/parse failure. |
| `OnBadgeTypeChanged()` | `private` | Updates `_currentBadgeType`, saves to DB, refreshes preview. |
| `OnGuestImageChanged()` | `private` | Updates `_currentGuestImage`, refreshes preview if type is `GUEST`. |
| `LoadAvailablePrinters()` | `private` | Populates `PrinterPicker` from `PrinterSettings.InstalledPrinters`. |
| `OnRefreshPrintersClicked()` | `private` | Reloads printer list. |
| `OnPrintClicked()` | `private async void` | Validates selection/printer. Captures front/back views via `CaptureAsync()`, converts to Base64, sends to `_printerService`. |
| `StreamToBase64(IScreenshotResult)` | `private async Task` | Converts screenshot stream to Base64 string for printing. |

---
**💡 Architectural Notes:**
- **Dynamic UI Generation:** Badge preview is built entirely in C# (`HorizontalStackLayout`, `Frame`, `Grid`). This allows precise control over print dimensions but increases memory overhead.
- **Threading:** DB queries run on `Task.Run` or background threads. All UI updates use `MainThread.BeginInvokeOnMainThread` or `InvokeOnMainThreadAsync`.
- **Null Safety:** Heavy use of `?.` and `FindByName` checks indicates defensive coding against missing XAML `x:Name` mappings.
- **Printing Flow:** Uses `CommunityToolkit.Maui` screenshot API to capture rendered UI, bypassing native printing drivers for pixel-perfect badge output.