# Installation Guide - Windows Server (IIS + PHP + MySQL)

## Prerequisites
- Windows Server with IIS
- PHP 8.x installed (FastCGI)
- MySQL/MariaDB installed
- Node.js 18+ installed (for building React)

---

## Step 1: Install Node.js (if not installed)

Download from: https://nodejs.org/en/download
Choose "Windows Installer (.msi)" - LTS version.
After install, verify in CMD:
```cmd
node --version
npm --version
```

---

## Step 2: Create the Database

Open MySQL command line or phpMyAdmin/HeidiSQL:

```sql
CREATE DATABASE office_seating_master CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

Import the master schema:
```cmd
mysql -u root -p office_seating_master < C:\path\to\office-seating-saas\master_database.sql
```

Or paste the contents of `master_database.sql` into HeidiSQL/phpMyAdmin.

---

## Step 3: Configure the PHP API

### 3a. Edit Database Credentials
Open `api\config\database.php` and update:

```php
private const MASTER_HOST = 'localhost';
private const MASTER_USER = 'root';        // ← your MySQL username
private const MASTER_PASS = 'yourpassword'; // ← your MySQL password
private const MASTER_DB   = 'office_seating_master';
```

### 3b. Edit Constants
Open `api\config\constants.php` and update:

```php
// IMPORTANT: Change this secret key for security!
define('JWT_SECRET', 'your-unique-secret-key-here-change-me');

// Set your domain (after React is built and deployed)
define('SITE_URL', 'https://yourdomain.com');
define('API_URL', 'https://yourdomain.com/api');
```

### 3c. Update CORS for Production
Open `api\middleware\cors.php` and update the allowed origins:

```php
$allowedOrigins = [
    'https://yourdomain.com',
    'http://localhost:5173',  // keep for dev
];
```

---

## Step 4: Deploy Files to IIS

### Folder Structure on Server
```
C:\inetpub\wwwroot\office-seating\
├── api\                    ← PHP API files
│   ├── index.php
│   ├── web.config          ← IIS URL rewrite (see below)
│   ├── config\
│   ├── middleware\
│   ├── helpers\
│   └── routes\
├── index.html              ← React built files (from Step 5)
├── assets\                 ← React built JS/CSS
└── uploads\                ← File uploads directory
```

### 4a. Create IIS `web.config` for API URL Rewriting

Create this file at `api\web.config`:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="API Router" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" />
                </rule>
            </rules>
        </rewrite>
        <defaultDocument>
            <files>
                <add value="index.php" />
            </files>
        </defaultDocument>
    </system.webServer>
</configuration>
```

### 4b. Create Root `web.config` for React SPA Routing

Create this file at the root `web.config` (next to index.html):

```xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <!-- API requests go to PHP -->
                <rule name="API" stopProcessing="true">
                    <match url="^api/(.*)" />
                    <action type="Rewrite" url="api/index.php" />
                </rule>
                
                <!-- Upload files served directly -->
                <rule name="Uploads" stopProcessing="true">
                    <match url="^uploads/(.*)" />
                    <action type="None" />
                </rule>
                
                <!-- Static files served directly -->
                <rule name="Static Files" stopProcessing="true">
                    <match url="^assets/(.*)" />
                    <action type="None" />
                </rule>
                
                <!-- Everything else → React SPA -->
                <rule name="React SPA" stopProcessing="true">
                    <match url=".*" />
                    <conditions logicalGrouping="MatchAll">
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.html" />
                </rule>
            </rules>
        </rewrite>
        
        <!-- MIME types for modern JS -->
        <staticContent>
            <remove fileExtension=".json" />
            <mimeMap fileExtension=".json" mimeType="application/json" />
            <remove fileExtension=".woff2" />
            <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
        </staticContent>
        
        <defaultDocument>
            <files>
                <add value="index.html" />
            </files>
        </defaultDocument>
    </system.webServer>
</configuration>
```

---

## Step 5: Build the React Frontend

On your local machine OR on the server (anywhere with Node.js):

### 5a. Update the API URL before building

Edit `frontend\.env`:
```
VITE_API_URL=/api
VITE_UPLOADS_URL=
```

### 5b. Build

```cmd
cd frontend
npm install
npm run build
```

This creates a `frontend\dist\` folder with:
```
dist\
├── index.html
└── assets\
    ├── index-xxxxx.js
    └── index-xxxxx.css
```

### 5c. Copy Built Files to IIS

Copy the CONTENTS of `frontend\dist\` to your IIS root:

```cmd
xcopy /E /Y frontend\dist\* C:\inetpub\wwwroot\office-seating\
```

So `index.html` sits at `C:\inetpub\wwwroot\office-seating\index.html`

---

## Step 6: IIS Site Configuration

### 6a. Ensure URL Rewrite Module is Installed
- Download from: https://www.iis.net/downloads/microsoft/url-rewrite
- This is REQUIRED for both React SPA routing and PHP API routing

### 6b. Create IIS Site
1. Open **IIS Manager**
2. Right-click **Sites** → **Add Website**
   - Site name: `OfficeSeating`
   - Physical path: `C:\inetpub\wwwroot\office-seating`
   - Binding: your domain or IP, port 80/443
3. Make sure the Application Pool uses a recent .NET CLR version

### 6c. Verify PHP Handler Mapping
In IIS Manager → your site → **Handler Mappings**:
- Ensure `*.php` is mapped to PHP FastCGI
- If not: Add Module Mapping → `*.php` → FastCgiModule → `C:\PHP\php-cgi.exe`

### 6d. Set Folder Permissions
Right-click `uploads\` folder → Properties → Security:
- Add `IIS_IUSRS` with **Modify** permissions
- Same for any temp folder PHP uses

---

## Step 7: Verify Installation

### Test API:
Open browser: `https://yourdomain.com/api`
You should see:
```json
{"success":true,"message":"Success","data":{"name":"Office Seating SaaS API","version":"2.0","status":"running"}}
```

### Test Frontend:
Open: `https://yourdomain.com`
You should see the landing page.

### Test Login:
Go to: `https://yourdomain.com/master/login`
- Username: `superadmin`
- Password: `superadmin123`

---

## Step 8: SSL Certificate (Recommended)

If you have SSL configured in IIS:
1. Add HTTPS binding (port 443) in IIS
2. Update `api\config\constants.php`:
   ```php
   define('SITE_URL', 'https://yourdomain.com');
   define('API_URL', 'https://yourdomain.com/api');
   ```

---

## Troubleshooting

### "404 Not Found" on React pages (like /login, /master)
→ URL Rewrite module not installed or web.config not working.
→ Install: https://www.iis.net/downloads/microsoft/url-rewrite

### "500 Internal Server Error" on /api routes
→ Check PHP error log: `C:\PHP\logs\php_errors.log`
→ Verify PHP FastCGI handler is configured
→ Try accessing `https://yourdomain.com/api/index.php` directly

### API returns "Master DB Connection failed"
→ Wrong MySQL credentials in `api\config\database.php`
→ MySQL service not running: `net start mysql`

### CORS errors in browser console
→ Update allowed origins in `api\middleware\cors.php`
→ For production, add your exact domain

### React shows blank page
→ Check browser console (F12) for errors
→ Verify `index.html` exists at site root
→ Check that `assets/` folder was copied correctly

### PHP "Class not found" or "require_once failed"
→ Verify all API files are uploaded (check api\routes\ subfolders)
→ File paths are case-sensitive even on Windows in some configs

---

## Quick Reference

| URL | What |
|-----|------|
| `/` | Landing page |
| `/login` | Company admin login |
| `/register` | New company signup |
| `/master/login` | Super admin login |
| `/master/dashboard` | Super admin panel |
| `/app/dashboard` | Company admin panel |
| `/view/{slug}` | Public seating map |
| `/api` | API status check |
