# Implementation Plan & AI Continuity Handoff

> **This is the primary document for any AI agent continuing this project.**
> Last updated: 2026-04-30

---

## Recent platform updates (documentation sync)

The following shipped or was finalized recently; keep code and docs aligned when extending features.

| Area | Change |
|---|---|
| **Mount / URLs** | `helpers/AppUrls.php`, `.env` + `config/env.php`, no hardcoded app folder; `ViewUrls::viewsBase()` delegates to `AppUrls`; `resources/js/api.js` normalizes Axios `baseURL` and mount paths. |
| **Auth** | `AuthController::login` and password change use **only** `password_verify` against `users.password_hash` (no demo bypass). |
| **Company dashboard** | `DashboardController`: `GET .../dashboard/stats`, `/dashboard/activity`, `/dashboard/widgets`; `dashboard.php` uses widgets API. |
| **Contracts** | Split reads: `details`, `timeline`, `messages`; `POST .../contracts/upload`; milestones list/detail + actions; Postman **Activities** folder for activity API. |
| **Contract review UI** | `contract_review.php` hides **Send contract** unless `version_status === 'draft'` so sent versions are read-only; new revision drafts show the button again. |
| **Contract roles UI** | Signing rep / site engineer dropdowns aligned to **authorized_agent** / **site_engineer** roles. |
| **Termination & settlement** | `ContractController`: `GET .../termination/settlement`, `POST .../termination/approve`, `POST .../termination/reject`, `GET .../termination/reconciliation`, `POST .../termination/confirm-settlement`. Views: `contract_termination_settlement.php`, `contract_settlement_reconciliation.php`, `contract_settlement_recalculate.php`. Contract list shows `termination_pending`. |
| **contract_details.php** | Status badges for `terminated`, `cancelled`, `termination_pending`, etc.; hide **Withdraw** + **Revise** when terminated/cancelled; signing sidebar + main **timeline** include termination events (`type: termination` from API). |
| **Postman** | `API_COLLECTION.json`: **05 Contracts → Termination settlement** folder documents the new routes. |

---

## ✅ What Has Been Built (Completed)

### Authentication
- Login (email+password), OTP login, password reset, logout with token versioning (global logout).

### Company Profile & Settings
- Profile edit, logo upload, document upload, legal information.
- Account deactivation request workflow (admin-reviewed).
- Notification preferences, security settings.

### Catalog
- Products CRUD (with categories, media, specifications).
- Services CRUD (with multi-media: images + videos).
- Global catalog categories (non-company-scoped), filtered by `type = 'product'|'service'`.

### Requests
- Company views incoming direct and broadcast requests.
- `request_details.php` — full detail page with embedded **Chat/Messaging** (date+time timestamps: "MMM DD, YYYY at HH:MM AM/PM").

### Quotations
- Create line-item quotations with VAT and payment milestones.
- Upload PDF quotation alternative.
- Client accepts/rejects quotation.

### Contracts — **FULLY BUILT**
All pages and backend logic are complete for the contract lifecycle:

#### Pages (all in `views/company/`)
| Page | Status | Purpose |
|---|---|---|
| `contract_roles.php` | ✅ Done | Assign signing rep + site engineer |
| `generate_contract.php` | ✅ Done | Edit contract (scope, items, milestones, clauses) |
| `contract_review.php` | ✅ Done | Legal document preview; Send only for `version_status = draft`. |
| `revision_review.php` | ✅ Done | Side-by-side old vs new revision comparison |
| `revision_sent.php` | ✅ Done | Post-revision confirmation with "What Happens Next" tracker |
| `contract_details.php` | ✅ Done | Dynamic timeline + Messages tab; terminated/cancelled UI; termination timeline rows |
| `contracts.php` | ✅ Done | Contract list (incl. `termination_pending` treatment) |
| `contract_termination_settlement.php` | ✅ Done | Termination settlement wizard |
| `contract_settlement_reconciliation.php` | ✅ Done | Post-approve reconciliation |
| `contract_settlement_recalculate.php` | ✅ Done | Recalculate settlement comparison |

#### API Endpoints (all in `ContractController.php`, registered in `public/index.php`)
| Endpoint | Status |
|---|---|
| `POST /api/v1/company/contracts` | ✅ Done |
| `GET /api/v1/company/contracts` | ✅ Done |
| `GET /api/v1/company/contracts/init` | ✅ Done |
| `GET /api/v1/company/contracts/roles` + `POST` | ✅ Done |
| `GET /api/v1/company/contracts/review` | ✅ Done |
| `GET /api/v1/company/contracts/details` | ✅ Done |
| `GET /api/v1/company/contracts/timeline` | ✅ Done |
| `GET /api/v1/company/contracts/messages` | ✅ Done |
| `POST /api/v1/company/contracts/upload` | ✅ Done |
| `GET /api/v1/company/contracts/edit` | ✅ Done |
| `POST /api/v1/company/contracts/send` | ✅ Done |
| `POST /api/v1/company/contracts/sign` | ✅ Done (simulated UAE PASS) |
| `POST /api/v1/company/contracts/start-revision` | ✅ Done |
| `POST /api/v1/company/contracts/cancel-revision` | ✅ Done |
| `GET /api/v1/company/contracts/termination/settlement` | ✅ Done |
| `POST /api/v1/company/contracts/termination/approve` | ✅ Done |
| `POST /api/v1/company/contracts/termination/reject` | ✅ Done |
| `GET /api/v1/company/contracts/termination/reconciliation` | ✅ Done |
| `POST /api/v1/company/contracts/termination/confirm-settlement` | ✅ Done |

#### Dynamic Timeline
- `getContractReviewData` and `getContractTimeline` generate a `timeline` array based on `contracts.status` + `contract_versions` history, plus a final **`type: "termination"`** event when status is `termination_pending`, `terminated`, or `cancelled` (localized titles via `Lang::get` on the server).
- Frontend `renderTimeline()` in `contract_details.php` renders it dynamically (including termination styling).
- "ACTION REQUIRED" card auto-appears when `status = pending_signature`.

#### Messaging in Contract
- Messages tab in `contract_details.php` reuses `ChatController` via the contract's `request_id`.

### Admin Panel
- Company list, approval, suspension, verification.
- Platform settings.
- Global catalog category management.

---

## 🚧 Next Steps (What to Build Next)

### Priority 1: Execution Phase — **FULLY BUILT**
**Context:** When a contract is signed (`status = active`), the project enters execution. The site engineer reporting progress milestone by milestone is fully implemented.

**What has been built:**
- **Execution Control UI**: `execution_control.php` allows defining stages, tracking progress, and viewing stage details.
- **Stage Management**: `ExecutionController.php` handles CRUD for stages, progress updates (with multi-photo evidence), and customer reviews.
- **Progress Tracking**: Overall progress is dynamically calculated based on completed stages and reflects on the contract timeline.
- **Extension Requests**: Support for requesting deadline extensions with reason codes and evidence.

---

### Priority 2: Payment Milestones — **FULLY BUILT**
**Context:** `contract_details.php` has a "Payment Milestones" tab. Backend and frontend logic for requesting, reminding, and reviewing payments are complete.

**What has been built:**
- **Milestone Actions**: Request payment, send reminders, and review submissions directly from the "Payment Milestones" tab.
- **Status Integration**: Milestones transition through `locked` -> `payment_required` -> `pending` -> `verified`/`rejected`.
- **Customer Notifications**: Integrated with the notification system to alert customers when payment is requested.

---

### ✅ Customer Mobile App Backend
**Context:** The backend for the Customer Mobile App is now fully operational, covering all essential lifecycle features from discovery to contract signature.

**Completed:**
- Registered all `/api/v1/customer/...` routes in `public/index.php`.
- Verified and synced `CustomerDashboardController`, `BrowseController`, `CustomerRequestController`, `CustomerQuotationController`, and `CustomerContractController`.
- Added a new top-level folder **03 Customer Mobile App** in the Postman collection (`API_COLLECTION.json`) with subfolders for all modules.
- Implemented core flows:
    - **Discovery**: Browse companies, services, products, and categories.
    - **Requests**: Create service requests, manage drafts.
    - **Quotations**: View and respond (accept/reject) to quotations.
    - **Contracts**: Review, approve, and sign (UAE PASS simulation) contracts.
    - **Messaging**: Full chat support for requests and contracts.
    - **Notifications**: Real-time notification list and mark-as-read functionality.
    - **Execution**: Track project progress milestone-by-milestone from the customer side.
    - **Profile**: Manage customer profile, multiple addresses, and notification settings.

---

### Priority 3: Real UAE PASS Integration

### Priority 4: Real UAE PASS Integration
**Context:** `signContract()` in `ContractController.php` currently simulates the signature with a 2-second delay.

**What to build:**
- Integrate the real UAE PASS OAuth flow.
- The "Sign with UAE PASS" button should redirect to the UAE PASS authorization URL.
- On callback, update `contracts.signed_at` and `status = active`.
- Requires: UAE PASS API credentials from the client.

---

### Priority 5: Localization Audit
**Context:** Termination **titles/descriptions** returned in API `timeline` for `type: termination` use `Lang::get` (server-side). Older timeline rows (created, signature, execution, etc.) may still be English in `ContractController` — optional follow-up to move all timeline copy into `language/en.php` + `ar.php` or pass keys to the client.

---

## 🗂 Key Technical Notes for AI Agents

### Translation System
- PHP side: `Lang::get('key')` in view files.
- JS side: `const t = allTranslations[currentDocLang]` — fed by `json_encode($en_doc)` in the page.
- **Always add new keys to BOTH `language/en.php` AND `language/ar.php`.**
- Missing translation keys accessed with `.replace()` in JS cause fatal silent errors — the render function stops completely.

### Contract Version Logic
- `contracts.current_version_no` — the last **accepted** version.
- `contract_versions.version_no` — the MAX version is the current working draft.
- When `version_no > current_version_no`, there is a pending revision draft.
- `startRevision()` copies all items/milestones from the current accepted version into the new draft version.

### Chat / Messages
- All messages are tied to `request_id`, not `contract_id`.
- This means the same conversation thread spans the entire lifecycle from initial request through final contract.

### Postman Sync
- Keep `API_COLLECTION.json` aligned with `public/index.php` (manually or via `php scratch/update_postman.php` if that script is maintained in your checkout).
- Termination routes live under **05 Contracts → Termination settlement**.

### UAE PASS Button
- `handleUaePassSignature()` in `contract_details.php` shows a SweetAlert2 loading modal, waits 2 seconds, calls `POST /api/v1/company/contracts/sign`, then reloads the page on success.
- The dynamic timeline automatically re-renders with the new `active` status on reload.

---

## 📁 Most Important Files
| File | Why Important |
|---|---|
| `helpers/AppUrls.php` + `.env` | Correct URLs on any mount path or domain |
| `config/env.php` | Loads environment for DB and `LINKPROX_BASE_PATH` |
| `app/modules/Company/DashboardController.php` | Company dashboard APIs |
| `app/modules/Contracts/ContractController.php` | All contract business logic |
| `views/company/contract_details.php` | Main contract UI: timeline, chat, actions |
| `views/company/generate_contract.php` | Contract editor |
| `views/company/contract_review.php` | Legal document preview |
| `views/company/revision_review.php` | Revision comparison UI |
| `public/index.php` | API router |
| `resources/js/api.js` | JS API client |
| `language/en.php` + `language/ar.php` | All UI strings |
