# Guarantee Deposit Display and Management

## Overview
Implemented guarantee deposit visibility across all user roles (Admin, User, Officer), API responses, and an admin management interface. Loan-level deposit details remain available where a deposit was deducted, while the admin register also shows users whose deposit balance is stored on their user account.

## Changes Made

### 1. API Response Enhancement
**File**: [app/Http/Resources/LoanResource.php](app/Http/Resources/LoanResource.php)

Added guarantee deposit section to the JSON response when a guarantee deposit has been deducted:
```php
'guarantee_deposit' => $this->when($this->guarantee_deposit_amount > 0, function () {
    return [
        'amount' => $this->guarantee_deposit_amount,
        'percentage' => $this->guarantee_deposit_percentage,
        'usage_type' => $this->guarantee_deposit_usage,
    ];
}),
```

**Impact**: Mobile apps and API clients now receive guarantee deposit information for all loans with deducted guarantees.

### 2. Admin Loan Details View
**File**: [resources/views/admin/loans/show.blade.php](resources/views/admin/loans/show.blade.php)

Added guarantee deposit information to the "Loan Summary" section:
- **Guarantee Deposit Amount**: KSh (formatted with 2 decimal places)
- **Guarantee Deposit Percentage**: Percentage value (e.g., 10%)
- **Guarantee Deposit Usage**: Usage type displayed with readable formatting

Displays only when `guarantee_deposit_amount > 0`.

### 3. User Loan Details View
**File**: [resources/views/user/loans/show.blade.php](resources/views/user/loans/show.blade.php)

Added guarantee deposit information to the "Quick Info" section:
- Displays in a separated subsection with border-top for visual distinction
- Shows:
  - Amount Deducted (in KSh)
  - Percentage of principal
  - Usage Type (with readable formatting)
- Appears below disbursement details for context

### 4. Officer Loan Details View
**File**: [resources/views/officer/loans/show.blade.php](resources/views/officer/loans/show.blade.php)

Added guarantee deposit as a dedicated card in the financial details grid:
- Prominent display with indigo left border to match other financial details
- Shows guarantee amount with formatting
- Includes percentage and usage type in sub-details
- Positioned alongside other fees and financial information

### 5. Admin Guarantee Deposit Management
**Files**: [app/Http/Controllers/Admin/GuaranteeDepositController.php](app/Http/Controllers/Admin/GuaranteeDepositController.php), [resources/views/admin/guarantee-deposits/index.blade.php](resources/views/admin/guarantee-deposits/index.blade.php)

Added a protected management page at `/admin/guarantee-deposits`, linked by the **Guarantee Deposits** button on the admin loans page.

The page:
- Shows every user with a positive `guarantee_deposit_balance`
- Displays the user's national ID or phone number and linked loan details
- Displays each linked loan's ID, status, principal, tier, and usage type
- Shows filtered total balance and the number of matching users
- Supports search by name, national ID, or phone
- Supports filtering by guarantee usage type and loan status
- Allows an administrator to update a user's guarantee deposit balance

The balance update is validated as numeric and non-negative. It does not alter loan principal, repayment totals, or disbursement calculations.

### 6. Admin Routes
**File**: [routes/web.php](routes/web.php)

The management routes are inside the existing `auth` and `admin` middleware group:

| Method | URL | Purpose |
|---|---|---|
| `GET` | `/admin/guarantee-deposits` | List and filter users with positive balances |
| `PATCH` | `/admin/guarantee-deposits/users/{user}` | Update a user's guarantee balance |
| `PATCH` | `/admin/guarantee-deposits/{guaranteeDeposit}` | Update an audit deposit record when one exists |

## Display Logic

All views use the same conditional logic:
```php
@if($loan->guarantee_deposit_amount > 0)
    <!-- Display guarantee details -->
@endif
```

This ensures guarantee information only appears when a guarantee has actually been deducted.

## Usage Type Formatting

The display automatically formats usage types for readability:
- `offset_final_installment` → "Offset Final Installment"
- `carry_forward` → "Carry Forward"
- `user_account` → "User Account"

Implementation: `str_replace('_', ' ', ucfirst($loan->guarantee_deposit_usage))`

## Accessibility & Consistency

- **All three roles** (Admin, User, Officer) see the same guarantee deposit information
- **Responsive design** - works on mobile and desktop
- **Consistent styling** - matches existing loan detail displays
- **Clear labels** - easy to understand for all users

## Data Availability

Guarantee deposit information is available from:
1. **User balance**: `$user->guarantee_deposit_balance` is the source used by the admin management register
2. **Loan snapshot**: `$loan->guarantee_deposit_amount`, `$loan->guarantee_deposit_percentage`, and `$loan->guarantee_deposit_usage` are used by loan detail pages and API responses
3. **Audit trail**: `$loan->guaranteeDeposits()` contains deposit records when they have been created by the disbursement flow

The admin register intentionally uses the user balance as its primary source. This supports existing and imported data where a user has a positive balance but no corresponding `guarantee_deposits` audit row.

## Validation

The implementation was validated with:
- `php -l` on the new and modified PHP files
- `php artisan route:list --name=admin.guarantee-deposits`
- `php artisan view:cache`
- Database verification confirming positive-balance users are returned by the management query

## Testing Recommendations

1. **Admin View**: Create a test loan with guarantee, verify display in admin dashboard
2. **User View**: Log in as borrower, verify guarantee details show on loan page
3. **Officer View**: Log in as officer, verify guarantee details display correctly
4. **API Testing**: Query `/api/loans/{id}` and verify guarantee_deposit field present
5. **No Guarantee**: Verify guarantee section doesn't show when amount is 0

## Future Enhancements

Potential improvements:
- Add guarantee deposit history/timeline view
- Show guarantee deposit transactions separately
- Add guarantee usage actions (if implementing carry_forward/offset functionality)
- Add a dedicated audit history view for balance adjustments
