# SmartFlow AI — Implementation Plan

This plan is derived from SMARTFLOW-AI-BLUEPRINT.md. It defines the perfect implementation order and an autoinstaller whose **first step** is environment verification (PHP version, extensions, permissions); no later steps run until that passes.

**Installation is fully achievable through the web UI.** No command-line steps are required for install; open `/install` in the browser and complete the steps there.

---

## 1. Autoinstaller Design (First Step Enforced)

The installer is exposed at `/install` and is **step-gated**: Step 1 must succeed before Step 2 is available.

### Step 1 — Environment check (mandatory first step)

Before any DB, license, or admin setup:

- **PHP version**: Require PHP >= 8.2 (e.g. `version_compare(PHP_VERSION, '8.2.0', '>=')`).
- **Required extensions** (fail if any missing):
  - Core: `pdo`, `pdo_mysql`, `mbstring`, `openssl`, `tokenizer`, `xml`, `ctype`, `json`, `bcmath`, `fileinfo`, `curl`
  - Optional but recommended: `redis` (if using Redis queue)
- **Permissions**: Check that these are writable (or creatable):
  - `storage/` and `storage/framework/{sessions,views,cache}`
  - `bootstrap/cache/`
  - `.env` (or parent directory writable so installer can create it)

**UI behavior**: Single "Environment check" screen with a "Verify" (or "Check") action. Display a clear pass/fail list (PHP version, each extension, each path). **"Next" / "Continue" is disabled until all checks pass.** No route or button to skip to Step 2.

**Implementation**: A dedicated `EnvironmentCheckService` or `InstallationStep1Service` used by the installer controller. The same checks are also available via `php artisan install:check-env` for support/debugging only; the normal installation flow is entirely through the web UI.

### Steps 2–6 (only after Step 1 passes)

- **Step 2 — Database setup**: Collect DB host, port, name, user, password; test connection; optionally create DB if permitted.
- **Step 3 — SQL import**: Run migrations (preferred) or import `database/schema/install.sql` with FK checks disabled.
- **Step 4 — License activation**: Purchase code, validate with license server, store encrypted token.
- **Step 5 — Admin setup**: Admin name, email, password; create tenant + tenant_admin user (Argon2).
- **Step 6 — Lock installer**: Create `storage/installed.lock` and disable `/install` permanently.

Step 1 result can be stored in session or a temporary file so that revisiting `/install` doesn't allow jumping to Step 2 without passing Step 1 again (unless you explicitly allow "already verified" state in the same session).

---

## 2. High-Level Implementation Order (from blueprint)

| Phase  | Focus                                                      |
| ------ | ---------------------------------------------------------- |
| 1      | DB and tenancy (migrations, tenant_id, scopes, middleware) |
| 2      | Auth and RBAC                                              |
| 3      | Service layer (controllers call services only)             |
| 4      | AI module (provider interface, queue, states)              |
| 5      | Social integration (connect, schedule, publish)            |
| 6      | AI auto-reply (webhook, queue, tone, memory, knowledge)     |
| 7      | Knowledge system (upload, chunk, embeddings)               |
| 8      | Marketplace (products, orders, signed delivery)            |
| 9      | Billing and plan limits (PlanLimitMiddleware, JSON errors) |
| 10     | License (JWT RS256, cron, grace period)                     |
| **11** | **Installer (Step 1 = env check; then Steps 2–6)**          |
| 12     | UI (Material 3, tables, mobile)                            |
| 13     | QA and security                                            |

---

## 3. Key Technical Details

- **App structure**: Laravel 11+, modules under `app/Modules/` (Identity, Tenancy, AI, AIReply, AIKnowledge, Social, Marketplace, Funnel, Billing, Licensing, **Installer**).
- **Multi-tenancy**: Single DB; `tenant_id` (UUID) on all business tables; global scope + TenantResolutionMiddleware; no cross-tenant access.
- **Installer module**: Routes, controllers, and services for `/install`; Step 1 logic in a dedicated service; session or temp state to allow "proceed" only after Step 1 pass.
- **Lock**: After Step 6, create `storage/installed.lock` and disable installer routes (e.g. middleware or route condition).
- **Security**: No plaintext secrets; encrypted API tokens; hashed purchase codes; CSRF; rate limit license attempts; parameter binding only.

---

## 4. Deliverables

1. **Implementation plan MD file**: This file in the project root for reference.
2. **Autoinstaller**: 6-step installer with **Step 1 as a mandatory gate** (PHP >= 8.2, required extensions, writable directories). No proceeding to Step 2 until Step 1 passes. Entire installation is done through the web UI; no command line required.
3. **Environment check**: Run from the installer UI (Step 1). Same checks are also available via `php artisan install:check-env` for support/debugging only.

---

## 5. Diagram — Installer Flow

```mermaid
flowchart LR
  subgraph step1 [Step 1 - Env Check]
    A[PHP >= 8.2]
    B[Extensions]
    C[Permissions]
    A --> D{All pass?}
    B --> D
    C --> D
  end
  D -->|No| E[Show errors / block Next]
  D -->|Yes| F[Enable Next]
  F --> G[Step 2 DB]
  G --> H[Step 3 SQL]
  H --> I[Step 4 License]
  I --> J[Step 5 Admin]
  J --> K[Step 6 Lock]
```
