CLIENT PORTAL CRM — STAGE 4
===========================
Stack: PHP 8+, MySQL/MariaDB, Tailwind CSS CDN, vanilla PHP/JS.

UPGRADING FROM STAGE 3
----------------------
1. Back up your database and clientportal folder.
2. Replace the Stage 3 PHP files with this Stage 4 folder.
3. Import database/upgrade_stage3_to_stage4.sql into the existing clientportal database.
4. Do NOT import schema.sql over an existing install.

FRESH INSTALL
-------------
Import database/schema.sql, visit /clientportal/create_admin.php, create the admin, then delete/rename create_admin.php.

STAGE 4 ADDS
------------
- Reusable templates (proposal, contract, invoice, Smart File, email)
- Admin/client appointment scheduling views
- In-app client notifications, with optional PHP mail() email delivery
- Per-invoice hosted payment links for Stripe, PayPal, or any external checkout
- Client-facing Pay Online buttons and payment history
- Invoice-ready notification action
- Settings for business name, From email, email notifications, and default payment destinations
- Stage 3 features remain: proposals, signatures, invoices, payment tracking, files, messaging and Smart Files

PAYMENTS — IMPORTANT
--------------------
Stage 4 supports hosted payment links and records payments in the CRM. It does NOT automatically verify Stripe/PayPal transactions or process raw card data inside this app. For production card payments, use Stripe/PayPal hosted checkout and add signed webhooks before automatically marking invoices paid. Never store card numbers/CVV in this database.

EMAIL
-----
Email notifications use PHP mail() when enabled in Admin > Settings. Local XAMPP usually needs an SMTP/sendmail configuration before email will actually leave your machine. In-app notifications do not require email.

PRODUCTION
----------
Use HTTPS, production DB credentials, secure session cookies, rate limiting, password reset/email verification, backups, uploads outside public web root, SMTP with authenticated delivery, and verified Stripe/PayPal webhooks before automatic payment status changes.


STAGE 5 - VERIFIED PAYMENTS + AUTOMATION
--------------------------------------
Upgrade an existing Stage 4 database with:
  database/upgrade_stage4_to_stage5.sql

New:
- Stripe webhook signature verification (HMAC signing secret)
- PayPal webhook verification through PayPal's verify-webhook-signature API
- Idempotent payment processing (duplicate callbacks are safe)
- Automatic invoice Paid/Partial status updates
- Automatic Smart File invoice-step completion after full payment
- In-app/email payment receipt notification
- Admin Webhook Event Log
- Provider event/transaction IDs stored with payment records

Stripe webhook URL:
  https://YOUR-DOMAIN/clientportal/webhooks/stripe.php
Recommended Stripe events:
  checkout.session.completed
  checkout.session.async_payment_succeeded
  payment_intent.succeeded

Matching a Stripe payment to an invoice:
1. Best: send invoice_id or invoice_number in Stripe metadata, OR
2. On the invoice's payment link in Admin, enter the Stripe Payment Link ID (plink_...) in External Reference.

PayPal webhook URL:
  https://YOUR-DOMAIN/clientportal/webhooks/paypal.php
Recommended PayPal event:
  PAYMENT.CAPTURE.COMPLETED

In Admin > Settings enter PayPal Client ID, Client Secret, PayPal Webhook ID and Sandbox/Live mode.
Matching PayPal to an invoice uses invoice_id/custom_id, invoice_number, or the payment link External Reference.

SECURITY:
- Never expose webhook secrets or API secrets in client-side HTML.
- Use HTTPS in production.
- Keep webhook endpoints publicly reachable but protected by provider signature verification.
- XAMPP/localhost can test Stripe using Stripe CLI forwarding. PayPal requires a reachable HTTPS callback for normal webhook delivery.


STAGE 6
=======
Stage 6 adds the HoneyBook-style business workflow layer:
- Visual lead pipeline with New / Contacted / Qualified / Proposal / Won / Lost stages
- One-click lead conversion into a portal client
- Project tasks, priorities and milestones
- Recurring invoice schedules with Generate Now
- Reminder automation rules for overdue invoices, unsigned contracts and pending proposals
- Daily automation runner endpoint
- Dashboard lead/task counters

UPGRADE FROM STAGE 5
1. Back up your database and files.
2. Replace application files with Stage 6.
3. Import database/upgrade_stage5_to_stage6.sql into the existing clientportal database.
4. Log in as Admin.
5. Lead Pipeline, Tasks, Recurring and Automations will appear in navigation.

AUTOMATION CRON
Add a secure random cron_key to app_settings, for example:
INSERT INTO app_settings(setting_key,setting_value) VALUES('cron_key','REPLACE-WITH-LONG-RANDOM-SECRET')
ON DUPLICATE KEY UPDATE setting_value=VALUES(setting_value);

Then call /clientportal/cron/run_automations.php?key=YOUR_SECRET once daily from cron.
Do not expose the cron key publicly.

Recurring invoices are deliberately generated explicitly from Admin in this release so an accidental cron configuration cannot create unwanted invoices. They are ready to be automated in a later release.


STAGE 7
=======
Stage 7 is the commercial UI + advanced Smart Files release.

New:
- Redesigned admin navigation and responsive mobile Admin menu
- Cleaner branded client portal and mobile client navigation
- Modern client dashboard with active projects, Smart File actions, open invoices and recent updates
- Services & Packages catalog
- Smart File Package blocks: clients can select one approved package/service from inside the workflow
- Smart File visual journey builder with step cards and Up/Down reordering
- Package, form, proposal, contract, invoice, scheduler, upload and content steps in one workflow
- Business branding settings: business tagline, accent color and logo URL
- Project Workspace with client card, tasks, milestones, Smart Files and unified Stage 7 activity timeline
- Activity records for Smart File changes and package selections
- Fresh-install schema ordering corrected for project task/milestone foreign keys

UPGRADE FROM STAGE 6
1. Back up the database and application folder.
2. Replace application files with Stage 7.
3. Import database/upgrade_stage6_to_stage7.sql.
4. Go to Admin -> Settings to add business tagline, accent color and optional logo URL.
5. Go to Admin -> Services to create service/package choices.
6. Add a Package block inside a Smart File to let a client choose a service.

IMPORTANT
- The Stage 7 upgrade does not delete Stage 6 CRM data.
- Package selection records are stored separately and linked to the Smart File block/client.
- Existing Smart Files continue working.
- Up/Down controls reorder Smart File steps without requiring an external JavaScript drag-and-drop library.
- Payment processing remains handled by the Stage 5+ webhook/payment architecture.


STAGE 8
=======
Stage 8 expands the platform toward a full HoneyBook-style workflow system.

NEW IN STAGE 8
- Permanent fix for the Stage 7 exposed log_activity() helper. PHP-only functions.php no longer closes PHP before that function.
- Smart File HTML5 drag-and-drop reordering with a CSRF-protected reorder endpoint.
- Service package quantities.
- Service package add-ons.
- Smart File package steps can automatically generate a proposal, an invoice, or both when a client chooses a service.
- Generated proposal/invoice IDs are saved with the client's package selection.
- Public lead capture page: /clientportal/lead-form.php
- Public lead submissions enter the Lead Pipeline as New leads.
- Project Templates with reusable project defaults and task checklists.
- New projects can be created from Project Templates.
- Workflow Templates for reusable Smart File journeys.
- New Smart Files can copy an existing Workflow Template.
- Reports dashboard with leads, won leads, active projects, payments, outstanding amount, monthly revenue and pipeline counts.
- Stripe webhook processing hardened to canonical paid Checkout Session events to reduce duplicate payment recording.
- Provider transaction ID duplicate checks added before recording verified payments.
- Fresh-install schema table ordering corrected for project foreign keys.

UPGRADE FROM STAGE 7
1. Back up your clientportal database and application folder.
2. Replace the Stage 7 application files with Stage 8.
3. Import:
   database/upgrade_stage7_to_stage8.sql
4. Log in as Admin.
5. Open Services to create packages with optional quantities and add-ons.
6. Open Project Templates to create reusable project/task setups.
7. Open Workflow Templates to create reusable Smart File journeys.
8. Create a Smart File and enable Auto Proposal and/or Auto Invoice on a Package step when desired.

PUBLIC LEAD FORM
The included public inquiry form is:
  /clientportal/lead-form.php

It includes:
- CSRF protection
- basic server-side validation
- a honeypot field for simple bot filtering
- automatic insertion into the Lead Pipeline

SMART FILE AUTO-GENERATION
For Package blocks, Admin may enable:
- Auto-create proposal
- Auto-create invoice

When the client selects the service, selected quantity and add-ons are copied into generated line items. The proposal/invoice is linked to the same client/project.

STRIPE NOTE
Stage 8 processes:
- checkout.session.completed
- checkout.session.async_payment_succeeded

It intentionally ignores payment_intent.succeeded and charge.succeeded in this webhook implementation to avoid counting the same Checkout payment through multiple Stripe event families.

VALIDATION
Run the SQL migration once on an existing Stage 7 database. The fresh database/schema.sql is for new installs only.


STAGE 9
=======
Stage 9 focuses on automation reliability, recurring billing workflows, client onboarding visibility, and client-facing history.

New:
- Reliable daily automation deduplication using automation_log.run_date.
- Lead follow-up automations now run and notify the first admin account.
- Automation rules may use reusable Email templates.
- Automation rules can be paused/reactivated.
- Cron key is now managed in Admin -> Settings.
- Recurring invoice schedules can auto-generate from the daily cron runner.
- Recurring invoice schedules can be paused and Auto mode toggled.
- Client lifecycle status: onboarding, active, paused, completed.
- Client admin page now includes a consolidated activity timeline.
- Client portal Activity page.
- Client portal Notifications page with Mark All Read.
- Template deletion changed from GET to POST + CSRF.
- Recurring invoice generation uses the shared unique invoice-number helper.
- Existing Stage 8 Smart Files, service packages, workflow templates, project templates, lead capture, reporting, Stripe/PayPal and project workspaces remain available.

UPGRADE FROM STAGE 8
1. Back up your database and clientportal folder.
2. Replace application files with Stage 9.
3. Import database/upgrade_stage8_to_stage9.sql ONCE.
4. Open Admin -> Settings and set a long random Cron Key.
5. Schedule the daily endpoint:
   /clientportal/cron/run_automations.php?key=YOUR_SECRET
6. In Recurring Invoices, enable Auto for schedules you want generated automatically.
7. In Automations, create reminder rules and optionally select an Email template.

IMPORTANT
- Do not import database/schema.sql over an existing installation.
- The migration preserves existing Stage 8 records.
- The cron runner should be protected with a long, unguessable secret.
\n\nSTAGE 10\n========\nStage 10 is a production-readiness and client-access hardening release.\n\nNEW IN STAGE 10\n- Secure client invite/password setup flow.\n- One-time invite tokens are hashed in the database and expire after 72 hours.\n- Admin can resend/reset a client portal invite from the client page.\n- New clients no longer expose temporary passwords in the admin UI.\n- Lead conversion now requires a valid email and refuses to reuse admin accounts.\n- Lead conversion refuses duplicate existing client accounts and creates an onboarding invite.\n- Appointment cancellation moved from GET to POST + CSRF.\n- Invoice and proposal line-item deletion moved from GET to POST + CSRF.\n- Smart File manual completion moved from GET to POST + CSRF.\n- Manual payments now update invoice status, sync Smart File invoice blocks, log activity and notify the client when paid.\n- Smart File brand color is restricted to a six-digit hex color before inline rendering.\n- Client Projects now show project milestones and task progress.\n- Expanded mobile Admin menu.\n- Existing Stage 9 automations, recurring invoices, reports, Smart Files, templates and payment webhooks remain available.\n\nUPGRADE FROM STAGE 9\n1. Back up your database and clientportal folder.\n2. Replace the application files with Stage 10.\n3. Import database/upgrade_stage9_to_stage10.sql ONCE.\n4. Existing client passwords keep working.\n5. For a client who needs portal access, open Admin -> Clients -> Open -> Send / Reset Portal Invite.\n\nCLIENT INVITE FLOW\nAdmin creates or converts a client -> a one-time invite is generated -> client opens /clientportal/setup-password.php?token=... -> client creates a password -> invite is invalidated and onboarding client becomes active.\n\nEMAIL NOTE\nWhen email notifications are enabled and PHP mail() is configured, invite emails are sent automatically. The admin interface also displays the generated invite path so it can be copied manually during testing.\n

STAGE 11
========
Stage 11 adds team access control, client invitation management, audit logging, and another production-readiness pass.

NEW IN STAGE 11
- Team accounts with role=staff.
- Granular server-side permissions for CRM sections.
- Team management page under Admin -> Team.
- Admin-only staff creation, permission changes, password resets, and account deletion.
- Client Invites management page with active/expired/used status and revocation.
- Audit Log page for login, staff/security changes, invites, settings changes, client portal activation, and verified payment webhook activity.
- Admin dashboard now shows active client invites and recent activity.
- Staff logins route into the admin workspace instead of the client portal.
- Stripe and PayPal verified payment events are added to the audit trail.
- Payment provider transaction lookup index added for faster duplicate checking.
- Sensitive settings no longer display stored webhook/cron secrets back into HTML forms.
- Blank secret fields preserve the existing saved secret; entering a new value replaces it.
- Existing Stage 10 secure client invitation/password setup remains intact.

TEAM PERMISSIONS
Staff access can be granted individually for:
- Dashboard
- Pipeline
- Clients & Invites
- Projects & Tasks
- Messages
- Proposals & Contracts
- Invoices & Recurring Billing
- Automations
- Files
- Calendar
- Services
- Templates
- Smart Files
- Reports
- Settings & Webhooks
- Audit Log

Permissions are enforced on the server in require_admin(), not only hidden from navigation.

UPGRADE FROM STAGE 10
1. Back up your database and application folder.
2. Replace the application files with Stage 11.
3. Import database/upgrade_stage10_to_stage11.sql ONCE.
4. Log in as the main Admin account.
5. Open Admin -> Team to add staff accounts and assign access.
6. Open Admin -> Client Invites to review or revoke active client invitations.
7. Open Admin -> Audit Log to review security and operational events.

SECURITY NOTES
- Only role=admin may manage Team accounts even if a staff account is somehow granted the team permission.
- Stored Stripe webhook secret, PayPal client secret, and Cron key are not echoed back into the Settings page.
- Client invite tokens remain hashed and time-limited.
- Stage 11 adds an index on provider/provider_transaction_id but keeps application-level duplicate checks for compatibility with existing records.

Do not import database/schema.sql over an existing installation.


STAGE 12
========
Stage 12 is the production-readiness authentication and account-security release.

NEW IN STAGE 12
- Forgot Password flow for admin, staff, and client accounts.
- One-time password reset tokens are SHA-256 hashed in the database.
- Reset links expire after 60 minutes and are invalidated after use.
- New reset requests invalidate previous unused reset tokens.
- Login CSRF protection.
- Login brute-force/rate limiting: 8 failed attempts in a rolling 15-minute window by email or IP.
- Login attempts stored for security review.
- Session ID regeneration after successful login.
- Hardened session cookies: HttpOnly, SameSite=Lax, Secure automatically when HTTPS is active.
- Safer logout clears the session and cookie.
- Common security response headers for authenticated pages and authentication flows.
- last_login_at tracking for users.
- Production/development environment setting.
- Development-only reset-link display when PHP email is disabled.
- Production Check page under Admin -> Settings.
- Existing Stage 11 staff permissions, audit logs, client invitations, payment verification, Smart Files, automations, recurring billing, reporting and workflow templates remain intact.

UPGRADE FROM STAGE 11
1. Back up your database and /clientportal folder.
2. Replace application files with Stage 12.
3. Import database/upgrade_stage11_to_stage12.sql ONCE.
4. Open Admin -> Settings.
5. Keep Application environment on Development while testing.
6. Test Forgot Password from the login page.
7. Configure working email delivery and set the Application environment to Production.
8. Run Admin -> Settings -> Production Check.
9. Verify HTTPS is enabled on the live domain.

PASSWORD RESET
Forgot-password page:
  /clientportal/forgot-password.php

Reset links:
  /clientportal/reset-password.php?token=...

Reset tokens expire after 60 minutes and are stored only as SHA-256 hashes.

LOGIN RATE LIMIT
After 8 failed attempts associated with an email or IP during a 15-minute window, login is temporarily blocked for that window.

EMAIL
The current application still uses the existing send_portal_email() transport. For local XAMPP testing, Stage 12 can display a reset link only while:
- app_environment = development
- email_notifications = off

Never rely on the development reset-link display in production.

PRODUCTION
Before launch:
- use HTTPS
- use a non-root MySQL application account with a strong password
- remove/disable create_admin.php after initial setup
- configure real outbound email
- use strong Stripe/PayPal/Cron secrets
- back up the database and uploads
- run the Production Check page

Do not import database/schema.sql over an existing installation.


STAGE 13 — RELEASE CANDIDATE 1
==============================
Version: 1.0.0-rc1

Stage 13 stops expanding the CRM feature set and focuses on deployment readiness.

New:
- SMTP email transport with TLS/SSL/authentication support.
- PHP mail() remains available as a fallback.
- Email delivery log.
- Send Test Email page.
- Public Site URL setting; invite/reset links now use absolute URLs.
- Environment-variable database configuration.
- Protected PHP application error log.
- Admin Error Log viewer/clear action.
- System Health page.
- Full SQL database backup export.
- Hardened first-run admin setup replacing fixed admin@example.com / Admin123! credentials.
- Expanded Production Check.
- VERSION and DEPLOYMENT.txt files.
- Apache directory listing disabled and protected internal folders.

Upgrade from Stage 12:
  database/upgrade_stage12_to_stage13.sql

Do not import the fresh schema over an existing database.
Read DEPLOYMENT.txt before putting RC1 on a public server.


HELP & USER MANUAL ENHANCEMENT
==============================
- Added Admin -> Help & Manual.
- Added Client Portal -> Help.
- Added contextual blue Tip panels across major admin and client screens.
- Added hover tooltip helper for future field-level ? hints.
- Added USER-MANUAL.pdf inside the application package.
- Admin manual explains the recommended Lead -> Client -> Project -> Smart File -> Proposal -> Contract -> Invoice/Payment workflow.
- Client help explains projects, messages, proposals, contracts, invoices, files, scheduling, Smart Files, notifications and account security.

No database migration is required for this help/manual enhancement.
