# Seraph3 - Business Management System

A comprehensive Laravel-based business management application for managing tasks, clients, invoicing, projects, and team workflows. Built with modern technologies and designed for scalability.

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![PHP Version](https://img.shields.io/badge/PHP-8.2%2B-blue)](https://php.net)
[![Laravel](https://img.shields.io/badge/Laravel-12.x-red)](https://laravel.com)

## ✨ Features

- 📋 **Task & Project Management** - Complete workflow management with priorities, assignments, and tracking
- 👥 **Client & Customer Management** - Comprehensive CRM with contacts, sites, and service history
- 💰 **Invoicing & Quotes** - Professional invoicing with Xero accounting integration
- 📞 **3CX Phone Integration** - Click-to-call, automatic call logging, and CDR synchronization
- 📊 **Inventory & Stock Management** - Parts tracking, stock levels, and supplier management
- 👔 **HR & User Management** - Employee records, permissions, and role-based access control
- 📧 **Email & SMS Integration** - Automated notifications and communication
- 🔐 **LDAP/Active Directory** - Enterprise authentication and user sync
- 📱 **Push Notifications** - Real-time updates via Firebase Cloud Messaging
- 🔄 **Real-time Updates** - WebSocket support for live collaboration
- 📈 **Reporting & Analytics** - Business insights and performance metrics
- 🌐 **Multi-tenant Support** - Manage multiple business entities

## 🚀 Quick Start

### Docker Installation (Recommended)

The fastest way to get started:

```bash
# 1. Clone the repository
git clone https://github.com/yourusername/seraph3.git
cd seraph3

# 2. Copy environment configuration
cp .env.demo .env

# 3. Start Docker containers
docker-compose up -d

# 4. Install dependencies and setup
docker-compose exec app composer install
docker-compose exec app php artisan key:generate
docker-compose exec app php artisan migrate
docker-compose exec app php artisan db:seed

# 5. Access the application
open https://localhost:8000
```

### Default Login Credentials
- **Username:** `admin`
- **Password:** `admin123`

⚠️ **Change these immediately after first login!**

## 📖 Documentation

- **[3CX Phone System Setup](app/Modules/ThreeCX/SETUP_GUIDE.md)** - VoIP integration guide

---

## 📋 Table of Contents
- [Features](#-features)
- [Quick Start](#-quick-start)
- [System Requirements](#-system-requirements)
- [Development Setup](#-development-setup)
- [Asset Management](#-asset-management)
- [Integrations](#-integrations)
- [Production Deployment](#-production-deployment)
- [Common Commands](#-common-commands)
- [Troubleshooting](#-troubleshooting)
- [Contributing](#-contributing)
- [License](#-license)

---

## 💻 System Requirements

### For Docker Installation
- Docker 20.10+
- Docker Compose 2.0+
- 4GB RAM minimum (8GB recommended)
- 10GB free disk space

### For Manual Installation
- PHP 8.2 or higher
- MySQL 8.0+ or MariaDB 10.5+
- Redis 6.0+ (recommended for production)
- Nginx or Apache
- Node.js 18+ and NPM 9+
- Composer 2.0+

**Required PHP Extensions:**
```
php-fpm, php-mysql, php-redis, php-mbstring, php-xml,
php-curl, php-zip, php-gd, php-intl, php-bcmath,
php-dom, php-ldap (optional)
```

See **[INSTALL.md](INSTALL.md)** for complete installation instructions.

---

## 🔧 Development Setup

### Prerequisites
- Docker & Docker Compose
- Git

### Initial Setup
```bash
# Clone the repository
git clone [your-repo-url]
cd seraph3

# Copy environment file
cp .env.example .env

# Start containers
docker-compose up -d

# Install dependencies (first time only)
docker-compose exec app composer install
docker-compose exec app npm install

# Generate application key (first time only)
docker-compose exec app php artisan key:generate

# Run migrations (first time only)
docker-compose exec app php artisan migrate
```

---

## 🎨 Asset Management (Laravel Mix)

**⚠️ IMPORTANT:** We use **Laravel Mix** (not Gulp) for asset compilation.

### Development Build
```bash
# Build assets for development
docker-compose exec app npm run dev

# Watch for changes (auto-rebuild)
docker-compose exec app npm run watch
```

### Production Build
```bash
# Build optimized production assets
docker-compose exec app npm run production
```

### Available NPM Scripts
- `npm run dev` - Development build
- `npm run watch` - Watch mode (auto-rebuild)
- `npm run production` - Production build (minified)
- `npm run hot` - Hot module replacement

---

## 🔌 Integrations

### 📞 3CX Phone System Integration

Modern phone system integration replacing the legacy Asterisk system.

**Quick Setup:**
```bash
# 1. Run migration
docker-compose exec app php artisan migrate

# 2. Configure environment
THREECX_BASE_URL=https://your-3cx-server:5001
THREECX_API_KEY=your_api_key
THREECX_DEFAULT_EXTENSION=1001

# 3. Test connection
docker-compose exec app php artisan threecx:test-connection
```

**Features:**
- ✅ **Click-to-Call**: Direct calling from task views
- ✅ **Auto Call Logging**: Calls automatically linked to tasks
- ✅ **Real-time Status**: Live call progress updates
- ✅ **CDR Sync**: Background synchronization with 3CX
- ✅ **Admin Interface**: Complete configuration panel

**Documentation:**
- 📖 **[Complete Setup Guide](app/Modules/ThreeCX/SETUP_GUIDE.md)** - Comprehensive installation and configuration
- 📖 **[Technical Reference](app/Modules/ThreeCX/README.md)** - API documentation and troubleshooting

**Admin Configuration:**
- Navigate to **Admin → Settings → Integrations**
- Enable **3CX Phone System Integration**
- Configure your 3CX server details
- Click **Test Connection** to verify setup

### 💼 Other Integrations

**💰 Xero Accounting Integration:**
- Real-time invoice synchronization
- Automated accounting workflows
- OAuth2 authentication

**📱 SMS/Communication Systems:**
- SMS gateway integration
- Email notification system
- Push notification support

**🔐 Active Directory/LDAP:**
- User authentication and management
- Group-based permissions
- Enterprise directory integration

---

## 🚀 Production Deployment (Direct Host)

### Prerequisites
- Ubuntu/Debian Linux server
- PHP 8.3+ with required extensions
- MySQL 9.0+
- Nginx
- Redis
- Composer
- Node.js & NPM

### 📖 Production Server Setup

#### 1. Install PHP and Extensions
```bash
# Update system
sudo apt update && sudo apt upgrade -y

# Install PHP 8.3 and required extensions
sudo apt install -y software-properties-common
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update

# Install PHP with all required extensions including LDAP
sudo apt install -y php8.3 php8.3-fpm php8.3-mysql php8.3-redis \
    php8.3-mbstring php8.3-xml php8.3-curl php8.3-zip php8.3-gd \
    php8.3-intl php8.3-bcmath php8.3-dom php8.3-ldap php8.3-cli \
    php8.3-common php8.3-opcache

# Install LDAP support
sudo apt install -y libldap2-dev libnss-ldap libpam-ldap ldap-utils
```

#### 2. Install Database and Cache
```bash
# Install MySQL 9.0
sudo apt install -y mysql-server-9.0
sudo mysql_secure_installation

# Install Redis
sudo apt install -y redis-server
sudo systemctl enable redis-server
sudo systemctl start redis-server
```

#### 3. Install Web Server
```bash
# Install Nginx
sudo apt install -y nginx
sudo systemctl enable nginx
sudo systemctl start nginx
```

#### 4. Install Node.js and Composer
```bash
# Install Node.js (LTS)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install -y nodejs

# Install Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
sudo chmod +x /usr/local/bin/composer
```

### 📦 Application Deployment

#### 1. Deploy Application Code
```bash
# Clone repository
cd /var/www
sudo git clone [your-repo-url] seraph3
cd seraph3

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

#### 2. Install Dependencies
```bash
# Install PHP dependencies
sudo -u www-data composer install --optimize-autoloader --no-dev

# Install Node.js dependencies and build assets
sudo -u www-data npm install
sudo -u www-data npm run production
```

#### 3. Configure Environment
```bash
# Copy and configure environment file
sudo -u www-data cp .env.example .env
sudo -u www-data nano .env

# Generate application key
sudo -u www-data php artisan key:generate
```

#### 4. Configure Database
```bash
# Create database
sudo mysql -u root -p
CREATE DATABASE seraph CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'seraph_user'@'localhost' IDENTIFIED BY 'secure_password';
GRANT ALL PRIVILEGES ON seraph.* TO 'seraph_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

# Run migrations
sudo -u www-data php artisan migrate

# Cache configuration for production
sudo -u www-data php artisan config:cache
sudo -u www-data php artisan route:cache
sudo -u www-data php artisan view:cache
```

### 🔧 LDAP Configuration

#### PHP LDAP Extension
The LDAP extension is already installed in the setup above. Configure it in your `.env`:

```bash
# LDAP Configuration
LDAP_ENABLED=true
LDAP_HOST=your-ldap-server.com
LDAP_PORT=389
LDAP_BASE_DN=dc=company,dc=com
LDAP_USERNAME=cn=admin,dc=company,dc=com
LDAP_PASSWORD=ldap_password
```

### 🌐 Nginx Configuration
```bash
# Create Nginx site configuration
sudo nano /etc/nginx/sites-available/seraph3

# Basic configuration example:
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/seraph3/public;
    index index.php index.html;

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

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

# Enable site
sudo ln -s /etc/nginx/sites-available/seraph3 /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
```

### 🔒 SSL Certificate Setup (Optional)
```bash
# Install Certbot for SSL certificates
sudo apt install -y certbot python3-certbot-nginx

# Get SSL certificate (replace your-domain.com with your actual domain)
sudo certbot --nginx -d your-domain.com

# Auto-renewal (already set up by certbot)
sudo systemctl status certbot.timer
```

### 🔄 Maintenance Commands
```bash
# Update application
cd /var/www/seraph3
sudo -u www-data git pull
sudo -u www-data composer install --optimize-autoloader --no-dev
sudo -u www-data npm run production
sudo -u www-data php artisan migrate
sudo -u www-data php artisan config:cache
sudo -u www-data php artisan route:cache
sudo -u www-data php artisan view:cache

# Restart services
sudo systemctl restart php8.3-fpm
sudo systemctl reload nginx
```

---

## ⚡ Common Commands

### 🐳 Docker Commands

#### Container Management
```bash
# Start all services
docker-compose up -d

# Stop all services
docker-compose down

# Restart specific service
docker-compose restart app

# View logs
docker-compose logs app
docker-compose logs nginx

# Execute commands in container
docker-compose exec app bash
docker-compose exec app php artisan tinker
```

#### Database Operations
```bash
# Run migrations
docker-compose exec app php artisan migrate

# Rollback migrations
docker-compose exec app php artisan migrate:rollback

# Seed database
docker-compose exec app php artisan db:seed

# Fresh migration with seed
docker-compose exec app php artisan migrate:fresh --seed
```

#### Cache Management
```bash
# Clear all caches
docker-compose exec app php artisan optimize:clear

# Clear specific caches
docker-compose exec app php artisan cache:clear
docker-compose exec app php artisan config:clear
docker-compose exec app php artisan route:clear
docker-compose exec app php artisan view:clear

# Cache for production
docker-compose exec app php artisan config:cache
docker-compose exec app php artisan route:cache
docker-compose exec app php artisan view:cache
```

---

## 🔨 Build System (Laravel Mix)

### Configuration
Laravel Mix configuration is in `webpack.mix.js`. It handles:
- JavaScript compilation and minification
- SCSS/CSS compilation with Compass support
- File versioning for cache busting
- Automatic vendor/app file separation

### Build Process
```javascript
// webpack.mix.js
mix.scripts(vendorFiles, 'public/js/vendor.js')
   .scripts(appFiles, 'public/js/app.js')
   .sass('resources/assets/scss/main.scss', 'public/css/main.css')
   .options({
     processCssUrls: false,
     postCss: [require('autoprefixer')]
   })
   .version(); // Add versioning for cache busting
```

### Asset Structure
```
public/
├── css/
│   ├── main.css          # Compiled SCSS
│   └── main.css.gz       # Gzipped version
├── js/
│   ├── vendor.js         # Third-party libraries
│   ├── app.js           # Application code
│   └── *.js.gz          # Gzipped versions
└── mix-manifest.json     # Asset versioning map
```

---

## 🚦 Services & Ports

| Service | Container | Port | Purpose |
|---------|-----------|------|---------|
| Laravel | app | 9000 | PHP-FPM Application |
| Nginx | nginx | 8000 (HTTPS) | Web Server |
| MySQL | mysql | 3306 | Database |
| Redis | redis | 6379 | Cache/Sessions |
| Adminer | adminer | 8080 | Database Admin |

---

## 🔧 Troubleshooting

### Common Issues

**502 Bad Gateway:**
```bash
# Check if PHP-FPM is running
docker-compose exec app ps aux | grep php-fpm

# Restart containers
docker-compose restart app nginx
```

**Assets not loading:**
```bash
# Rebuild assets
docker-compose exec app npm run production

# Clear browser cache or check versioned URLs in mix-manifest.json
```

**Permission issues:**
```bash
# Method 1: Fix via Docker container
docker-compose exec app chmod -R 775 storage bootstrap/cache

# Method 2: Fix on host (Linux/WSL2)
sudo ./fix-host-permissions.sh

# Method 3: Quick host fix
sudo chown -R 33:33 storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache

# Method 4: Windows/WSL2 specific
# Use separate Docker volumes for writable directories (already configured)
docker-compose down
docker-compose up -d
```

**Docker permission errors (chmod issues):**
The Docker configuration has been updated to handle permission issues better:
- ✅ **Separate volumes** for storage and cache directories
- ✅ **Improved entrypoint script** with better error handling
- ✅ **User/group management** with proper UID/GID mapping
- ✅ **Windows/WSL2 compatibility** with volume mounts

If you still have permission issues, the container will now:
- Use safer permission handling
- Fall back to volume-based permissions
- Provide clear error messages
- Continue running even if some permissions can't be set

**Database connection issues:**
```bash
# Check container connectivity
docker-compose exec app php artisan tinker
# Test: DB::connection()->getPdo();
```

### Performance Optimization

**Production Checklist:**
- [ ] `APP_DEBUG=false` in .env
- [ ] Assets built with `npm run production`
- [ ] Laravel caches enabled (`config:cache`, `route:cache`, `view:cache`)
- [ ] Composer optimized (`composer install --optimize-autoloader`)
- [ ] SSL certificates configured
- [ ] Gzip compression enabled

### Debug Mode
```bash
# Enable debug logging
docker-compose exec app php artisan log:clear
docker-compose exec app tail -f storage/logs/laravel.log
```

---

## 📚 Additional Resources

- **Laravel Mix Documentation:** https://laravel-mix.com/docs
- **Laravel Documentation:** https://laravel.com/docs
- **Docker Compose Reference:** https://docs.docker.com/compose/

---

## 🔄 Migration Notes

### From Gulp to Laravel Mix (Completed)
- ✅ Replaced Gulp with Laravel Mix
- ✅ Updated build scripts and processes
- ✅ Fixed asset compilation pipeline
- ✅ Added production optimization

### Deployment Changes
- **Old:** `gulp --production`
- **New:** `npm run production`

Make sure to update your CI/CD pipelines and deployment scripts accordingly.

---

## 🤝 Contributing

We welcome contributions! Here's how you can help:

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

**Development Guidelines:**
- Follow PSR-12 coding standards
- Write tests for new features
- Update documentation
- Keep commits atomic and well-described

---

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

## 📞 Support & Community

- **🐛 Bug Reports:** [GitHub Issues](https://github.com/yourusername/seraph3/issues)
- **💬 Discussions:** [GitHub Discussions](https://github.com/yourusername/seraph3/discussions)

---

## 🙏 Acknowledgments

Built with amazing open-source technologies:
- [Laravel](https://laravel.com) - PHP Framework
- [Vue.js](https://vuejs.org) - Frontend Framework
- [MySQL](https://mysql.com) - Database
- [Redis](https://redis.io) - Caching
- [Docker](https://docker.com) - Containerization

---

## 🔒 Security

If you discover any security-related issues, please email security@yourdomain.com instead of using the issue tracker.

---

**Made with ❤️ for business management**
