# Insurance Company Controller Documentation

**File**: `/controllers/insurancecompany.php`  
**Purpose**: Manages insurance company profiles, contracts, and discount agreements for warranty services  
**Last Updated**: December 20, 2024  
**Total Functions**: 4  
**Lines of Code**: ~223

---

## 📋 Overview

The Insurance Company Controller handles the complete lifecycle management of insurance company partnerships. It manages company profiles, contract documents, discount percentages, contract validity periods, and special instructions for warranty processing. This controller supports the warranty management system by maintaining the database of service providers and their contractual terms.

### Primary Functions
- [x] Add new insurance company partnerships with contract details
- [x] Display active and expired insurance companies with status indicators
- [x] Edit insurance company information and contract terms
- [x] Soft delete insurance companies (mark as deleted)
- [x] Upload and manage contract document images
- [x] Track contract validity periods with automatic expiration
- [x] Manage discount percentages for different service types
- [x] Handle special instructions and terms per company

### Related Controllers
- [insuranceGo.php](insuranceGo.md) - Outbound warranty shipments
- [insuranceReturn.php](insuranceReturn.md) - Warranty returns processing
- [shippercompaniesController.php](shippercompaniesController.md) - Shipping companies
- [representativecompanyController.php](#) - Company representatives

---

## 🗄️ Database Tables

### Primary Table (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **insurancecompanies** | Insurance company master data | insurancecompaniesid, name, discountpercent, contractstart, contractend, contractphoto, instruction, userid, deleted |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **user** | User information for audit | userid, username |
| **programsettings** | System configuration | programsettingsid, settingkey, settingvalue |

---

## 🔑 Key Functions

### 1. **Default Action** - Add New Insurance Company
**Location**: Lines 52-58  
**Purpose**: Display form for adding new insurance company partnerships

**Function Signature**:
```php
// Triggered when: empty $do
include_once("../public/authentication.php");
$smarty->display("insuranceview/add.html");
```

**Features**:
- Authentication check required
- File upload capability for contract documents
- Form validation for required fields
- Contract date range selection

---

### 2. **add()** - Create Insurance Company Record
**Location**: Lines 143-168  
**Purpose**: Process new insurance company creation with contract document upload

**Function Signature**:
```php
function add()
```

**Process Flow**:
1. Collect form data including company details and contract info
2. Handle contract photo upload:
   ```php
   $handle = new upload($_FILES['contractPhoto']);
   $path = "../upload/insuranceCompany";
   $contractPhoto = uploadImages2($handle, $path);
   ```
3. Create new insurance company record with all details
4. Set default values (deleted = 0, userid from session)
5. Insert into database via DAO layer

**Form Fields Processed**:
- `companyName` - Insurance company name
- `discountPercent` - Discount percentage offered
- `contractStart` - Contract start date
- `contractEnd` - Contract end date  
- `contractPhoto` - Upload contract document image
- `instruction` - Special instructions/terms

---

### 3. **show()** - Display Insurance Companies List
**Location**: Lines 71-84  
**Purpose**: Show all insurance companies with automatic expiration status updates

**Function Signature**:
```php
// Triggered when: do=show
$insurancecompany = $insuranceCompanyDAO->queryAll();
```

**Process Flow**:
1. Query all insurance companies (including deleted)
2. Check contract expiration for each company:
   ```php
   foreach ($insurancecompany as $comp) {
       if ($comp->contractend < date('Y-m-d') && $comp->deleted != 1) {
           $comp->deleted = 2;  // Mark as expired
       }
   }
   ```
3. Assign to template for display
4. Present via `insuranceview/show.html`

**Status Indicators**:
- `deleted = 0` - Active company
- `deleted = 1` - Manually deleted company
- `deleted = 2` - Expired contract company

---

### 4. **edit()** - Edit Insurance Company Form
**Location**: Lines 101-109  
**Purpose**: Load insurance company data for editing

**Function Signature**:
```php
// Triggered when: do=edit&id=X
$companyId = filter_input(INPUT_GET, "id");
$insurancecompany = $insuranceCompanyDAO->load($companyId);
```

**Process Flow**:
1. Get company ID from URL parameter
2. Load existing company data
3. Assign to template for pre-populated form
4. Display via `insuranceview/edit.html`

---

### 5. **update()** - Update Insurance Company Record
**Location**: Lines 194-222  
**Purpose**: Process insurance company updates with optional contract photo replacement

**Function Signature**:
```php
function update()
```

**Process Flow**:
1. Load existing company record by ID
2. Handle optional contract photo update:
   ```php
   if ($_FILES['contractPhoto']['name']) {
       $handle = new upload($_FILES['contractPhoto']);
       $path = "../upload/insuranceCompany";
       $contractPhoto = uploadImages2($handle, $path);
       $insurancecompany->contractphoto = $contractPhoto;
   }
   ```
3. Update all other fields from form data
4. Save changes via DAO update method

**Update Logic**:
- Only replaces contract photo if new file uploaded
- Preserves existing photo if no new upload
- Updates all other fields regardless
- Maintains audit trail with userid

---

### 6. **delete()** - Soft Delete Insurance Company
**Location**: Lines 86-98  
**Purpose**: Mark insurance company as deleted (soft delete)

**Function Signature**:
```php
// Triggered when: do=delete&id=X
$companyId = filter_input(INPUT_GET, "id");
$insurancecompany = $insuranceCompanyDAO->load($companyId);
$insurancecompany->deleted = 1;
```

**Process Flow**:
1. Get company ID from URL parameter
2. Load company record
3. Set `deleted = 1` (soft delete)
4. Update record in database
5. Redirect to success or error page

---

## 🔄 Workflows

### Workflow 1: Insurance Company Registration
```
┌─────────────────────────────────────────────────────────────┐
│            START: Register Insurance Company                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Display Registration Form                               │
│     - Company name field                                    │
│     - Discount percentage field                             │
│     - Contract start date                                   │
│     - Contract end date                                     │
│     - Contract document upload                              │
│     - Special instructions textarea                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Validate Form Input                                     │
│     - Check required fields                                 │
│     - Validate date range (start < end)                    │
│     - Validate discount percentage (0-100)                 │
│     - Check contract photo upload                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Contract Document                               │
│     - Upload contract photo to server                       │
│     - Store in ../upload/insuranceCompany/                  │
│     - Generate unique filename                              │
│     - Validate file type and size                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Create Insurance Company Record                         │
│     - Set company name and discount                         │
│     - Set contract dates and photo path                    │
│     - Set special instructions                              │
│     - Set userid for audit trail                           │
│     - Set deleted = 0 (active status)                      │
│     - Insert into insurancecompanies table                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Confirm Registration                                    │
│     - Display success message                               │
│     - Return to company list                                │
│     - Company ready for warranty operations                │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Contract Expiration Management
```
┌─────────────────────────────────────────────────────────────┐
│              START: View Company List                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Query All Insurance Companies                           │
│     - Load all records regardless of status                 │
│     - Include active, deleted, and expired                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Check Contract Expiration                               │
│     FOR EACH insurance company:                             │
│       │                                                     │
│       ├─→ Compare contractend with today's date            │
│       │                                                     │
│       ├─→ If expired and not manually deleted:             │
│       │   └─ Set deleted = 2 (expired status)             │
│       │                                                     │
│       └─→ Maintain other statuses unchanged                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Display Company List with Status                        │
│     - Show company name and details                         │
│     - Display contract dates                                │
│     - Show discount percentage                              │
│     - Indicate status:                                      │
│       ├─ Active (deleted = 0)                              │
│       ├─ Deleted (deleted = 1)                             │
│       └─ Expired (deleted = 2)                             │
│     - Provide edit/delete actions for active companies     │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display add insurance company form |
| `do=add` | add() | Process new insurance company creation |
| `do=show` | show() | Display all insurance companies with status |
| `do=edit&id=X` | edit() | Load company for editing |
| `do=update` | update() | Process company updates |
| `do=delete&id=X` | delete() | Soft delete company |
| `do=sucess` | Default | Success page display |
| `do=error` | Default | Error page display |

### Required Parameters by Action

**Add Insurance Company** (`do=add`):
- `companyName` - Company name (required)
- `discountPercent` - Discount percentage offered
- `contractStart` - Contract start date
- `contractEnd` - Contract end date
- `contractPhoto` - Contract document file upload
- `instruction` - Special instructions (optional)

**Edit Company** (`do=edit`):
- `id` - Insurance company ID (GET parameter)

**Update Company** (`do=update`):
- `companyId` - Company ID (POST parameter)
- `companyName` - Updated company name
- `discountPercent` - Updated discount percentage
- `contractStart` - Updated contract start date
- `contractEnd` - Updated contract end date
- `contractPhoto` - New contract document (optional)
- `instruction` - Updated special instructions

**Delete Company** (`do=delete`):
- `id` - Insurance company ID (GET parameter)

---

## 🧮 Calculation Methods

### Contract Expiration Check
```php
// Automatic expiration status update
foreach ($insurancecompany as $comp) {
    if ($comp->contractend < date('Y-m-d') && $comp->deleted != 1) {
        $comp->deleted = 2;  // Mark as expired
    }
}
```

### Status Values
```php
// Status interpretation
$status = [
    0 => 'Active',     // Active contract
    1 => 'Deleted',    // Manually deleted
    2 => 'Expired'     // Contract expired
];
```

### File Upload Processing
```php
// Contract document upload
$handle = new upload($_FILES['contractPhoto']);
$path = "../upload/insuranceCompany";
$contractPhoto = uploadImages2($handle, $path);
```

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
// All actions require authentication
include_once("../public/authentication.php");
```

### Input Validation
```php
// Safe input handling using filter_input
$companyName = filter_input(INPUT_POST, "companyName");
$discountPercent = filter_input(INPUT_POST, "discountPercent");
$companyId = filter_input(INPUT_GET, "id");
```

### File Upload Security
- Images uploaded to restricted directory: `../upload/insuranceCompany`
- File type validation through uploadImages2() function
- Unique filename generation to prevent conflicts
- Path traversal protection

### Data Integrity
- Soft delete preserves historical data
- Audit trail maintained with userid
- Contract expiration automated to prevent manual oversight
- Foreign key relationships maintained

---

## 📊 Performance Considerations

### Database Optimization
1. **Required Indexes**:
   - `insurancecompanies(deleted)` - For status filtering
   - `insurancecompanies(contractend)` - For expiration checking
   - `insurancecompanies(userid)` - For audit queries

2. **Query Efficiency**:
   - Single query loads all companies for expiration check
   - Status updates processed in memory before display
   - File upload validation prevents large file processing

3. **File Management**:
   - Contract photos stored in dedicated directory
   - Image processing optimized through uploadImages2() function
   - Old contract photos not automatically deleted (manual cleanup needed)

---

## 🐛 Common Issues & Troubleshooting

### 1. **Contract Photo Upload Failures**
**Issue**: Contract photo not uploading or showing broken links  
**Cause**: File permission issues or invalid file types

**Debug**:
```php
// Check upload directory permissions
if (!is_writable("../upload/insuranceCompany")) {
    echo "Directory not writable";
}

// Check upload errors
if ($_FILES['contractPhoto']['error'] !== UPLOAD_ERR_OK) {
    echo "Upload error: " . $_FILES['contractPhoto']['error'];
}
```

### 2. **Contract Expiration Not Updating**
**Issue**: Expired companies still showing as active  
**Cause**: Date comparison or status update logic issues

**Debug**:
```sql
-- Check contract end dates
SELECT name, contractend, deleted, DATEDIFF(contractend, CURDATE()) as days_until_expiry
FROM insurancecompanies 
WHERE deleted != 1;

-- Manual expiration update
UPDATE insurancecompanies 
SET deleted = 2 
WHERE contractend < CURDATE() AND deleted = 0;
```

### 3. **Discount Percentage Validation**
**Issue**: Invalid discount percentages accepted  
**Cause**: Missing client-side or server-side validation

**Fix**:
```php
// Add validation in add() and update() functions
if ($discountPercent < 0 || $discountPercent > 100) {
    throw new Exception("Discount percentage must be between 0 and 100");
}
```

### 4. **Soft Delete Recovery**
**Issue**: Need to restore accidentally deleted companies  
**Cause**: No restore functionality provided

**Fix**:
```sql
-- Restore deleted company
UPDATE insurancecompanies 
SET deleted = 0 
WHERE insurancecompaniesid = ? AND deleted = 1;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Company Registration
```
1. Navigate to insurance company management
2. Fill in company details:
   - Company name: "Test Insurance Co"
   - Discount: 10%
   - Contract dates: Valid future range
   - Upload contract document
   - Add special instructions
3. Submit form and verify success message
4. Check company appears in list as active
```

### Test Case 2: Contract Expiration Handling
```
1. Create company with past contract end date
2. Navigate to company list view
3. Verify company shows as expired (status = 2)
4. Confirm company cannot be used for warranty operations
```

### Test Case 3: Company Update with Photo Replacement
```
1. Edit existing company
2. Update discount percentage
3. Upload new contract document
4. Save changes
5. Verify old photo replaced and new data saved
```

### Test Case 4: Soft Delete and Recovery
```
1. Delete active company
2. Verify company marked as deleted in list
3. Check company not available for warranty operations
4. Manually restore via database if needed
```

### Debug Mode Enable
```php
// Add at top of controller for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Debug file upload
echo "Upload status: " . $_FILES['contractPhoto']['error'] . "<br>";
echo "Upload path: " . $contractPhoto . "<br>";

// Debug expiration logic
echo "Today: " . date('Y-m-d') . "<br>";
echo "Contract end: " . $comp->contractend . "<br>";
echo "Expired: " . ($comp->contractend < date('Y-m-d') ? 'Yes' : 'No') . "<br>";
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [insuranceGo.md](insuranceGo.md) - Outbound warranty shipments
- [insuranceReturn.md](insuranceReturn.md) - Warranty returns processing  
- [shippercompaniesController.md](shippercompaniesController.md) - Shipping companies
- [Upload Library Documentation](#) - File upload functions

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When insurance company processes change