# cPanel Deployment Guide

## Prerequisites

- cPanel hosting with PHP 8.2+ and MySQL/MariaDB
- PHP extensions enabled: `pdo`, `pdo_mysql`, `mbstring`, `openssl`, `fileinfo`
- SSH access (recommended) or File Manager
- Domain name pointing to the hosting

## Step-by-Step Deployment

### 1. Upload Files

**Important:** this app's `asset()`/`base_url('public/...')` helper (`app/helpers/functions.php`) always builds asset URLs with a `/public/` path segment baked in — e.g. a stylesheet always resolves to `{APP_URL}/public/css/style.css`, regardless of where `public/index.php` physically lives relative to the web root. That means you must **not** flatten `public/`'s contents up into `public_html/` — doing so silently breaks every CSS/JS/image/upload/OG-image/manifest link on the live site (they'd all 404) without an accompanying code change. Instead, upload the **entire project tree intact** — `app/`, `config/`, `public/`, `routes/`, etc. all stay siblings — directly inside `public_html/` (or a subfolder of it).

**Option A — File Manager:**
1. Log in to cPanel
2. Open File Manager → `public_html`
3. Upload the project as a ZIP file and extract it, or extract first then upload the whole `AiWebReporter/` folder's *contents* (not the folder itself) directly into `public_html/`
4. Do **not** upload `temp_import/` or `.zcode/` — they're local dev/test scratch folders, not part of the app

**Option B — SSH/SFTP:**
```bash
scp -r AiWebReporter/ user@yourhost:~/public_html/
```

### 2. Set Document Root

Both options below keep the same internal folder layout (`app/`, `config/`, `public/`, `routes/`, `lib/`, `cron/`, `storage/`, `database/`, `.env` as siblings) — they differ only in whether there's a `/AiWebReporter/` URL prefix.

**Option A — Root domain install (recommended — clean URLs like `yourdomain.com/blog`):**

1. Upload the project directly into `public_html/`, so `public_html/index.php` does **not** exist, but `public_html/public/index.php`, `public_html/app/`, `public_html/config/`, etc. do.
2. Edit `public_html/.htaccess` (this is the project's existing root `.htaccess`, just with the hardcoded subdirectory path removed) so the first `RewriteCond` reads:
   ```apache
   RewriteCond %{REQUEST_URI} ^/public/
   ```
   instead of `^/AiWebReporter/public/`. Leave everything else in that file (gzip, caching headers, the `.env`/`.git`/`.sql` deny block) as-is.
3. Set `APP_URL=https://yourdomain.com` in `.env` (no path suffix).
4. Visiting `https://yourdomain.com/` now hits `public_html/.htaccess` → routes through `public_html/public/index.php`, while asset URLs correctly resolve to `https://yourdomain.com/public/css/style.css` etc., matching the physical file at `public_html/public/css/style.css`.

**Option B — Subdirectory install** (e.g., `yourdomain.com/AiWebReporter`) — identical, but keeps the folder one level deeper:
1. Upload the project into `public_html/AiWebReporter/` (so `public_html/AiWebReporter/public/index.php` exists).
2. Leave `public_html/AiWebReporter/.htaccess`'s `RewriteCond %{REQUEST_URI} ^/AiWebReporter/public/` line exactly as it already is — it already matches this layout.
3. Set `APP_URL=https://yourdomain.com/AiWebReporter` in `.env`.

Because `app/`, `config/`, `database/`, `routes/`, `lib/`, and `cron/` end up living inside the web-reachable `public_html/` under both options, their `.htaccess` `Require all denied` files (already present in the repo) are what keeps them from being served directly — verify each one survived the upload intact (step 6 below has a direct test for this).

### 3. Create MySQL Database

1. cPanel → **MySQL Databases**
2. Create database: `youruser_aiwebreporter`
3. Create database user with a strong password
4. Add user to database with **ALL PRIVILEGES**

### 4. Run Migrations

1. cPanel → **phpMyAdmin**
2. Select your database
3. Import each file **in this exact order** (SQL tab → Choose File → Go). The two files numbered `002` are independent of each other but both must come after `001` and the `002` seed:
   - `database/migrations/001_schema.sql`
   - `database/seeds/002_seed.sql` — roles, categories, and the default admin user
   - `database/migrations/002_approval_logs.sql`
   - `database/migrations/002_post_reactions.sql`
   - `database/migrations/003_bot_enhancements.sql`
   - `database/migrations/004_newsletter_system.sql`
   - `database/migrations/005_static_pages.sql`
   - `database/migrations/006_comments.sql`
   - `database/migrations/007_comments_guest.sql`
   - `database/migrations/008_security_phase1.sql`
   - `database/migrations/009_performance_indexes.sql`
   - `database/seeds/003_sample_posts.sql` — **optional**, demo/placeholder articles only. Skip this on a real production site unless you want sample content to review the design with.

   > `001_schema.sql` contains its own `CREATE DATABASE` statement — if phpMyAdmin errors on that line because your cPanel user lacks `CREATE DATABASE` privilege, just delete that one line and the following `USE` line, then import into the database you already created in step 3.

4. **Change the seeded admin password immediately.** `seeds/002_seed.sql` creates `admin@aiwebreporter.com` with a password hash that ships in this repo/guide — treat it as a known/compromised credential. Generate a fresh hash locally:
   ```bash
   php -r "echo password_hash('YourNewStrongPassword', PASSWORD_BCRYPT, ['cost' => 12]);"
   ```
   Then in phpMyAdmin, update the `users` table row for `admin@aiwebreporter.com`, setting `password_hash` to the new value — do this before the site is publicly reachable.

### 5. Configure Application

The app reads configuration from a `.env` file (via `config/env.php` → `config/config.php`), **not** by editing `config/config.php` directly. Copy `.env.example` to `.env` at the project root (alongside `app/`, `config/`, `public/` — see step 2) and fill in:

```ini
APP_NAME="AI Web Reporter"
APP_URL=https://yourdomain.com
APP_TIMEZONE=UTC
APP_DEBUG=false

DB_HOST=localhost
DB_PORT=3306
DB_NAME=youruser_aiwebreporter
DB_USER=youruser_dbuser
DB_PASS=your_strong_password

MAIL_DRIVER=smtp
MAIL_HOST=mail.yourdomain.com
MAIL_PORT=587
MAIL_USERNAME=noreply@yourdomain.com
MAIL_PASSWORD=your_email_password
MAIL_ENCRYPTION=tls
MAIL_FROM_EMAIL=noreply@yourdomain.com
MAIL_FROM_NAME="AI Web Reporter"

SESSION_NAME=AIWR_SESSION
SESSION_LIFETIME=7200
SESSION_SECURE=true

CRON_SECRET=generate_a_long_random_string_here
BACKUP_DIR=
BACKUP_RETENTION_DAYS=30
```

Leave `OPENAI_API_KEY` / `ANTHROPIC_API_KEY` / keyword API vars blank unless you're enabling the AI content pipeline (Stage 5) now — they aren't required for the site to go live.

**Never upload `.env.example` values as-is, and never commit `.env` to version control** — `.gitignore` already excludes it.

### 6. Set File Permissions

Via SSH (run from `public_html`, or `public_html/AiWebReporter` for the subdirectory install):
```bash
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod 755 public/uploads/
chmod 600 .env
```

Or via cPanel File Manager: right-click folders → Change Permissions.

`app/`, `config/`, `database/`, `routes/`, `lib/`, and `cron/` sit inside the web-reachable `public_html/` (see step 2), so the `Require all denied` in each folder's `.htaccess` is what actually keeps them from being served — confirm each one made it through the upload intact. Quick test after deploying: browse to `/app/`, `/config/`, `/database/`, `/routes/`, `/lib/`, `/cron/`, and `/.env` off your site root (prefix with `/AiWebReporter` if you used the subdirectory install) — every one of those should return a 403 or 404, never file contents or a directory listing.

### 7. Configure SMTP

For cPanel-hosted email:
- Host: `localhost` or `mail.yourdomain.com`
- Port: `587` (TLS) or `465` (SSL)
- Username: full email address created in cPanel → Email Accounts
- Password: email account password

For Gmail SMTP:
- Host: `smtp.gmail.com`
- Port: `587`
- Username: your Gmail address
- Password: App Password (not regular password; enable 2FA first)

### 8. Set Up Cron Jobs

cPanel → **Cron Jobs**. Adjust the PHP path (`which php` via SSH to find it — often `/usr/local/bin/php` or `/opt/cpanel/ea-php82/root/usr/bin/php`) and the project path (`/home/youruser/public_html/cron/...`, or `/home/youruser/public_html/AiWebReporter/cron/...` for the subdirectory install) for each:

**Newsletter Queue Processor** (every 5 minutes — sends emails for newly published posts):
```
*/5 * * * * /usr/local/bin/php /home/youruser/public_html/cron/newsletter_send.php >> /home/youruser/public_html/storage/logs/newsletter.log 2>&1
```

**AI Bot Pipeline** (if Stage 5 is enabled — hourly is reasonable to start):
```
0 * * * * /usr/local/bin/php /home/youruser/public_html/cron/bot_run.php >> /home/youruser/public_html/storage/logs/bot.log 2>&1
```

**Database Backup** (daily, e.g. 3am):
```
0 3 * * * /usr/local/bin/php /home/youruser/public_html/cron/backup_run.php >> /home/youruser/public_html/storage/logs/backup.log 2>&1
```

`storage/logs/` already exists in the repo and is protected the same way as `app/`/`config/` (deny-all `.htaccess`), so it's a safe place for cron output that still won't be web-reachable.

### 9. Enable SSL

1. cPanel → **SSL/TLS** or **Let's Encrypt**
2. Install certificate for your domain
3. Enable "Force HTTPS Redirect" in cPanel → Domains
4. In `.env`, confirm `APP_URL=https://...` and `SESSION_SECURE=true`

### 10. Security Hardening

- Confirm `APP_DEBUG=false` in `.env` — leaving it `true` in production leaks stack traces to visitors
- Confirm `.env` is not web-accessible — the root `.htaccess`'s `<FilesMatch>` deny block covers this, but verify by browsing directly to it and confirming you get a 403/404, never the file contents (see the test list in step 6)
- Rotate the seeded admin password (see step 4) before the site is publicly reachable
- Set a strong random `CRON_SECRET` in `.env`
- `robots.txt` and `sitemap.xml` are generated dynamically from `APP_URL` (`SitemapController`) — no static file to edit, they're correct automatically once `.env` is set

### 11. Verify Deployment

- [ ] Homepage loads correctly, with CSS/JS/images all resolving (check DevTools Network tab for 404s — this is exactly what breaks if the folder layout in step 2 isn't followed)
- [ ] Login works
- [ ] Admin dashboard accessible
- [ ] Posts display with images
- [ ] Newsletter subscription works
- [ ] Contact form submits
- [ ] Static pages render
- [ ] Sitemap accessible at `/sitemap.xml` and lists real post/category/page URLs on your real domain
- [ ] `/robots.txt` loads and its `Sitemap:` line points at your real domain, not `localhost`
- [ ] View source on a post page: `<link rel="canonical">`, Open Graph tags, and the `application/ld+json` Article block are present and use your real domain
- [ ] Paste a post URL into Google's [Rich Results Test](https://search.google.com/test/rich-results) — Article and BreadcrumbList should validate with no errors
- [ ] HTTPS redirects properly
- [ ] Error pages show (test with invalid URL)

## Troubleshooting

| Issue | Solution |
|-------|----------|
| 500 Internal Server Error | Check error_log in cPanel, verify PHP version is 8.2+ |
| Database connection refused | Verify DB host is `localhost`, credentials are correct |
| mod_rewrite not working | Contact host to ensure it's enabled |
| Emails not sending | Check SMTP credentials, try `localhost` as host for cPanel mail |
| Uploads failing | Check `uploads/` permissions (755) and PHP `upload_max_filesize` |
| Session issues | Verify PHP session save path is writable |
