# Developer Setup Guide

Complete guide to setting up the M1 ERP development environment on your local machine.

## Prerequisites

### Required Software

- **PHP**: 8.2 or higher
- **Database**: MariaDB 10.5+ or MySQL 8.0+
- **Composer**: 2.5+
- **Git**: 2.30+
- **Web Server**: Apache 2.4+ or Nginx 1.20+

### Optional Tools

- **PHPStorm**: Recommended IDE
- **Docker**: For containerized development (optional)
- **Node.js**: For front-end asset compilation (if needed)

## Installation Steps

### 1. Clone the Repository

```bash
# Clone via HTTPS
git clone https://github.com/merkuriddg/m1_erp.git
cd m1_erp

# Or clone via SSH (if configured)
git clone git@github.com:merkuriddg/m1_erp.git
cd m1_erp
```

### 2. Install Dependencies

```bash
# Install PHP dependencies
composer install

# This installs:
# - PHPUnit (testing)
# - PHPStan (static analysis)
# - PHPCS/PHPMD (code quality)
# - Other dev dependencies
```

### 3. Environment Configuration

```bash
# Copy example environment file
cp .env.example .env.development

# Edit .env.development with your settings
nano .env.development
```

**Required .env settings:**

```bash
# Application
APP_ENV=development
APP_NAME="MERPH"
APP_URL=http://localhost:8080
APP_DEBUG=true

# Database
DB_HOST=localhost
DB_NAME=brickwal_m1_ds
DB_USER=rpmbbu
DB_PASS=your_password_here
DB_CHARSET=utf8mb4

# Session
SESSION_NAME=MERPH_SESSION
SESSION_LIFETIME=7200

# Monitoring
PERFORMANCE_MONITORING=true
DETAILED_PERFORMANCE_LOGGING=false
ALERT_EMAIL=your-email@example.com

# Timezone
TIMEZONE=America/New_York
```

### 4. Database Setup

**Create Database:**

```bash
# Connect to MySQL/MariaDB
mysql -u root -p

# Create database
CREATE DATABASE brickwal_m1_ds CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Create user (optional, if not using root)
CREATE USER 'rpmbbu'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON brickwal_m1_ds.* TO 'rpmbbu'@'localhost';
FLUSH PRIVILEGES;

EXIT;
```

**Run Migrations:**

```bash
# Run all pending migrations
php scripts/run_all_migrations.php

# Should see:
# ✓ Running migration 001...
# ✓ Running migration 002...
# ...
# ✓ All migrations completed successfully
```

**Seed Development Data (Optional):**

```bash
# If seed script exists
php scripts/seed_development_data.php
```

### 5. Web Server Configuration

#### Apache Configuration

**Create Virtual Host** (`/etc/apache2/sites-available/m1-erp.conf`):

```apache
<VirtualHost *:8080>
    ServerName localhost
    DocumentRoot /path/to/m1_erp_web/public
    
    <Directory /path/to/m1_erp_web/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
        
        # Rewrite rules (if .htaccess not working)
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php [QSA,L]
    </Directory>
    
    ErrorLog ${APACHE_LOG_DIR}/m1-erp-error.log
    CustomLog ${APACHE_LOG_DIR}/m1-erp-access.log combined
</VirtualHost>
```

**Enable Site:**

```bash
# Enable site
sudo a2ensite m1-erp

# Enable rewrite module
sudo a2enmod rewrite

# Restart Apache
sudo systemctl restart apache2
```

#### Nginx Configuration

**Create Server Block** (`/etc/nginx/sites-available/m1-erp`):

```nginx
server {
    listen 8080;
    server_name localhost;
    root /path/to/m1_erp_web/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;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\.ht {
        deny all;
    }
    
    error_log /var/log/nginx/m1-erp-error.log;
    access_log /var/log/nginx/m1-erp-access.log;
}
```

**Enable Site:**

```bash
# Symlink site
sudo ln -s /etc/nginx/sites-available/m1-erp /etc/nginx/sites-enabled/

# Test configuration
sudo nginx -t

# Restart Nginx
sudo systemctl restart nginx
```

### 6. Set Permissions

```bash
# Set correct ownership
sudo chown -R www-data:www-data /path/to/m1_erp_web

# Or for your user
sudo chown -R $USER:$USER /path/to/m1_erp_web

# Set file permissions
chmod -R 755 /path/to/m1_erp_web

# Make writable directories
chmod -R 775 /path/to/m1_erp_web/uploads
chmod -R 775 /path/to/m1_erp_web/logs
chmod -R 775 /path/to/m1_erp_web/debug
```

### 7. Verify Installation

**Test Web Server:**

```bash
# Visit in browser
http://localhost:8080

# Should see login page
```

**Test Database Connection:**

```bash
# Quick PHP test
php -r "
require_once 'core/Database.php';
try {
    \$db = Database::getInstance();
    echo 'Database connected successfully!';
} catch (Exception \$e) {
    echo 'Error: ' . \$e->getMessage();
}
"
```

**Test Health Check:**

```bash
# Check system health
curl http://localhost:8080/api/health | jq

# Should return:
# {
#   "status": "healthy",
#   "timestamp": 1234567890,
#   "checks": {
#     "database": "ok",
#     "filesystem": "ok"
#   }
# }
```

## Development Tools

### Run Tests

```bash
# Run all tests
composer test

# Run specific test file
./vendor/bin/phpunit tests/Unit/DatabaseTest.php

# Run with coverage
composer test:coverage
```

### Code Quality Checks

```bash
# Run all quality checks
composer quality

# Individual tools
composer phpstan      # Static analysis
composer phpcs        # Coding standards
composer phpmd        # Mess detection

# Auto-fix code style
composer quality:fix
```

### Pre-commit Hook

**Install Git Hook:**

```bash
# Hook is auto-installed by composer
# Or manually:
cp .git/hooks/pre-commit.sample .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
```

**The hook runs:**
- PHPStan on staged files
- PHPCS on staged files
- Blocks commit if issues found

### Database Management

**Create New Migration:**

```bash
# Via System Scripts UI (recommended)
# Visit: http://localhost:8080/admin/system-scripts
# Click: "Create New Migration"

# Or get next migration number
mysql -u rpmbbu -p brickwal_m1_ds -e "SELECT MAX(migration_number) + 1 FROM migration_log"

# Create file: database/migrations/XXX_description.sql
```

**Run Migrations:**

```bash
# Run all pending
php scripts/run_all_migrations.php

# Check migration status
php scripts/compare_migrations.php
```

**Rollback Migration (Manual):**

```bash
# Connect to database
mysql -u rpmbbu -p brickwal_m1_ds

# Delete from log
DELETE FROM migration_log WHERE migration_number = XXX;

# Manually reverse changes in database
```

## IDE Setup (PHPStorm)

### Configure PHPStorm

**1. Open Project:**
- File → Open → Select `m1_erp_web` directory

**2. Configure PHP Interpreter:**
- Settings → PHP → CLI Interpreter
- Add Local → PHP 8.2+
- Apply

**3. Configure Database:**
- View → Tool Windows → Database
- Add → MySQL/MariaDB
- Host: localhost, Port: 3306
- Database: brickwal_m1_ds
- Test Connection

**4. Enable Composer:**
- Settings → PHP → Composer
- Path: /path/to/composer.phar or composer
- Apply

**5. Configure PHPStan:**
- Settings → PHP → Quality Tools → PHPStan
- Configuration file: `phpstan.neon`
- Level: 5

**6. Configure PHPCS:**
- Settings → PHP → Quality Tools → PHP_CodeSniffer
- Coding standard: PSR-12
- Enable inspection

### Recommended Plugins

- **PHP Annotations**: Better PHPDoc support
- **.env files support**: Syntax highlighting for .env
- **Database Navigator**: Enhanced database tools
- **GitToolBox**: Better Git integration

## Troubleshooting

### Common Issues

**1. Database Connection Failed**

```bash
# Check MySQL is running
sudo systemctl status mysql

# Check credentials in .env.development
cat .env.development | grep DB_

# Test connection
mysql -u rpmbbu -p -h localhost brickwal_m1_ds
```

**2. 500 Internal Server Error**

```bash
# Check Apache/Nginx error logs
tail -f /var/log/apache2/m1-erp-error.log
# or
tail -f /var/log/nginx/m1-erp-error.log

# Check PHP error logs
tail -f /var/log/php8.2-fpm.log

# Check application logs
tail -f logs/error-$(date +%Y-%m-%d).log
```

**3. Permission Denied**

```bash
# Fix ownership
sudo chown -R $USER:www-data /path/to/m1_erp_web

# Fix permissions
chmod -R 755 /path/to/m1_erp_web
chmod -R 775 uploads/ logs/ debug/
```

**4. Composer Install Fails**

```bash
# Update composer
composer self-update

# Clear cache
composer clear-cache

# Install with verbose output
composer install -vvv
```

**5. Migrations Fail**

```bash
# Check migration log
mysql -u rpmbbu -p brickwal_m1_ds -e "SELECT * FROM migration_log ORDER BY applied_at DESC LIMIT 10"

# Check for syntax errors
php -l database/migrations/XXX_file.sql

# Run migrations with debug
php scripts/run_all_migrations.php
```

## Next Steps

After setup is complete:

1. **Read Architecture Docs**: `docs/ARCHITECTURE.md`
2. **Review Code Standards**: `docs/CODE_QUALITY.md`
3. **Run Tests**: `composer test`
4. **Start Development**: Create a feature branch
5. **Read Contributing Guide**: `docs/CONTRIBUTING.md`

## Getting Help

- **Documentation**: Check `docs/` directory
- **GitHub Issues**: Report bugs/request features
- **Code Review**: Submit PR for review
- **System Scripts**: `http://localhost:8080/admin/system-scripts`

## Useful Commands

```bash
# Start development
git checkout -b feature/your-feature
composer quality
composer test

# Before committing
composer quality:fix
git add .
git commit -m "Your message"

# Push and create PR
git push origin feature/your-feature
```

---

**Setup Complete!** You're ready to start developing. 🚀
