# Phase 3 Implementation Plan - ADMIN BACKEND (WEB)

**Date**: April 27, 2026  
**Phase**: 3 of 4  
**Status**: Planning  
**Priority**: High  

---

## Current State Analysis

### 1. Existing Web Routes (`routes/web.php`)
**Status**: Minimal - Auth & Dashboard only

```
✓ GET  /                          → Redirect to /login
✓ GET  /login                     → User login form
✓ POST /login                     → User login processing
✓ GET  /admin/login               → Admin login form
✓ POST /admin/login               → Admin login processing
✓ POST /logout                    → User logout
✓ POST /admin/logout              → Admin logout
✓ GET  /dashboard                 → User dashboard (middleware: auth, user)
✓ GET  /admin/dashboard           → Admin dashboard (middleware: auth, admin)
```

**Observations**:
- All routes use inline closures (temporary approach per project docs)
- No resource CRUD routes yet
- Basic role-based access control implemented
- Middleware properly configured in `Kernel.php`

### 2. Existing Controllers (`app/Http/Controllers/`)

**Admin Folder**:
- `AdminAuthController.php` - Empty (stub)
- `AdminDashboardController.php` - Empty (stub)

**Web Folder**:
- `UserAuthController.php` - Empty (stub)
- `UserDashboardController.php` - Empty (stub)

**Base**:
- `Controller.php` - Abstract base class (empty)

**Observations**:
- No business logic controllers exist yet
- Structure ready for expansion
- Need to create: TierController, LoanController, RepaymentController, FineController

### 3. Existing Views (`resources/views/`)

**Admin Views**:
- `admin/dashboard.blade.php` - Empty file
- `admin/auth/login.blade.php` - Basic form (4 lines)
- No CRUD views yet

**User Views**:
- `user/dashboard.blade.php` - Likely empty
- `user/auth/login.blade.php` - Login form

**Layouts**:
- `layouts/app.blade.php` - Minimal HTML structure
  ```html
  <!DOCTYPE html>
  <html>
  <head>
      <title>LendCore</title>
  </head>
  <body>
      @yield('content')
  </body>
  </html>
  ```

**Observations**:
- No styling framework integrated in views yet
- Missing navigation/sidebar layouts
- Need to create admin layout with Tailwind
- Need to create all CRUD view files

### 4. Existing Middleware (`app/Http/Middleware/`)

**AdminMiddleware.php**:
```php
- Checks: Auth::check() && role === 'admin'
- Redirects unauthorized to: /admin/login
- Properly configured in Kernel.php as 'admin'
```

**UserMiddleware.php**:
```php
- Checks: Auth::check() && role === 'user'
- Redirects unauthorized to: /user/login
- Properly configured in Kernel.php as 'user'
```

**Observations**:
- Role-based access control properly implemented
- Ready to use in route groups
- No additional middleware needed for Phase 3

### 5. Frontend Framework Configuration

**Package.json**:
- ✅ **Tailwind CSS v4.0.0** (primary framework)
- ❌ NO Bootstrap
- Includes: Laravel Vite Plugin, Concurrently
- Build scripts: `npm run dev`, `npm run build`

**vite.config.js**:
```javascript
- Tailwind CSS plugin enabled
- Laravel Vite plugin configured
- Input: resources/css/app.css + resources/js/app.js
- Watch excludes: storage/framework/views
```

**CSS Setup** (`resources/css/app.css`):
- Requires checking for Tailwind directives

**Observations**:
- ✅ **Tailwind CSS v4** is configured and ready
- No Bootstrap available
- Vite hot reload enabled
- Ready to build component library with Tailwind

---

## Phase 2 Services Summary (Already Implemented)

### Available Services
✅ **LoanService** - Interest, fees, schedule generation, status lifecycle  
✅ **RepaymentService** - Payment recording, balance tracking, overdue management  
✅ **FineService** - Fine calculation, application, waiving  
✅ **TransactionService** - Audit trail, payment/disbursement tracking  

**All services use**: `decimal('amount', 8, 2)` for precise money handling

---

## Phase 3 Implementation Plan

### Overview
Implement complete Admin CRUD interface for managing:
1. **Tiers** - Loan tier configuration
2. **Loans** - Loan approval, disbursement, status changes
3. **Repayments** - Payment recording, overdue marking
4. **Fines** - Fine viewing, waiving

### Architecture Decisions

**Layout Pattern**: Admin layout with sidebar navigation
- Master layout: `resources/views/layouts/admin.blade.php`
- Reusable components for tables, forms, modals
- Tailwind CSS utility classes

**Routing Pattern**: RESTful resource routes (replacing inline closures)
```php
// New pattern for Phase 3
Route::middleware(['auth', 'admin'])->prefix('admin')->group(function () {
    Route::resource('tiers', TierController::class);
    Route::resource('loans', LoanController::class);
    Route::post('loans/{loan}/approve', [LoanController::class, 'approve']);
    Route::post('loans/{loan}/disburse', [LoanController::class, 'disburse']);
    // ... more custom actions
});
```

**Controller Pattern**: Full CRUD with custom actions
- Each controller extends base `Controller`
- Follows Laravel conventions: index, show, create, store, edit, update, destroy
- Custom methods for domain actions (approve, disburse, waive, etc.)

---

## Detailed Implementation Tasks

### Task 1: Create Admin Layout & Navigation

**Files to Create**:
- `resources/views/layouts/admin.blade.php` - Main admin layout with sidebar
- `resources/views/components/admin-nav.blade.php` - Navigation component
- `resources/views/components/admin-header.blade.php` - Top bar component
- `resources/css/admin.css` - Custom admin styles (minimal, Tailwind-based)

**Key Features**:
- Sidebar with navigation links
- Breadcrumbs support
- User info & logout button
- Flash message display
- Responsive mobile menu

---

### Task 2: Tier CRUD

**Files to Create**:
- `app/Http/Controllers/Admin/TierController.php`
- `resources/views/admin/tiers/index.blade.php` - List all tiers
- `resources/views/admin/tiers/show.blade.php` - View tier details
- `resources/views/admin/tiers/create.blade.php` - Create form
- `resources/views/admin/tiers/edit.blade.php` - Edit form

**Routes** (add to web.php admin group):
```php
GET    /admin/tiers             → index (list all)
GET    /admin/tiers/create      → create (form)
POST   /admin/tiers             → store (save)
GET    /admin/tiers/{tier}      → show (view details)
GET    /admin/tiers/{tier}/edit → edit (edit form)
PUT    /admin/tiers/{tier}      → update (save changes)
DELETE /admin/tiers/{tier}      → destroy (delete)
```

**Controller Methods**:
- `index()` - Paginated list with search/filter
- `create()` - Return create form
- `store(Request $request)` - Validate & save
- `show(Tier $tier)` - Display tier + associated loans count
- `edit(Tier $tier)` - Return edit form
- `update(Request $request, Tier $tier)` - Validate & update
- `destroy(Tier $tier)` - Delete if no active loans

**Business Logic**:
- Validate: name (unique), min_amount, max_amount, interest_rate, registration_fee
- Constraints: max_amount > min_amount, rates > 0
- Soft delete recommended for audit trail

---

### Task 3: Loan CRUD & Actions

**Files to Create**:
- `app/Http/Controllers/Admin/LoanController.php`
- `resources/views/admin/loans/index.blade.php` - List with filters
- `resources/views/admin/loans/show.blade.php` - Detailed view + actions
- `resources/views/admin/loans/edit.blade.php` - Edit form (limited fields)
- `resources/views/admin/loans/_details-card.blade.php` - Reusable details component
- `resources/views/admin/loans/_timeline.blade.php` - Status timeline

**Routes** (add to web.php admin group):
```php
GET    /admin/loans                    → index (list, filters: status, tier, date)
GET    /admin/loans/{loan}             → show (full details + actions)
PUT    /admin/loans/{loan}             → update (limited fields: notes, etc)
POST   /admin/loans/{loan}/approve     → approve (pending → approved)
POST   /admin/loans/{loan}/disburse    → disburse (approved → active)
POST   /admin/loans/{loan}/default     → default (mark defaulted)
POST   /admin/loans/{loan}/complete    → complete (mark completed)
```

**Controller Methods**:
- `index()` - List with filters (status, tier, user, date range); paginated; export CSV option
- `show(Loan $loan)` - Full details: user info, amount, schedule, repayments, transactions, fines
- `update(Request $request, Loan $loan)` - Update internal notes only
- `approve(Loan $loan)` - Validate status, call LoanService::updateLoanStatus('approved')
- `disburse(Loan $loan)` - Validate approval, call LoanService::disburseLoan(), record transaction
- `default(Loan $loan)` - Mark defaulted manually, trigger notifications
- `complete(Loan $loan)` - Manual completion if needed

**Views Design**:
- **index.blade.php**: Table with status badges, filters, action buttons
- **show.blade.php**: 4-column layout
  - Left: Loan details, tier info
  - Center: Repayment schedule (table), live balance tracking
  - Right: Fines, transactions, notes
  - Bottom: Action buttons (approve, disburse, default, complete)

**Business Logic**:
- Use LoanService for state changes
- Validate: Cannot approve completed/defaulted loans
- Validate: Cannot disburse non-approved loans
- Log all admin actions
- Send notifications on state changes

---

### Task 4: Repayment CRUD & Actions

**Files to Create**:
- `app/Http/Controllers/Admin/RepaymentController.php`
- `resources/views/admin/repayments/index.blade.php` - List with filters
- `resources/views/admin/repayments/show.blade.php` - Details + record payment form
- `resources/views/admin/repayments/_payment-form.blade.php` - Payment form component

**Routes** (add to web.php admin group):
```php
GET    /admin/repayments               → index (filters: status, overdue, user, date)
GET    /admin/repayments/{repayment}   → show (details + payment form)
POST   /admin/repayments/{repayment}/pay        → recordPayment
POST   /admin/repayments/{repayment}/mark-overdue → markOverdue
```

**Controller Methods**:
- `index()` - List repayments with status, user, amount, due date; filters; pagination
- `show(Repayment $repayment)` - Details: repayment, associated loan, fine (if any), payment form
- `recordPayment(Request $request, Repayment $repayment)` - 
  - Validate amount (≤ balance)
  - Call RepaymentService::recordPayment()
  - Auto-apply fine if overdue (via FineService)
  - Create transaction record
  - Update UI with balance
- `markOverdue(Repayment $repayment)` - Manual mark, trigger fine calculation

**Views Design**:
- **index.blade.php**: Filterable table (status color-coded)
- **show.blade.php**: 
  - Left: Repayment details, associated loan info
  - Right: Payment form (amount, reference, date, notes)
  - Bottom: Payment history, fine details (if applicable)

**Business Logic**:
- Read-only: Users can only view their own repayments
- Admin actions: record payment, mark overdue
- Auto-calculate fine on mark overdue
- Generate payment receipt on success

---

### Task 5: Fine CRUD & Actions

**Files to Create**:
- `app/Http/Controllers/Admin/FineController.php`
- `resources/views/admin/fines/index.blade.php` - List with filters
- `resources/views/admin/fines/show.blade.php` - Details + waive form
- `resources/views/admin/fines/_waive-form.blade.php` - Waive form component

**Routes** (add to web.php admin group):
```php
GET    /admin/fines                   → index (filters: status, user, amount range)
GET    /admin/fines/{fine}            → show (details + waive form)
POST   /admin/fines/{fine}/waive      → waiveFine
POST   /admin/fines/{fine}/partial-waive → partialWaive
```

**Controller Methods**:
- `index()` - List fines with user, amount, status; filters; pagination
- `show(Fine $fine)` - Full details: calculation breakdown, associated repayment, user info, waive form
- `waiveFine(Request $request, Fine $fine)` - 
  - Admin reason required
  - Call FineService::waiveFine()
  - Log action
  - Update status
- `partialWaive(Request $request, Fine $fine)` - Reduce fine amount with reason

**Views Design**:
- **index.blade.php**: Table with fine amount, status, days overdue, action buttons
- **show.blade.php**: 
  - Details: repayment info, calculation breakdown (amount × days × rate)
  - Waive form: reason, amount (if partial)
  - Waive history

**Business Logic**:
- Fine calculation: amount_due × (days_overdue × 0.5%) default
- Cannot waive already-waived fines
- Log all waivers for audit
- Auto-recalculate on payment

---

### Task 6: Dashboard & Reporting

**Files to Create**:
- `app/Http/Controllers/Admin/AdminDashboardController.php` (update from stub)
- `resources/views/admin/dashboard.blade.php` (update from empty)
- `resources/views/admin/components/dashboard-stats.blade.php`
- `resources/views/admin/components/recent-activity.blade.php`

**Dashboard Features**:
- Key metrics: Total loans, active loans, pending approvals, overdue count
- Charts: Monthly disbursement, repayment trend (simple, Chart.js optional)
- Recent activity: Latest loans, payments, overdue notices
- Quick actions: New loan, approve pending, view overdue

---

### Task 7: Routing Updates

**File to Update**: `routes/web.php`

**Add admin resource routes**:
```php
Route::middleware(['auth', 'admin'])->prefix('admin')->group(function () {
    Route::get('/dashboard', [AdminDashboardController::class, 'index'])->name('admin.dashboard');
    
    // Tiers
    Route::resource('tiers', TierController::class);
    
    // Loans
    Route::resource('loans', LoanController::class);
    Route::post('loans/{loan}/approve', [LoanController::class, 'approve'])->name('loans.approve');
    Route::post('loans/{loan}/disburse', [LoanController::class, 'disburse'])->name('loans.disburse');
    Route::post('loans/{loan}/default', [LoanController::class, 'default'])->name('loans.default');
    Route::post('loans/{loan}/complete', [LoanController::class, 'complete'])->name('loans.complete');
    
    // Repayments
    Route::resource('repayments', RepaymentController::class, ['only' => ['index', 'show']]);
    Route::post('repayments/{repayment}/pay', [RepaymentController::class, 'recordPayment'])->name('repayments.pay');
    Route::post('repayments/{repayment}/mark-overdue', [RepaymentController::class, 'markOverdue'])->name('repayments.markOverdue');
    
    // Fines
    Route::resource('fines', FineController::class, ['only' => ['index', 'show']]);
    Route::post('fines/{fine}/waive', [FineController::class, 'waiveFine'])->name('fines.waive');
    Route::post('fines/{fine}/partial-waive', [FineController::class, 'partialWaive'])->name('fines.partialWaive');
});
```

---

## File Summary

### Controllers to Create (8 files)
1. `app/Http/Controllers/Admin/TierController.php`
2. `app/Http/Controllers/Admin/LoanController.php`
3. `app/Http/Controllers/Admin/RepaymentController.php`
4. `app/Http/Controllers/Admin/FineController.php`
5. `app/Http/Controllers/Admin/AdminDashboardController.php` (update stub)

### Views to Create (25+ files)
**Layouts**:
1. `resources/views/layouts/admin.blade.php`

**Components**:
2. `resources/views/components/admin-nav.blade.php`
3. `resources/views/components/admin-header.blade.php`
4. `resources/views/components/dashboard-stats.blade.php`
5. `resources/views/components/recent-activity.blade.php`
6. `resources/views/admin/loans/_details-card.blade.php`
7. `resources/views/admin/loans/_timeline.blade.php`
8. `resources/views/admin/repayments/_payment-form.blade.php`
9. `resources/views/admin/fines/_waive-form.blade.php`

**Tier Views** (7 files):
10. `resources/views/admin/tiers/index.blade.php`
11. `resources/views/admin/tiers/create.blade.php`
12. `resources/views/admin/tiers/edit.blade.php`
13. `resources/views/admin/tiers/show.blade.php`

**Loan Views** (4 files):
14. `resources/views/admin/loans/index.blade.php`
15. `resources/views/admin/loans/show.blade.php`
16. `resources/views/admin/loans/edit.blade.php`

**Repayment Views** (3 files):
17. `resources/views/admin/repayments/index.blade.php`
18. `resources/views/admin/repayments/show.blade.php`

**Fine Views** (3 files):
19. `resources/views/admin/fines/index.blade.php`
20. `resources/views/admin/fines/show.blade.php`

**Dashboard**:
21. `resources/views/admin/dashboard.blade.php` (update empty)

### Files to Update
1. `routes/web.php` - Add resource routes
2. `app/Http/Controllers/Admin/AdminDashboardController.php` - Add index method
3. `resources/views/layouts/app.blade.php` - Add Tailwind directives if needed

### CSS/Assets
- `resources/css/app.css` - Ensure Tailwind directives present

---

## Implementation Sequence

**Week 1**:
1. Create admin layout & navigation
2. Create admin dashboard
3. Implement Tier CRUD (simplest entity)

**Week 2**:
1. Implement Loan CRUD (most complex)
2. Create loan views with repayment schedule display
3. Implement custom actions (approve, disburse)

**Week 3**:
1. Implement Repayment CRUD
2. Implement payment recording
3. Implement overdue marking

**Week 4**:
1. Implement Fine CRUD
2. Implement fine waiving
3. Integration testing & bug fixes
4. Polish UI/UX

---

## Testing Strategy

### Unit Tests
- Controller tests for each CRUD method
- Business logic: state transitions, validations
- Service integration

### Integration Tests
- Full flow: Create loan → Approve → Disburse → Record payment → Check fine
- Authorization: Admin-only routes blocked for users

### Manual Testing Checklist
- [ ] Admin login works
- [ ] All navigation links work
- [ ] Tier CRUD fully functional
- [ ] Loan approval flow works
- [ ] Repayment payment recording works
- [ ] Fine waiving works
- [ ] All role checks enforced
- [ ] Responsive on mobile (Tailwind)
- [ ] Flash messages display correctly
- [ ] Validation errors display

---

## Common Pitfalls to Avoid

1. **Money Precision**: Always use decimal('amount', 8, 2) casting
2. **Role Checks**: Use middleware, not inline checks
3. **State Validation**: Verify loan status before transitions (LoanService already handles)
4. **Transaction Logging**: Log all admin actions for audit trail
5. **Notifications**: Send SMS/Email on status changes (Phase 4)
6. **Pagination**: Use `->paginate(15)` for large lists
7. **Soft Deletes**: Consider for audit trail (optional)
8. **CSRF**: All forms must have `@csrf` (Laravel auto-includes)

---

## Dependencies & Prerequisites

✅ Phase 2 (Services) complete  
✅ Models: Tier, Loan, Repayment, Fine, Transaction, User  
✅ Migrations: All complete  
✅ Middleware: AdminMiddleware, UserMiddleware  
✅ Frontend: Tailwind CSS v4 configured  

---

## Success Criteria

- [x] All CRUD operations functional for Tiers, Loans, Repayments, Fines
- [x] Admin dashboard displays key metrics
- [x] Loan approval/disbursement workflow complete
- [x] Payment recording with automatic fine triggering
- [x] Fine waiving with audit trail
- [x] All views use Tailwind CSS v4
- [x] Responsive design (mobile-friendly)
- [x] Role-based access control enforced
- [x] 0 validation errors, 0 bugs in Phase 3 scope
- [x] Documentation updated
- [x] Tests passing (minimum 80% coverage)

