# Company Portal Modules

The Company Portal is the primary interface for service providers. Controllers live in `app/modules/Company/`, `app/modules/Contracts/`, `app/modules/Requests/`, `app/modules/Quotations/`, and `app/modules/Payments/`.

---

## 1. Dashboard (`views/company/dashboard.php`, `views/company/activity.php`)
- **Stats / funnel:** `GET /api/v1/company/dashboard/stats` (`DashboardController`) — KPIs and funnel counts used by the dashboard cards.
- **Activity feed:** `GET /api/v1/company/dashboard/activity` — recent company-scoped events for `activity.php` or widgets.
- **Widgets (batched):** `GET /api/v1/company/dashboard/widgets` — one call for “requests requiring response”, recent requests, active contracts, and system activity snippets on the main dashboard.

---

## 2. Requests (`RequestController.php`)
Views: `requests.php`, `request_details.php`

- Company receives requests either `direct` (targeted) or `broadcast` (open tender).
- Endpoints: `GET /api/v1/requests`, `GET /api/v1/requests/count`
- **Chat** is embedded in `request_details.php` — uses `ChatController` via `GET /api/v1/chat/history?request_id=` and `POST /api/v1/chat/send`.
- Message timestamps display as "MMM DD, YYYY at HH:MM AM/PM".

---

## 3. Quotations (`QuotationController.php`)
Views: `quotations.php`, `create_quotation.php`

- Build line-item quotations with VAT and payment milestones.
- Can upload a PDF instead of building one in-system.
- Endpoints: `GET|POST /api/v1/company/quotations`, `POST /api/v1/company/quotations/upload`

---

## 4. Contracts — Full Lifecycle (`ContractController.php`)
Views: `contracts.php`, `contract_details.php`, `contract_roles.php`, `generate_contract.php`, `contract_review.php`, `revision_review.php`, `revision_sent.php`, `contract_termination_settlement.php`, `contract_settlement_reconciliation.php`, `contract_settlement_recalculate.php`

### Contract States & UI Flow

```
[Quotation Accepted]
       ↓
contract_roles.php          → Assign signing_representative + site_engineer
       ↓
generate_contract.php       → Edit scope, items, milestones, clauses
       ↓
contract_review.php         → Legal preview; Send only if version is draft (see below)
       ↓
  [status = under_review]   → Client reviews
       ↓
  ┌── Client Approves ──────────────────────────────────────────────────────┐
  │                                                                          │
  │    [status = pending_signature]                                          │
  │           ↓                                                              │
  │    contract_details.php  → Timeline shows "ACTION REQUIRED"             │
  │    Click "Sign with UAE PASS"  → POST /api/v1/company/contracts/sign    │
  │           ↓                                                              │
  │    [status = active]     → Execution phase begins                        │
  │           ↓                                                              │
  │    Termination (optional) → Settlement wizard → `termination_pending`    │
  │           → Reconciliation page → confirm → `terminated`                 │
  │                                                                          │
  └── Client Requests Revision ────────────────────────────────────────────┐
                                                                             │
       [status = revision_requested]                                         │
              ↓                                                              │
       revision_review.php   → Side-by-side comparison of old vs new        │
       Click "Review & Send Revision"                                        │
              ↓                                                              │
       generate_contract.php (mode=revision) → Edit the new version         │
              ↓                                                              │
       contract_review.php (mode=revision) → Preview revised doc            │
       Click "Send Contract"  → POST /api/v1/company/contracts/send         │
              ↓                                                              │
       revision_sent.php     → Confirmation page                             │
              ↓                                                              │
       [status = under_review again, version_no incremented]                 │
       (loop repeats until client approves)                                   │
```

**Role pickers (`contract_roles.php`):** the signing representative list targets **authorized agents**; the site engineer list targets **site engineer** staff, with fallbacks where the dataset is incomplete.

### Key API Endpoints for Contracts
| Endpoint | What It Does |
|---|---|
| `POST /api/v1/company/contracts` | Generate contract from a quotation |
| `GET /api/v1/company/contracts/review?contract_id=` | Returns full contract data + `timeline`; includes `version_status` (latest version `review_status`) |
| `GET /api/v1/company/contracts/details?contract_id=` | Contract meta for `contract_details.php` (split from review payload) |
| `GET /api/v1/company/contracts/timeline?contract_id=` | Timeline-only JSON |
| `GET /api/v1/company/contracts/messages?contract_id=` | Messages for the contract’s `request_id` |
| `POST /api/v1/company/contracts/upload` | Multipart upload for contract documents |
| `POST /api/v1/company/contracts/send?contract_id=` | Sends the latest **draft** `contract_versions` row (`review_status` → `sent_for_review`). If `version_no > 1`, it is a revision send. |
| `POST /api/v1/company/contracts/sign?contract_id=` | Simulate UAE PASS signature → sets status = active, signed_at, activated_at |
| `POST /api/v1/company/contracts/start-revision?contract_id=` | Creates new `version_no` as **draft**, copies from latest accepted line |
| `POST /api/v1/company/contracts/cancel-revision?contract_id=` | Deletes draft versions above `current_version_no` |
| `GET /api/v1/company/contracts/milestones?contract_id=` | List milestones |
| `GET /api/v1/company/contracts/milestones/details?milestone_id=` | Milestone detail |
| `POST` … `/milestones/request-payment`, `/send-reminder`, `/review` | Milestone workflow actions |
| `GET /api/v1/company/contracts/termination/settlement?contract_id=` | Financial snapshot + scenarios for termination UI |
| `POST /api/v1/company/contracts/termination/approve` | Approve settlement: body `contract_id`, `system_scenario` (`work_based` \| `refund_required` \| `outstanding_payment`), optional `adjustment_amount`, `adjustment_reason`, `reason` → sets `termination_pending` |
| `POST /api/v1/company/contracts/termination/reject` | Reject pending client termination request; may revert `termination_pending` → `active` |
| `GET /api/v1/company/contracts/termination/reconciliation?contract_id=` | Reconciliation payload for `termination_pending` contracts |
| `POST /api/v1/company/contracts/termination/confirm-settlement` | Finalize settlement → `terminated`, sets `terminated_at` |

### Contract review UI (`contract_review.php`)
- Footer **Send contract** is shown only when `version_status === 'draft'` (latest version not yet sent). Viewing an already-sent version hides the button; after **start revision** + edits, the new draft version shows it again.
- **Cancel** still returns to `generate_contract.php` with the same `contract_id` / `mode=revision` when applicable.

### Dynamic Timeline (contract_details.php)
The `getContractReviewData` endpoint returns a `timeline` array (same shape as `GET /api/v1/company/contracts/timeline`). The JS `renderTimeline()` function in `contract_details.php` renders it. Timeline event statuses:
- `completed` → green check
- `pending` → grey dashed
- `action-req` → yellow card with UAE PASS button
- `revision` → blue revision marker
- **`type: termination`** — appended when contract is `termination_pending` (amber “settlement” row), `terminated`, or `cancelled` (red terminated/cancelled badge). Uses `terminated_at` / `updated_at` from `contracts` where applicable.

### Contract details footer (`contract_details.php`)
When `status` is **`terminated`** or **`cancelled`**, the sticky footer hides **Withdraw contract** and **Revise contract**; the header shows a **Terminated** / **Cancelled** status badge (and contract number row). **Signing progress** sidebar shows an extra “contract ended” step for those statuses and for **`termination_pending`**.

### Postman
The collection file `API_COLLECTION.json` includes a **Termination settlement** folder under **05 Contracts** with the four termination routes above plus example JSON bodies.

### Messaging in contract_details.php
The Messages tab reuses the same `ChatController` as `request_details.php`. The chat is linked by the contract's `request_id` (not `contract_id`). This means conversations from the request stage persist into the contract stage seamlessly.

---

## 5. Catalog — Products (`CatalogController.php`)
Views: `catalog_products.php`, `catalog_add_product.php`, `catalog_edit_product.php`

- Products are company-scoped.
- Categories are **global** (`catalog_categories`) filtered by `type = 'product'`.

## 6. Catalog — Services (`ServiceController.php`)
Views: `catalog_services.php`, `catalog_service_add.php`, `catalog_service_edit.php`, `catalog_service_details.php`

- Services support multi-media (images + videos stored as JSON or linked rows).
- Categories filtered by `type = 'service'`.

---

## 7. Company Profile (`ProfileController.php`)
Views: `profile.php`, `legal_information.php`

- Update company name, address, logo, documents.
- `PUT /api/v1/company/profile/legal` — trade license, legal rep name.

---

## 8. Team Management
- `company_staff` — internal employees, can be assigned as `signing_representative` on a contract.
- `site_engineers` — specialized staff who update execution progress. Assigned on `contract_roles.php`.

---

## 9. Settings & Security (`SettingsController.php`)
Views: `settings.php`, `security.php`, `notification_settings.php`

- Account preferences, password change, 2FA.
- `POST /api/v1/company/deactivate-request` — sends a deactivation request for admin review.

---

## 11. Execution Control (`ExecutionController.php`)
Views: `execution_control.php`

- **Stage Management**: Define execution stages (Owner only), reorder them, or delete empty stages.
- **Progress Reporting**: Site engineers upload evidence (notes + photos) for specific stages.
- **Customer Review**: Customer reviews submissions via the mobile app; status updates to `completed` or `rejected`.
- **Extension Requests**: Site engineers can request deadline extensions; customers must approve or reject them.
- **Overall Progress**: Dynamic percentage calculation reflects on the contract details and timeline.
