# Licensing Resources Implementation

## Overview

This document describes the implementation of the Well License and Station License resources in the Sekaya Laravel application, following the same pattern as the Order resource.

## Created Date
October 3, 2025

## Resources Structure

### Licensing Cluster
- **File**: `app/Filament/Clusters/Licensing.php`
- **Purpose**: Groups licensing resources together in the admin panel
- **Navigation**: Icon: `heroicon-o-document-check`, Sort: 3
- **Features**: Uses `HasPageShield` trait for permission management

### WellLicense Resource
- **File**: `app/Filament/Resources/WellLicenseResource.php`
- **Model**: `App\Models\WellLicense`
- **Icon**: `heroicon-o-beaker`
- **Sort Order**: 1 (within Licensing cluster)

#### Form Sections
1. **Basic Information**
   - Association selection
   - Well name
   - Status (LicenseStatus enum)
   - Created by (hidden)

2. **Location Information**
   - State, City, Center dropdowns (cascading)
   - Google Maps integration with auto-location
   - Latitude/Longitude (hidden)

3. **Well Specifications**
   - Well depth (meters)
   - Well diameter (inches)
   - Pump size (HP)
   - Withdrawal amount (m³/day)

4. **Required Documents** (Media Library)
   - Survey plan (multiple files)
   - Well disclosure
   - Water sample analysis (multiple files)
   - Ownership document

#### Table Columns
- ID (badge)
- Well name
- Association name
- Status (badge with enum colors)
- State name
- City name
- Created at

#### Filters
- Status (LicenseStatus enum)
- State (dropdown)

#### Permissions
Standard CRUD permissions plus:
- `approve_to_next_stage`
- `send_back_to_previous_stage`
- `reject`

### StationLicense Resource
- **File**: `app/Filament/Resources/StationLicenseResource.php`
- **Model**: `App\Models\StationLicense`
- **Icon**: `heroicon-o-building-office`
- **Sort Order**: 2 (within Licensing cluster)

#### Form Sections
1. **Basic Information**
   - Association selection
   - Station name
   - Status (LicenseStatus enum)
   - Created by (hidden)

2. **Location Information**
   - Google Maps integration
   - Latitude/Longitude (hidden)

3. **Station Specifications**
   - Site area (m²)
   - Design capacity (m³/day)
   - Operation start date

4. **Environmental Compliance**
   - Has environmental permit (toggle)
   - Has evaporation ponds (toggle)
   - Evaporation ponds area (conditional field, shown only if has_evaporation_ponds is true)

5. **Required Documents** (Media Library)
   - Survey plan (multiple files)
   - Well water analysis (multiple files)
   - Produced water analysis (multiple files)
   - Reject water analysis (multiple files)
   - Station photos (multiple images)
   - Environmental permit (conditional, required if has_environmental_permit is true)

#### Table Columns
- ID (badge)
- Station name
- Association name
- Status (badge with enum colors)
- Has environmental permit (icon)
- Operation start date
- Created at

#### Filters
- Status (LicenseStatus enum)
- Has environmental permit (ternary)

#### Permissions
Same as WellLicense

## Pages Structure

### WellLicense Pages
Located in: `app/Filament/Resources/WellLicenseResource/Pages/`

1. **ListWellLicenses.php**
   - Uses `AdvancedTables` trait
   - Tabs for each status: All, Created, Initial Approved, Approved, Rejected
   - Each tab shows badge count

2. **CreateWellLicense.php**
   - Simple create form
   - Custom title from translation

3. **EditWellLicense.php**
   - Standard edit with View and Delete actions

4. **ViewWellLicense.php**
   - Split layout with two columns
   - Approval workflow actions (Approve, Send Back, Reject)
   - Permission-based action visibility
   - Shows all well details, specifications, location, documents
   - Links to association resource
   - Displays uploaded files with temporary URLs

### StationLicense Pages
Located in: `app/Filament/Resources/StationLicenseResource/Pages/`

1. **ListStationLicenses.php**
   - Same structure as WellLicense list
   - Status-based tabs with counts

2. **CreateStationLicense.php**
   - Simple create form
   - Custom title from translation

3. **EditStationLicense.php**
   - Standard edit with View and Delete actions

4. **ViewStationLicense.php**
   - Split layout with two columns
   - Approval workflow actions (Approve, Send Back, Reject)
   - Permission-based action visibility
   - Shows station details, environmental compliance, documents
   - Links to association resource
   - Displays uploaded files with temporary URLs
   - Conditional display of evaporation ponds area

## Approval Workflow

Both resources implement the same approval workflow pattern:

### Status Flow
1. **CREATED** (gray) → Initial state
2. **INITIAL_APPROVED** (info/blue) → First approval stage
3. **APPROVED** (success/green) → Final approval
4. **REJECTED** (danger/red) → Can be set at any stage

### Approval Actions
Available in ViewWellLicense and ViewStationLicense:

1. **Approve to Next Stage**
   - Icon: `heroicon-o-check-circle`
   - Color: success (green)
   - Optional notes field
   - Permission: `approve_to_next_stage_well_license` / `approve_to_next_stage_station_license`
   - Visible only if `canApproveToNextStage()` returns true

2. **Send Back**
   - Icon: `heroicon-o-arrow-left-circle`
   - Color: warning (yellow)
   - Required notes field
   - Permission: `send_back_to_previous_stage_well_license` / `send_back_to_previous_stage_station_license`
   - Visible only if `canSendBackToPreviousStage()` returns true

3. **Reject**
   - Icon: `heroicon-o-x-circle`
   - Color: danger (red)
   - Required notes field
   - Permission: `reject_well_license` / `reject_station_license`
   - Always visible except on rejected records

All actions use modal confirmations and show success notifications.

## Translations

### Files Created
- `lang/ar/licensing.php` - Licensing cluster labels
- `lang/en/licensing.php` - Licensing cluster labels
- `lang/ar/well_license.php` - Well license translations
- `lang/en/well_license.php` - Well license translations
- `lang/ar/station_license.php` - Station license translations
- `lang/en/station_license.php` - Station license translations

### Translation Keys
Each resource has translations for:
- Resource labels (singular/plural)
- All form field labels and helpers
- Section headings
- File upload labels
- Status tab labels
- Messages (no files uploaded, etc.)
- Approval action labels and confirmations

## Features Implemented

### From Order Resource Pattern
✅ Shield permissions integration (`HasShieldPermissions`)
✅ Custom permission prefixes including approval actions
✅ Sectioned forms with helper methods
✅ Google Maps integration with auto-location
✅ Cascading location dropdowns (State → City → Center)
✅ Spatie Media Library for file uploads
✅ Custom model labels using translations
✅ Status-based tabs with badge counts
✅ Split-column view layout
✅ Approval workflow actions with modals
✅ Permission-based action visibility
✅ Activity logging for approval actions
✅ Association relationship display with links
✅ Temporary URLs for file downloads
✅ Advanced tables trait

### Additional Features
✅ Conditional fields (evaporation ponds area, environmental permit)
✅ Toggle fields for boolean values
✅ Multiple file uploads per field
✅ Enum-based status management with colors and labels
✅ Location coordinates display

## Files Created

### Cluster
- `app/Filament/Clusters/Licensing.php`

### Resources
- `app/Filament/Resources/WellLicenseResource.php`
- `app/Filament/Resources/StationLicenseResource.php`

### Pages (WellLicense)
- `app/Filament/Resources/WellLicenseResource/Pages/ListWellLicenses.php`
- `app/Filament/Resources/WellLicenseResource/Pages/CreateWellLicense.php`
- `app/Filament/Resources/WellLicenseResource/Pages/EditWellLicense.php`
- `app/Filament/Resources/WellLicenseResource/Pages/ViewWellLicense.php`

### Pages (StationLicense)
- `app/Filament/Resources/StationLicenseResource/Pages/ListStationLicenses.php`
- `app/Filament/Resources/StationLicenseResource/Pages/CreateStationLicense.php`
- `app/Filament/Resources/StationLicenseResource/Pages/EditStationLicense.php`
- `app/Filament/Resources/StationLicenseResource/Pages/ViewStationLicense.php`

### Translations
- `lang/ar/licensing.php`
- `lang/en/licensing.php`
- `lang/ar/well_license.php`
- `lang/en/well_license.php`
- `lang/ar/station_license.php`
- `lang/en/station_license.php`

## Next Steps

### Required for Full Functionality
1. **Policies**: Create `WellLicensePolicy` and `StationLicensePolicy`
2. **Shield Permissions**: Run `php artisan shield:generate` to create permission records
3. **Tests**: Create feature tests for both resources
4. **Factories**: Create factories for testing (optional)
5. **Seeders**: Create seeders for demo data (optional)

### Recommended
- Add exporters for both resources (similar to OrderExporter)
- Add widgets for license statistics
- Add relation managers if needed
- Add bulk actions for status changes
- Add filters for date ranges and associations

## Usage

### Accessing Resources
Navigate to the admin panel:
- Resources are grouped under "Licensing" cluster
- Well Licenses: `/admin/licensing/well-licenses`
- Station Licenses: `/admin/licensing/station-licenses`

### Creating a License
1. Click "Create" button on list page
2. Fill in required fields in each section
3. Upload required documents
4. Submit form (status defaults to CREATED)

### Approving a License
1. View the license details
2. Click "Approve to Next Stage" button
3. Optionally add notes
4. Confirm action
5. Status progresses to next stage

### Rejecting a License
1. View the license details
2. Click "Reject License" button
3. Add required rejection notes
4. Confirm action
5. Status changes to REJECTED

## Integration Points

### Models
- Uses `WellLicense` and `StationLicense` models with approval methods
- Leverages `LicenseStatus` enum for status management
- Integrates with `Association`, `State`, `City`, `Center` models

### Services
- Uses `LocationCoordinatesService` for auto-location on city selection

### Media Library
- Multiple collections per resource
- Private visibility for all documents
- Temporary URLs for secure downloads

### Activity Log
- All approval actions logged with Spatie Activity Log
- Notes stored as activity properties
- Causer tracked automatically

## Differences from Order Resource

1. **Simpler Workflow**: Licenses have 3 approval stages vs Order's 10+
2. **No Finance/Agreement**: Licenses don't have finance or agreement sections
3. **Enum-Based Status**: Uses `LicenseStatus` enum instead of constants
4. **Conditional Fields**: StationLicense has conditional environmental fields
5. **No Requirements**: Licenses don't have separate requirement relations
6. **Cluster Organization**: Grouped in Licensing cluster vs standalone
7. **Simpler Permissions**: Fewer permission types needed
8. **No Type Variations**: Each license has fixed structure (no type-based field variations)

## Maintenance Notes

- Follow existing Order resource patterns when adding new features
- Always add translations for new fields
- Use enum methods for status colors and labels
- Maintain permission checks on all actions
- Keep approval workflow methods in model, not resource
- Use activity logging for all status changes
- Follow Filament v3 conventions for components
