# Deploying BeAuthentic on cPanel

BeAuthentic runs on ordinary cPanel shared hosting: **no Redis, Docker, Node.js, Supervisor or long-running workers.** One cron entry drives everything in the background.

## Quick install with the web wizard (recommended)

No terminal needed.

1. **Make the release zip** on your computer: `./scripts/package-release.sh` creates `dist/beauthentic-YYYYMMDD-HHMM.zip`. It contains production dependencies and built assets, and no `.env`.
2. **PHP:** in cPanel → *MultiPHP Manager*, set the domain to **PHP 8.3+**. Run *SSL/TLS Status → AutoSSL* so the site has HTTPS.
3. **Database:** in cPanel → *MySQL® Databases*, create a database and a user, then *Add User To Database* with **ALL PRIVILEGES**. Note the names (they include your cPanel prefix) and the password.
4. **Upload and extract the zip:**
   - **Addon or subdomain**, or any domain whose document root you can change: extract to `/home/cpuser/beauthentic`, then set the domain's *Document Root* to `/home/cpuser/beauthentic/public`.
   - **Main domain with a fixed `public_html`:** extract the zip *into* `public_html`. The included root `.htaccess` sends every request to `/public`, so your code and `.env` are never downloadable. The wizard double-checks this.
5. **Open `https://your-domain/install`.** The wizard asks for a one-time setup key; open the file it names in *File Manager* and copy the key. It then walks you through:
   - **Requirements:** PHP version, extensions, folder permissions, HTTPS, and private files staying hidden.
   - **Site & database:** your details are tested before anything is saved, and `.env` is written for production.
   - **Create tables.**
   - **Admin account:** optionally loads the starter catalogue.
   - **Email:** sends a real test before saving your SMTP settings.
   - **Paystack keys:** the secret key is checked with Paystack. This step also covers the Cloudflare option and generates the backup encryption password.
   - **Finish:** creates the storage link, optimises the store, and switches the installer off permanently.
6. **Add the cron job** the final screen shows you (cPanel → *Cron Jobs* → *Once Per Minute*). Then add the Paystack webhook URL it shows.
7. **Sign in at `/admin`** and open *Admin → System*. Once cron has run, every check should be green.

**To run the installer again**, for example on a new server, delete `storage/app/installed.lock` and `.env`. The wizard only works for someone who can read the setup key from the server.

## Deploying from GitHub with cPanel Git™ Version Control

This replaces uploading zips. Push to GitHub, then press one button in cPanel. The repository's `.cpanel.yml` runs `scripts/cpanel-deploy.sh`, which:

- copies the code into the app folder, never touching `.env`, `storage/` (uploads, logs, backups) or `public/storage`;
- runs `composer install --no-dev` with PHP 8.3+, downloading Composer if the host has none;
- once the store is installed, puts it into maintenance mode, migrates, re-caches and brings it back online (it comes back online even if a step fails);
- on the first deploy, leaves everything ready for the `/install` wizard;
- refuses to deploy into a folder holding anything other than BeAuthentic, so it can't wipe an existing `public_html` site.

### One-time setup

1. **Give cPanel read access to the private GitHub repo** with a *deploy key*:
   1. cPanel → *SSH Access* → *Manage SSH Keys* → **Generate a New Key**. Leave the password empty, otherwise cPanel can't use the key.
   2. Next to the new key, click *Manage* → **Authorize**. Then *View/Download* the **public** key and copy it.
   3. GitHub → `thehivemediang/beauthentic` → *Settings* → *Deploy keys* → **Add deploy key**. Paste the key and leave "Allow write access" **off**.
2. **Clone.** In cPanel → *Git™ Version Control* → **Create**:
   - *Clone URL:* `git@github.com:thehivemediang/beauthentic.git`
   - *Repository Path:* `/home/cpuser/repositories/beauthentic`. This is just the clone, so keep it **outside** `public_html`.
   - *Repository Name:* `beauthentic`

   If cloning fails with "Host key verification failed", open cPanel → *Terminal* once and run `ssh-keyscan github.com >> ~/.ssh/known_hosts`. If your plan has no Terminal, ask your host to run it.
3. **Choose where the live app goes.** The default is `/home/cpuser/beauthentic`; point the domain's *Document Root* at its `public` folder. To use `public_html` instead (main domain), create a file named `.beauthentic-deploy-path` in your home folder containing `/home/cpuser/public_html`. The deploy refuses to run if that folder holds another site's files.
4. **First deploy.** *Git™ Version Control* → *Manage* → *Pull or Deploy* → **Deploy HEAD Commit**. Then open `https://your-domain/install` and follow the wizard above (steps 2–7).

### Every update

1. Changes are pushed to `main` on GitHub.
2. In cPanel → *Git™ Version Control* → *Manage* → *Pull or Deploy*, press **Update from Remote**, then **Deploy HEAD Commit**.
3. *Admin → System* confirms the store is healthy. The deploy output appears under *Last Deployment Information*.

To roll back, check out the previous commit in the cPanel clone (or revert it on GitHub), then deploy again. If that release added migrations, see *Rollback* below.

---

The sections below are the manual (SSH) route and reference for everything the wizard sets up.

---

After every deploy, run **`php artisan beauthentic:doctor`** (or open **Admin → System**). It checks PHP, extensions, the environment, caches, the database, storage, cron, the queue, backups, email, Paystack and AI, and tells you exactly what to fix.

---

## 1. Requirements

| | |
|---|---|
| PHP | **8.3 or newer** (cPanel → *MultiPHP Manager*) |
| PHP extensions | `bcmath`, `ctype`, `curl`, `dom`, `fileinfo`, `gd` (with WebP), `intl`, `mbstring`, `openssl`, `pdo_mysql`, `tokenizer`, `xml`, `zip` (cPanel → *Select PHP Version → Extensions*) |
| PHP settings | `memory_limit` ≥ 256M, `upload_max_filesize` and `post_max_size` ≥ 10M, `max_execution_time` ≥ 60 (cPanel → *MultiPHP INI Editor*) |
| Database | MySQL 8.0+ or MariaDB 10.6+ |
| Disk | 2 GB+ free (uploads, backups) |
| SSL | AutoSSL or any valid certificate — HTTPS is required |

Node.js is **not** needed on the server: assets are built on your computer (`npm run build`) and uploaded with the app.

## 2. Prepare the release (on your computer)

```bash
composer install --no-dev --optimize-autoloader   # use the same PHP major version as the server
npm ci && npm run build                           # creates public/build
zip -r beauthentic.zip . -x "node_modules/*" ".git/*" "storage/logs/*" "storage/app/backups/*" ".env" "tests/*"
```

The zip must contain `vendor/` and `public/build/`. It must **not** contain `.env`.

## 3. Database

cPanel → **MySQL® Databases**:

1. Create a database, e.g. `cpuser_beauthentic`.
2. Create a user with a long generated password.
3. *Add User To Database* → **ALL PRIVILEGES**.

## 4. Upload and set the document root

1. cPanel → **File Manager**: upload `beauthentic.zip` to your home directory (e.g. `/home/cpuser/`), *not* `public_html`, and extract it to `/home/cpuser/beauthentic`.
2. cPanel → **Domains** → your domain → *Document Root* = `/home/cpuser/beauthentic/public`.

**If you can't change the document root:** move the contents of `beauthentic/public/` into `public_html/`, then edit `public_html/index.php` so its two paths point to `__DIR__.'/../beauthentic/vendor/autoload.php'` and `__DIR__.'/../beauthentic/bootstrap/app.php'`. The app code stays outside the web root either way.

## 5. Environment (`.env`)

Copy `.env.example` to `.env` (File Manager → *Copy*, then *Edit*). Every variable is described in [ENVIRONMENT.md](ENVIRONMENT.md). The minimum for production is:

```dotenv
APP_ENV=production
APP_DEBUG=false
APP_URL=https://beauthentic.ng
LOG_LEVEL=warning

DB_CONNECTION=mysql
DB_HOST=localhost
DB_DATABASE=cpuser_beauthentic
DB_USERNAME=cpuser_beauthentic
DB_PASSWORD=…

# Behind Cloudflare? Uncomment so HTTPS and visitor IPs are detected:
# TRUSTED_PROXIES=*

MAIL_MAILER=smtp
MAIL_HOST=mail.beauthentic.ng
MAIL_PORT=465
MAIL_SCHEME=smtps
MAIL_USERNAME=hello@beauthentic.ng
MAIL_PASSWORD=…
MAIL_FROM_ADDRESS=hello@beauthentic.ng

PAYSTACK_PUBLIC_KEY=pk_live_…
PAYSTACK_SECRET_KEY=sk_live_…

SEED_ADMIN_EMAIL=you@beauthentic.ng
SEED_ADMIN_PASSWORD=…        # remove after the first deploy

BACKUP_DISK=s3               # off-site copy — see section 11
BACKUP_ARCHIVE_PASSWORD=…    # encrypts backups (they contain customer data)
```

Leave `SESSION_SECURE_COOKIE` unset: cookies are HTTPS-only automatically when `APP_ENV=production`. Then lock the file down: File Manager → `.env` → *Permissions* → **600**.

## 6. Install

### Preferred: SSH or cPanel → Terminal

```bash
cd ~/beauthentic
php artisan key:generate --force     # first deploy only
php artisan migrate --force
php artisan db:seed --force          # first deploy only: admin, colours, catalogue, pages
php artisan storage:link
php artisan optimize                 # caches config, routes, events, views
php artisan beauthentic:doctor
```

### Without SSH (cron one-offs)

Many hosts include **cPanel → Terminal** even without SSH, so check for it first. If there's no terminal at all, run each command once through **Cron Jobs**:

1. Add a cron job set to *Once Per Minute* with the command:
   `cd /home/cpuser/beauthentic && /usr/local/bin/php artisan migrate --force >> storage/logs/deploy.log 2>&1`
2. Wait a minute, check `storage/logs/deploy.log` in File Manager, then **delete that cron job**.
3. Repeat for `key:generate --force` (first deploy), `db:seed --force` (first deploy), `storage:link`, `optimize` and `beauthentic:doctor`.

The PHP path is shown under *Cron Jobs → Common Settings* or *MultiPHP Manager*. On many hosts it's `/usr/local/bin/php` or `/opt/cpanel/ea-php83/root/usr/bin/php`.

## 7. Permissions

`storage/` and `bootstrap/cache/` must be writable by PHP. With suPHP/LSAPI/PHP-FPM (the cPanel default) the owner is your cPanel user, so **755 for folders and 644 for files** is enough. Never use 777. `.env` should be 600.

## 8. Cron — the only background setup

cPanel → **Cron Jobs** → *Once Per Minute* (`* * * * *`):

```
cd /home/cpuser/beauthentic && /usr/local/bin/php artisan schedule:run >> /dev/null 2>&1
```

That single entry runs everything below. *Admin → System → Scheduled & failed jobs* shows the last successful run of each task and flags any that are overdue.

| Task | When | What it does |
|---|---|---|
| heartbeat | every minute | proves cron is working |
| `queue:work --stop-when-empty` | every minute | sends queued emails and runs AI jobs (no worker needed: `QUEUE_PROCESSING_STRATEGY=cron`) |
| `outbox:dispatch` | every minute | delivers CRM events and campaign webhooks, with retries |
| `orders:expire-unpaid` | every 5 min | re-checks Paystack, then releases stock held by abandoned payments |
| `ai:cleanup` | every 15 min | deletes AI originals after the retention window; expires unsaved results |
| `carts:process-abandoned` | hourly | flags bags left behind (the "Bag left behind" campaign trigger); prunes old guest bags |
| `campaigns:housekeep` | hourly | switches off campaigns that have ended (date windows apply live anyway) |
| `backup:run` | 01:30 | database + media backup, off-site copy, retention |
| `analytics:aggregate` | 02:00 | nightly daily rollups for fast long-range charts |
| `loyalty:expire` | 02:30 | expires old points and unused reward codes |
| `creators:approve-commissions` | 03:00 | makes commissions payable after the return window |
| `queue:prune-failed`, `model:prune` | daily | housekeeping |

**Queue alternative:** if your host allows a persistent worker (e.g. via Supervisor), set `QUEUE_PROCESSING_STRATEGY=worker` and run `php artisan queue:work --tries=3`. The cron strategy is the default because shared hosting usually forbids long-running processes.

## 9. SSL and HTTPS

cPanel → **SSL/TLS Status** → *Run AutoSSL*. Plain-HTTP page requests then redirect to HTTPS automatically in production. HSTS is sent on HTTPS responses. If you use Cloudflare, set its SSL mode to **Full (strict)** and add `TRUSTED_PROXIES=*`.

## 10. Services

**Paystack** (Dashboard → Settings → API Keys & Webhooks)
- Copy the live keys into `.env`.
- Webhook URL: `https://YOUR-DOMAIN/webhooks/paystack`
- Callback URL: `https://YOUR-DOMAIN/checkout/callback` (the default if `PAYSTACK_CALLBACK_URL` is empty).
- Test once with test keys before switching to live.

**Email (SMTP)**
- Use a cPanel mailbox (*Email Accounts* → *Connect Devices* shows the host and port), or a provider such as Mailgun, Postmark or Zoho.
- Add SPF and DKIM records (cPanel → *Email Deliverability*) or mail lands in spam.
- *Admin → Integrations → Emails* logs every send and failure.

**AI try-on** ([AI.md](AI.md))
- Set `AI_PROVIDER` (`openai` or `replicate`), `AI_API_KEY` and `AI_PROVIDER_MODEL`.
- Replicate also needs `AI_WEBHOOK_SECRET`, and its webhook goes to `https://YOUR-DOMAIN/webhooks/ai/replicate`.
- Then set limits, cost and budget in *Admin → AI Try-On*. Leave `AI_PROVIDER=disabled` until you have keys.

**CRM (optional)** ([ENVIRONMENT.md](ENVIRONMENT.md))
- `CRM_DRIVER=webhook` or `fluentcrm`.
- For inbound unsubscribes and tags: set `CRM_INBOUND_SECRET` and point the CRM at `https://YOUR-DOMAIN/webhooks/crm`.
- *Admin → Integrations → Send test event* confirms the connection.

## 11. Backups & recovery

cPanel's own backups are a useful extra, but they live with the same host. BeAuthentic therefore makes its own backups and copies them off-site.

**What's backed up nightly (01:30)**
- One zip: `database.sql` (a portable dump made in PHP, so no `mysqldump` is needed) plus all uploaded media (product images, Wall photos).
- AI previews are excluded on purpose. They're temporary by design, and backups must not outlive their deletion window.
- If `BACKUP_ARCHIVE_PASSWORD` is set, the archive is **AES-256 encrypted** and also contains a copy of `.env`. Without a password, `.env` is never included.
- Archives are kept for `BACKUP_KEEP_DAYS` (default 14), locally in `storage/app/backups` and on `BACKUP_DISK`.

**Off-site copy (recommended).** Create a bucket in Cloudflare R2, Backblaze B2, Wasabi or AWS S3, then set:

```dotenv
BACKUP_DISK=s3
AWS_ACCESS_KEY_ID=…
AWS_SECRET_ACCESS_KEY=…
AWS_DEFAULT_REGION=auto
AWS_BUCKET=beauthentic-backups
AWS_ENDPOINT=https://<account>.r2.cloudflarestorage.com   # R2 / B2 / Wasabi
AWS_USE_PATH_STYLE_ENDPOINT=true
```

Use a bucket-scoped key that can only write to that bucket.

**Configuration backup.** Keep `.env`, especially `APP_KEY`, in a password manager as well. **Without the original `APP_KEY`, encrypted data (creator bank account numbers) can't be decrypted after a restore.**

*Admin → System → Backups* has "Back up now", a list of archives and logged downloads. To run one from the command line: `php artisan backup:run` (add `--db-only` to skip media).

### Restoring

1. **Get the archive.** Use *Admin → System → Backups* if the site is up, otherwise take it from the off-site bucket. If it's encrypted, unzip it with the password using 7-Zip, Keka or `unzip -P`.
2. **Database.** In cPanel → **phpMyAdmin**, select the (empty or old) database → *Import* → choose `database.sql` → *Go*. The dump drops and recreates each table. For files over phpMyAdmin's upload limit, use Terminal: `mysql -u USER -p DBNAME < database.sql`.
3. **Media.**
   - Upload `media/public/*` to `storage/app/public/`.
   - Upload `media/private/*` to `storage/app/private/media/`.
4. **Configuration.** Restore `.env` from the encrypted archive (`config/.env`) or your password manager, keeping the original `APP_KEY`.
5. **Finish.** Run `php artisan optimize:clear && php artisan optimize && php artisan beauthentic:doctor`.

**Test a restore every few months** on a staging subdomain. An untested backup isn't a backup.

## 12. Updating a live store

```bash
# 1. Put up the maintenance page (or use Admin → System → Maintenance mode — it gives you a bypass link)
php artisan down --render="errors::503" --retry=60
# 2. Back up first
php artisan backup:run
# 3. Upload the new release over the old files (keep .env and storage/), or git pull
# 4. Apply
php artisan migrate --force
php artisan optimize:clear && php artisan optimize
php artisan beauthentic:doctor
php artisan up
```

If you deploy without SSH, run the step 4 commands as cron one-offs (section 6).

### Rollback

1. Re-upload the previous release zip; keep releases as `beauthentic-YYYYMMDD.zip`.
2. If the failed release ran migrations, either run `php artisan migrate:rollback --step=N`, where N is the number of new migrations (every migration has a working `down()`), or restore the database from the backup taken in step 2.
3. Run `php artisan optimize:clear && php artisan optimize && php artisan up`.

**Safer variant (folder per release).**
- Extract each release to `~/releases/YYYYMMDD` and point a symlink `~/beauthentic` at it, sharing `.env` and `storage/` via symlinks.
- Rolling back is then just re-pointing the symlink.

## 13. Production checklist

- [ ] `beauthentic:doctor` shows **0 problems**
- [ ] `APP_ENV=production`, `APP_DEBUG=false`, `APP_URL` is https
- [ ] `php artisan optimize` has run (config, routes, events, views cached)
- [ ] Cron job added; the System page shows a recent heartbeat
- [ ] Paystack live keys, webhook URL and a ₦100 test order; refund it from Admin → Orders
- [ ] SMTP sends (register a test account and receive the welcome email)
- [ ] Backup ran, **off-site copy present**, archive password set, a test restore has been done
- [ ] `SEED_ADMIN_PASSWORD` removed from `.env` after the first deploy; admin password changed
- [ ] `.env` permissions 600; no `.env` in `public_html`
