# CompanyPage

**Namespace:** `FrymasterBadgeApp`  
**Base Class:** `ContentPage`  
**Purpose:** CRUD interface for managing company records and uploading/previewing company logos.

## 🔑 Fields
| Name | Type | Access | Description |
|------|------|--------|-------------|
| `_db` | `SqlService` | `private readonly` | Database service. |
| `_selectedCompany` | `Dictionary<string, object>?` | `private` | Currently selected company from the list. |
| `_tempLogoPath` | `string` | `private` | Path to currently selected/cached logo image. |
| `LogoPathKey` | `const string` | `private` | Preference key for logo directory (`"LogoBasePath"`). |

## 🛠 Constructor
### `CompanyPage(SqlService db)`
- **Access:** `public`
- **Behavior:** Configures custom back button behavior, calls `LoadCompanies()`.

## 📦 Methods

### `GetLogoDirectory()`
- **Access:** `private`
- **Returns:** `string`
- **Behavior:** Reads logo directory from Preferences. Defaults to `C:\FrymasterData\logos`.

### `LoadCompanies()`
- **Access:** `private`
- **Behavior:** Executes `SELECT * FROM Companies ORDER BY Name ASC`, binds to `CompanyList`. Catches and alerts on DB failure.

### `OnCompanySelectionChanged(object sender, SelectionChangedEventArgs e)`
- **Access:** `private`
- **Behavior:** Updates form fields and loads logo preview on main thread. Clears fields if selection is null.

### `GetValue(Dictionary<string, object> dict, string key)`
- **Access:** `private`
- **Returns:** `string`
- **Behavior:** Case-insensitive dictionary lookup. Returns trimmed value or empty string if missing.

### `OnSelectLogoClicked(object sender, EventArgs e)`
- **Access:** `private async void`
- **Behavior:** Opens file picker filtering for images. Stores `FullPath` in `_tempLogoPath` and updates preview.

### `OnSaveClicked(object sender, EventArgs e)`
- **Access:** `private async void`
- **Behavior:**
  1. Validates company name.
  2. Ensures logo directory exists (creates if missing).
  3. If logo selected: copies to directory with timestamped name on collision. Stores only filename.
  4. Executes `INSERT` or `UPDATE` via `_db.Execute`.
  5. Refreshes list and clears form.

### `OnAddNewClicked(object sender, EventArgs e)`
- **Access:** `private`
- **Behavior:** Deselects list item and clears form fields.

### `ClearFields()`
- **Access:** `private`
- **Behavior:** Resets `_selectedCompany`, `_tempLogoPath`, all text fields, logo preview, and hides delete button.

### `OnDeleteClicked(object sender, EventArgs e)`
- **Access:** `private async void`
- **Behavior:** Shows confirmation dialog, executes `DELETE FROM Companies WHERE ID=@id`, refreshes list, clears fields. Catches and alerts on error.

---
**Data Flow Notes:**
- Logo paths are stored as filenames only in the database to keep DB portable.
- File operations use `File.Copy` with overwrite protection (`timestamp` suffix).
- All UI updates after async operations are marshaled via `MainThread.BeginInvokeOnMainThread`.