# ERP Setup Guide

Complete installation, configuration, and deployment guide for the ERP system.

---

## Table of Contents

1. [System Requirements](#1-system-requirements)
2. [Installation (XAMPP / Windows)](#2-installation-xampp--windows)
3. [Installation (Linux / Production)](#3-installation-linux--production)
4. [Environment Configuration](#4-environment-configuration)
5. [Database Setup](#5-database-setup)
6. [Building Assets](#6-building-assets)
7. [Initial Data Setup](#7-initial-data-setup)
8. [Google Drive Backup Sync](#8-google-drive-backup-sync)
9. [Queue Worker Setup](#9-queue-worker-setup)
10. [Scheduled Tasks (Cron)](#10-scheduled-tasks-cron)
11. [Email Configuration](#11-email-configuration)
12. [Production Deployment Checklist](#12-production-deployment-checklist)
13. [Backup & Restore](#13-backup--restore)
14. [Troubleshooting](#14-troubleshooting)

---

## 1. System Requirements

| Component | Minimum | Recommended |
|-----------|---------|-------------|
| PHP | 8.2 | 8.3+ |
| MySQL/MariaDB | 10.4 | 10.6+ (for `SKIP LOCKED` support) |
| Composer | 2.8 | Latest |
| Node.js | 20 | 22+ |
| npm | 10 | Latest |
| RAM | 2 GB | 4 GB+ |
| Disk | 5 GB | 20 GB+ (for backups) |

### Required PHP Extensions
- `pdo_mysql`, `mbstring`, `xml`, `bcmath`, `ctype`, `json`, `openssl`, `gd`, `zip`, `curl`, `fileinfo`

---

## 2. Installation (XAMPP / Windows)

### Step 1: Install XAMPP
Download and install [XAMPP](https://www.apachefriends.org/) to `C:\xampp`. This provides PHP, MySQL/MariaDB, and Apache.

### Step 2: Clone or Copy the Project
```powershell
cd C:\xampp\htdocs
# If using git:
git clone <repository-url> erp
# Or copy the project folder to C:\xampp\htdocs\erp
```

### Step 3: Install PHP Dependencies
```powershell
cd C:\xampp\htdocs\erp
composer install
```

### Step 4: Install Node Dependencies & Build Assets
```powershell
npm install
npm run build
```

### Step 5: Configure Environment
```powershell
copy .env.example .env
php artisan key:generate
```

Edit `.env` (see [Environment Configuration](#4-environment-configuration) below).

### Step 6: Create Database
Open phpMyAdmin (`http://localhost/phpmyadmin`) or MySQL command line:
```sql
CREATE DATABASE erp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

### Step 7: Run Migrations & Seed
```powershell
php artisan migrate
php artisan db:seed
```

### Step 8: Configure Apache VirtualHost
Edit `C:\xampp\apache\conf\extra\httpd-vhosts.conf`:
```apache
<VirtualHost *:8123>
    DocumentRoot "C:/xampp/htdocs/erp/public"
    <Directory "C:/xampp/htdocs/erp/public">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
```

Add to `C:\xampp\apache\conf\httpd.conf` (uncomment if needed):
```apache
Listen 8123
```

Restart Apache from XAMPP Control Panel.

### Step 9: Access the Application
Open `http://127.0.0.1:8123` in your browser.

**Default login:**
- Email: `super@erp.test`
- Password: `password`

---

## 3. Installation (Linux / Production)

```bash
# Clone
cd /var/www
git clone <repository-url> erp
cd erp

# Install dependencies
composer install --no-dev --optimize-autoloader
npm install && npm run build

# Configure
cp .env.example .env
php artisan key:generate

# Edit .env with production values (see below)
nano .env

# Database
php artisan migrate --force
php artisan db:seed --force

# Cache for production
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache

# Set permissions
chown -R www-data:www-data /var/www/erp
chmod -R 775 /var/www/erp/storage
chmod -R 775 /var/www/erp/bootstrap/cache
```

### Nginx Configuration
```nginx
server {
    listen 80;
    server_name erp.yourdomain.com;
    root /var/www/erp/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

---

## 4. Environment Configuration

Edit the `.env` file with the following settings:

### Core Settings
```env
APP_NAME="ERP"
APP_ENV=production          # Use "local" for development
APP_DEBUG=false             # Set to false in production
APP_URL=http://your-domain.com
APP_LOCALE=en
```

### Database
```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=erp
DB_USERNAME=your_db_user
DB_PASSWORD=your_db_password
```

### Queue (for background jobs like real-time backup)
```env
QUEUE_CONNECTION=database
```

### Cache & Session
```env
CACHE_STORE=file            # Use "redis" for better performance
SESSION_DRIVER=file         # Use "redis" for better performance
SESSION_LIFETIME=120
```

### Google Drive (optional — for cloud backup sync)
```env
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REDIRECT_URI=http://your-domain.com/backups/google/callback
```

---

## 5. Database Setup

### Create Database
```sql
CREATE DATABASE erp CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

### Run Migrations
```powershell
php artisan migrate
```

### Seed Initial Data
```powershell
php artisan db:seed
```

This creates:
- 1 Platform Admin user (`super@erp.test`)
- 1 Demo Company ("Demo Traders")
- 3 Subscription plans (Billing Only, Standard, Professional)
- Chart of accounts template
- Sample products, customers, suppliers
- Default branches and warehouses

### Reset Database (Development Only)
```powershell
# Drop and recreate
mysql -u root -e "DROP DATABASE erp; CREATE DATABASE erp;"

# Re-run migrations and seed
php artisan migrate:fresh --seed
```

---

## 6. Building Assets

### Development
```powershell
npm run dev       # Starts Vite dev server with hot reload
```

### Production
```powershell
npm run build     # Compiles and minifies CSS/JS to public/build/
```

---

## 7. Initial Data Setup

After installation, log in as the platform admin and configure:

### 7.1 Company Setup
1. Go to **Setup > Company** (`/company`)
2. Edit company name, address, tax number, currency
3. Set fiscal year start date

### 7.2 Chart of Accounts
1. Go to **Accounting > Chart of Accounts** (`/accounts`)
2. Verify the seeded chart of accounts
3. Add any additional accounts needed
4. Configure account mappings (Settings > Account Mappings)

### 7.3 Warehouses
1. Go to **Inventory > Warehouses** (`/warehouses`)
2. Add your warehouse(s) or store location(s)

### 7.4 Products
1. Go to **Inventory > Products** (`/products`)
2. Add products with SKU, price, cost, tax rate
3. Set opening stock if applicable

### 7.5 Customers & Suppliers
1. Go to **Sales > Customers** (`/customers`)
2. Add customers with billing addresses
3. Go to **Purchases > Suppliers** (`/suppliers`)
4. Add suppliers with contact details

### 7.6 Bank Accounts
1. Go to **Banking > Bank Accounts** (`/bank-accounts`)
2. Add your bank accounts with opening balances

### 7.7 Users & Roles
1. Go to **Setup > Users** (`/users`)
2. Create user accounts for your staff
3. Go to **Setup > Roles** (`/roles`)
4. Assign permissions to roles
5. Assign roles to users

### 7.8 Fiscal Year
1. Go to **Accounting > Fiscal Years** (`/fiscal-years`)
2. Create the current fiscal year
3. Set the fiscal year status to "Open"

---

## 8. Google Drive Backup Sync

### 8.1 Create Google Cloud Project

1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project (e.g., "ERP Backups")
3. Enable the **Google Drive API**:
   - Navigate to **APIs & Services > Library**
   - Search for "Google Drive API"
   - Click **Enable**

### 8.2 Create OAuth Credentials

1. Go to **APIs & Services > Credentials**
2. Click **Create Credentials > OAuth client ID**
3. Choose **Web application**
4. Set authorized redirect URI:
   ```
   http://your-domain.com/backups/google/callback
   ```
   (For local dev: `http://127.0.0.1:8123/backups/google/callback`)
5. Copy the **Client ID** and **Client Secret**

### 8.3 Configure OAuth Consent Screen

1. Go to **APIs & Services > OAuth consent screen**
2. Set User Type to **External** (or Internal for Google Workspace)
3. Fill in app name, support email, developer email
4. Add scope: `https://www.googleapis.com/auth/drive.file`
5. Add your domain to authorized domains

### 8.4 Add to .env
```env
GOOGLE_CLIENT_ID=your_client_id_here
GOOGLE_CLIENT_SECRET=your_client_secret_here
GOOGLE_REDIRECT_URI=http://your-domain.com/backups/google/callback
```

### 8.5 Connect in the App

1. Go to **Setup > Backups** (`/backups`)
2. Click **Connect Google Drive**
3. Authorize in Google's consent screen
4. You'll be redirected back — connection confirmed
5. Toggle **Auto-sync** to enable automatic uploads
6. Toggle **Real-time Backup** to back up after every change

---

## 9. Queue Worker Setup

The queue worker processes background jobs like real-time backups.

### Start Worker (Development)
```powershell
php artisan queue:work --queue=backups
```

### Start Worker (Production — using Supervisor)

Install Supervisor:
```bash
sudo apt install supervisor
```

Create config `/etc/supervisor/conf.d/erp-worker.conf`:
```ini
[program:erp-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/erp/artisan queue:work --queue=backups --sleep=3 --tries=3
autostart=true
autorestart=true
numprocs=1
user=www-data
redirect_stderr=true
stdout_logfile=/var/www/erp/storage/logs/worker.log
stopwaitsecs=3600
```

Start:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start erp-worker:*
```

### Windows (Production Alternative)
Use a scheduled task or run in a terminal:
```powershell
php artisan queue:work --queue=backups --once
```
Add to Windows Task Scheduler to run every minute.

---

## 10. Scheduled Tasks (Cron)

### Add to `routes/console.php` or `app/Console/Kernel.php`:
```php
use Illuminate\Support\Facades\Schedule;

// Nightly full backup at 2 AM
Schedule::command('erp:backup')->dailyAt('02:00');

// Verify stock balances daily
Schedule::command('stock:verify')->dailyAt('03:00');

// Sync permissions weekly
Schedule::command('permissions:sync')->weekly();
```

### Linux Cron Entry
```bash
* * * * * cd /var/www/erp && php artisan schedule:run >> /dev/null 2>&1
```

### Windows Task Scheduler
Create a task that runs every minute:
```powershell
php C:\xampp\htdocs\erp\artisan schedule:run
```

---

## 11. Email Configuration

### SMTP (Production)
```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.your-provider.com
MAIL_PORT=587
MAIL_USERNAME=your_email@domain.com
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@yourdomain.com
MAIL_FROM_NAME="${APP_NAME}"
```

### Postmark
```env
MAIL_MAILER=postmark
POSTMARK_TOKEN=your_postmark_token
```

### Resend
```env
MAIL_MAILER=resend
RESEND_KEY=your_resend_key
```

---

## 12. Production Deployment Checklist

- [ ] **APP_ENV=production** in `.env`
- [ ] **APP_DEBUG=false** in `.env`
- [ ] **APP_URL** set to actual domain
- [ ] **DB_PASSWORD** set to a strong password
- [ ] **MAIL_*** configured with real SMTP
- [ ] Run `php artisan key:generate`
- [ ] Run `php artisan migrate --force`
- [ ] Run `npm run build`
- [ ] Run `php artisan config:cache`
- [ ] Run `php artisan route:cache`
- [ ] Run `php artisan view:cache`
- [ ] Run `php artisan event:cache`
- [ ] Set correct file permissions on `storage/` and `bootstrap/cache/`
- [ ] Configure Supervisor for queue worker
- [ ] Configure cron for scheduled tasks
- [ ] Set up Google Drive backup sync (optional)
- [ ] Configure HTTPS (Let's Encrypt / SSL certificate)
- [ ] Change platform admin password from default
- [ ] Test login, create invoice, run reports

---

## 13. Backup & Restore

### Create Backup (Manual)
```powershell
php artisan erp:backup
```
This creates a gzipped SQL dump in `storage/app/backups/`.

### Create Backup (UI)
Go to **Setup > Backups** (`/backups`) and click **Create Backup**.

### Download Backup
From the Backups page, click **Download** on any backup file.

### Restore from Backup
```powershell
# Extract the gzip file
gunzip backup_erp_2026-08-25_023930.sql.gz

# Import to database
mysql -u root -p erp < backup_erp_2026-08-25_023930.sql
```

### Automatic Backups
- **Scheduled**: Add `$schedule->command('erp:backup')->dailyAt('02:00')`
- **Google Drive**: Enable auto-sync on the Backups page
- **Real-time**: Enable real-time backup toggle (backs up after every change with 2-min debounce)

### Backup Retention
The system automatically keeps the last 30 backup files. Older files are deleted.

---

## 14. Troubleshooting

### "mysqldump not found"
On XAMPP/Windows, the backup command uses `C:\xampp\mysql\bin\mysqldump.exe`. If your XAMPP is in a different location, update the path in `app/Console/Commands/BackupCommand.php`.

### "No application encryption key found"
```powershell
php artisan key:generate
```

### "SQLSTATE[HY000] [2002] Connection refused"
- Verify MySQL/MariaDB is running
- Check `DB_HOST` and `DB_PORT` in `.env`

### "SQLSTATE[42S22] Column not found"
Run migrations:
```powershell
php artisan migrate
```

### Sidebar menu items not showing
- Platform admin needs a company selected. Use the company switcher in the top bar.
- Check that the subscription plan includes the feature (Setup > Subscription).

### POS redirects to session page
POS requires an open cash session. Go to **POS > Session** and open a new session first.

### Queue jobs not processing
- Ensure `QUEUE_CONNECTION=database` in `.env`
- Run `php artisan queue:work` to process jobs
- Check `storage/logs/laravel.log` for errors

### Google Drive connection failed
- Verify `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` in `.env`
- Ensure the redirect URI in Google Cloud Console matches exactly
- Check that Google Drive API is enabled

### Real-time backup not working
- Ensure Google Drive is connected and auto-sync is enabled
- Start a queue worker: `php artisan queue:work --queue=backups`
- Check that real-time backup toggle is ON in the Backups page

### Clearing Cache
```powershell
php artisan optimize:clear        # Clear all caches
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan event:clear
```

### Reset Everything (Development)
```powershell
mysql -u root -e "DROP DATABASE erp; CREATE DATABASE erp;"
php artisan migrate:fresh --seed
php artisan optimize:clear
```
