# IHMS CMS Backend - cPanel Deployment Guide

This guide walks you through deploying the PHP backend to a cPanel shared hosting environment.

---

## Prerequisites

- **cPanel access** with the following features enabled:
  - PHP 8.1 or higher
  - MySQL / MariaDB database
  - File Manager or FTP/SFTP access
  - Apache with `mod_rewrite` (usually enabled by default)
- **SSH access** (optional, for running Composer on the server)
- **A domain or subdomain** (e.g., `api.ihms.com` or `yourdomain.com/api`)

---

## Step 1: Prepare the Database

1. Log into **cPanel** and open **phpMyAdmin** or **MySQL Databases**.
2. Create a new database:
   - **Database Name**: `ihms_cms` (or any name you prefer)
   - **Username**: Choose a username
   - **Password**: Generate a strong password
3. Note down the database name, username, password, and host (usually `localhost`).
4. Open **phpMyAdmin**, select your new database, click the **SQL** tab, and paste the contents of `database/migration.sql` from this project.
5. Click **Go** to execute the migration. This creates all tables and seed data.

> **Default admin credentials after migration:**
> - Email: `admin@ihms.com`
> - Password: `admin123`

---

## Step 2: Upload Files to cPanel

### Option A: Using File Manager (simplest)

1. Zip the `backend/` folder on your local machine (excluding `vendor/` if you'll run Composer on the server).
2. In cPanel, open **File Manager** and navigate to `public_html/` (or a subdomain folder like `api.ihms.com/`).
3. Upload the zip file and extract it.
4. Rename the extracted folder to something clean (optional).

### Option B: Using FTP/SFTP

1. Connect to your server using an FTP client (FileZilla, WinSCP, etc.).
2. Upload the entire `backend/` contents to your desired directory (e.g., `public_html/api/`).

---

## Step 3: Configure the Environment

### If you have SSH access:

```bash
# Navigate to the backend directory
cd public_html/backend/

# Copy .env.example to .env
cp .env.example .env

# Edit .env with your database credentials
nano .env
```

### If you don't have SSH access:

1. Locally, copy `.env.example` and rename it to `.env`.
2. Edit the `.env` file with your production values:

```env
APP_NAME="IHMS CMS API"
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com

# Database - use the credentials from Step 1
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

# JWT - CHANGE THIS to a random 64-character string!
JWT_SECRET=your-random-64-char-secret-string-here-change-this
JWT_ISSUER=ihms-cms-api
JWT_EXPIRY=3600

# CORS - add your frontend domain
CORS_ALLOWED_ORIGINS=https://your-frontend-domain.com

# File Uploads
UPLOAD_MAX_SIZE=5242880
UPLOAD_ALLOWED_TYPES=jpg,jpeg,png,gif,webp,svg,pdf,doc,docx
UPLOAD_PATH=uploads
```

3. Upload the `.env` file to the server along with your other files.

---

## Step 4: Upload Files (No Composer Needed)

This backend uses a built-in autoloader and has no external Composer dependencies, so you can upload the files directly without running `composer install`.

### With SSH / File Manager:

1. Zip the `backend/` folder locally.
2. Upload to `public_html/backend/` and extract.
3. Create `.env` from `.env.example` and fill in your database credentials.

---

## Step 5: Set Directory Permissions

Ensure the following directories are writable:

```bash
chmod -R 755 backend/uploads/
chmod -R 755 backend/vendor/
chmod 644 backend/.env
```

If you're using File Manager:
1. Right-click the `uploads` folder → **Change Permissions** → Set to `755`.
2. Right-click the `.env` file → **Change Permissions** → Set to `644`.

---

## Step 6: Configure Subdomain or Document Root

### Option A: Point a subdomain to the `public/` folder (recommended)

1. In cPanel, go to **Domains** → **Create A New Domain**.
2. Enter `api.ihms.com` (or your desired subdomain).
3. Set the **Document Root** to: `public_html/backend/public`
4. This way, visitors access `https://api.ihms.com/api/...`

### Option B: Use a subfolder under your main domain

If you want the API at `https://yourdomain.com/api/backend/public/...`, you'll need to update the `.htaccess` file.

---

## Step 7: Update the Frontend Configuration

In your Next.js frontend (this project), update the `.env.local` file:

```env
NEXT_PUBLIC_APP_API_URL=https://api.ihms.com
```

This changes the Axios base URL from `http://localhost:4000` to your production API URL.

---

## Step 8: Test the Deployment

### 1. Health Check

Open your browser and visit:
```
https://api.ihms.com/api/health
```

Expected response:
```json
{
  "status": "success",
  "data": {
    "status": "ok",
    "timestamp": "2026-01-01T00:00:00+01:00",
    "version": "1.0.0"
  }
}
```

### 2. Test Login

```bash
curl -X POST https://api.ihms.com/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "admin@ihms.com", "password": "admin123"}'
```

---

## Troubleshooting

### Problem: 500 Internal Server Error
- Check if PHP version is 8.1 or higher.
- Check if `.env` file exists and is properly configured.
- Check file permissions.
- Enable debugging temporarily by setting `APP_DEBUG=true` in `.env`.

### Problem: 404 Not Found
- Ensure `mod_rewrite` is enabled in Apache.
- Check that `.htaccess` file exists in the `public/` directory.
- Verify the document root is pointing to `public/` folder.

### Problem: "Class not found" errors
- Run `composer dump-autoload` to regenerate the autoloader.
- Ensure `vendor/autoload.php` exists.

### Problem: Database connection failed
- Verify database credentials in `.env`.
- Ensure the database user has access to the database.
- Try using `127.0.0.1` instead of `localhost` for `DB_HOST`.

### Problem: CORS errors in the browser
- Update `CORS_ALLOWED_ORIGINS` in `.env` to include your frontend domain.
- Clear browser cache after making changes.

### Problem: File uploads failing
- Check that the `uploads/` directory exists and is writable (755).
- Check PHP upload limits in cPanel's **MultiPHP INI Editor**.

---

## Security Checklist

- [ ] `APP_DEBUG` is set to `false` in production.
- [ ] `JWT_SECRET` is a long, random string (at least 64 characters).
- [ ] Database password is strong and unique.
- [ ] The `.env` file is NOT publicly accessible (`.htaccess` blocks it).
- [ ] The `vendor/` folder is NOT publicly accessible (`.htaccess` blocks it).
- [ ] SSL/HTTPS is enabled on your domain.
- [ ] Regular backups are configured for the database.

---

## Maintenance

### Backup the Database
```bash
# Via SSH
mysqldump -u username -p ihms_cms > backup_$(date +%Y%m%d).sql
```

### Update Composer Dependencies
```bash
composer update --no-dev
composer dump-autoload --optimize
```

### View Error Logs
In cPanel, go to **Metrics** → **Error Log** to view PHP errors.

---

## File Structure Overview (after deployment)

```
public_html/
└── backend/                    # Your uploaded backend folder
    ├── .env                    # Environment configuration
    ├── composer.json
    ├── vendor/                 # Composer dependencies
    ├── config/
    │   └── app.php
    ├── database/
    │   └── migration.sql
    ├── src/
    │   ├── Controllers/
    │   ├── Core/
    │   ├── Helpers/
    │   ├── Middleware/
    │   └── routes.php
    ├── public/                 # <-- Document root points here
    │   ├── index.php           # Entry point
    │   └── .htaccess           # URL rewriting
    └── uploads/                # Uploaded files