# GengSewa - Complete Setup & Production Guide

**Rental Platform powered by Laravel + Livewire**
**Version:** 1.0
**Last Updated:** October 2025

---

## Table of Contents

1. [Quick Start](#quick-start)
2. [Requirements](#requirements)
3. [Installation](#installation)
4. [Configuration](#configuration)
5. [Security Setup](#security-setup)
6. [Payment Gateway (BayarCash)](#payment-gateway-bayarcash)
7. [Production Deployment](#production-deployment)
8. [Admin Panel](#admin-panel)
9. [Troubleshooting](#troubleshooting)

---

## Quick Start

### Installation Steps

```bash
# 1. Clone repository
git clone <repository-url> gengsewa
cd gengsewa

# 2. Install dependencies
composer install
npm install

# 3. Setup environment
cp .env.example .env
php artisan key:generate

# 4. Configure database in .env
# Then run migrations
php artisan migrate --seed

# 5. Create storage link
php artisan storage:link

# 6. Build assets
npm run build

# 7. Start server
php artisan serve
```

Visit: **http://localhost:8000**

### Demo Account

After seeding, login with:
- **Email**: `host@example.com`
- **Password**: `password`

---

## Requirements

### Server Requirements

- **PHP** >= 8.2
- **Composer** >= 2.0
- **Node.js** >= 18.x
- **Database**: MySQL >= 8.0 or MariaDB >= 10.3

### PHP Extensions Required

```
BCMath
Ctype
Fileinfo
JSON
Mbstring
OpenSSL
PDO
Tokenizer
XML
cURL
GD or Imagick (for image processing)
```

### Composer Packages

**Core Dependencies:**
- `laravel/framework` ^12.0 - Laravel framework
- `livewire/livewire` ^3.6 - Real-time components
- `webimpian/bayarcash-php-sdk` ^2.0 - Payment gateway integration
- `maatwebsite/excel` ^1.1 - CSV export functionality
- `aws/aws-sdk-php` ^3.356 - AWS services (S3, SES)

**Development Only:**
- `laravel/breeze` ^2.3 - Authentication scaffolding
- `laravel/pail` ^1.2 - Log viewer

---

## Installation

### 1. Clone and Install

```bash
git clone <repository-url> gengsewa
cd gengsewa
composer install
npm install
```

### 2. Environment Configuration

```bash
cp .env.example .env
php artisan key:generate
```

Edit `.env` file:

```env
APP_NAME="GengSewa"
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost:8000

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=gengsewa
DB_USERNAME=root
DB_PASSWORD=

# BayarCash Payment Gateway
BAYARCASH_PORTAL_KEY=your_portal_key
BAYARCASH_PAT=your_personal_access_token
BAYARCASH_SECRET_KEY=your_secret_key
BAYARCASH_MODE=sandbox

# Mail Configuration (optional for local dev)
MAIL_MAILER=log
MAIL_FROM_ADDRESS=noreply@gengsewa.com
MAIL_FROM_NAME="${APP_NAME}"
```

### 3. Database Setup

```bash
# Create database
mysql -u root -p
CREATE DATABASE gengsewa CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
EXIT;

# Run migrations and seed sample data
php artisan migrate:fresh --seed
```

**Seeded Data:**
- 4 Rental Types (Car, Houseboat, Guesthouse, Boat)
- 5 Locations (Langkawi, Penang, Kuala Lumpur, Melaka, Johor Bahru)
- 3 Sample Listings
- 1 Host Account (host@example.com / password)

### 4. Storage & Assets

```bash
# Create storage link
php artisan storage:link

# Build frontend assets
npm run build

# For development with hot reload
npm run dev
```

### 5. File Permissions

```bash
chmod -R 755 storage bootstrap/cache
```

On Linux/Mac:
```bash
chown -R www-data:www-data storage bootstrap/cache
```

---

## Configuration

### Admin Settings

Access: **http://localhost:8000/admin/settings**

**General Settings:**
- Site Name & Logo
- Footer Text
- Logo Display Mode (Logo Only, Name Only, Both)

**Payment & Fees:**
- BayarCash Credentials (Portal Key, PAT, Secret Key)
- Platform Fee (Fixed RM or Percentage %)
- Fee Charged To (Guest or Host)
- Outgoing Webhooks

**SEO & Branding:**
- Meta Title & Description
- Favicon
- Theme Mode (Light/Dark/System)
- Primary Brand Color
- Google Analytics ID

**Receipt Settings:**
- Template Selection (Professional or Compact)
- Company Name, Address, Phone, Email
- Website URL
- Footer Text
- Show/Hide Logo

---

## Security Setup

### CSRF Protection (Enabled by Default)

Laravel automatically protects all POST/PUT/DELETE requests with CSRF tokens.

### XSS Protection

All Blade templates use automatic escaping:
```blade
{{ $variable }} <!-- Escaped (safe) -->
{!! $variable !!} <!-- Unescaped (use carefully) -->
```

### SQL Injection Protection

Always use Eloquent ORM or Query Builder with parameter binding:
```php
// ✅ Safe - uses parameter binding
User::where('email', $email)->first();
Booking::where('id', $id)->update(['status' => 'confirmed']);

// ❌ Unsafe - never use raw SQL with user input
DB::raw("SELECT * FROM users WHERE email = '$email'");
```

### Rate Limiting

Laravel includes rate limiting by default. Check `app/Http/Kernel.php`:

```php
'api' => [
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],
```

To add custom rate limiting to routes:
```php
Route::middleware(['throttle:10,1'])->group(function () {
    // Max 10 requests per minute
});
```

### Security Headers

Add to `config/cors.php` if needed, or configure in your web server.

**Recommended Nginx Configuration:**
```nginx
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
```

### Input Validation

Always validate user inputs in Livewire components:

```php
public function save()
{
    $this->validate([
        'title' => 'required|string|max:255',
        'price' => 'required|numeric|min:0',
        'email' => 'required|email',
    ]);

    // Safe to save...
}
```

### Password Hashing

Laravel automatically hashes passwords using bcrypt. Never store plain-text passwords.

```php
// Hashing
$user->password = Hash::make($password);

// Verification
if (Hash::check($plainPassword, $user->password)) {
    // Password correct
}
```

---

## Payment Gateway (BayarCash)

### Setup

1. **Sign up**: https://bayarcash.com
2. **Get Credentials**:
   - Portal Key (Portal ID)
   - Personal Access Token (PAT) - up to 1000 characters
   - Secret Key

3. **Configure via Admin Panel**:
   - Go to Admin > Settings > Payment & Fees
   - Enter credentials
   - Save

4. **Or configure via .env**:
```env
BAYARCASH_PORTAL_KEY=your_portal_key
BAYARCASH_PAT=your_long_personal_access_token
BAYARCASH_SECRET_KEY=your_secret_key
BAYARCASH_MODE=sandbox  # Change to 'production' for live
```

### Payment Flow

1. Guest creates booking (status: pending)
2. Redirected to BayarCash payment page
3. Guest completes payment via FPX/Card/eWallet
4. BayarCash sends webhook to `/payment/callback`
5. System updates booking status to 'confirmed'
6. Confirmation email sent

### Webhook Configuration

**Callback URL**: `{APP_URL}/payment/callback`

Configure this URL in your BayarCash dashboard.

### Testing Payments

Use BayarCash sandbox mode with test credentials. Real money is NOT charged in sandbox mode.

---

## Production Deployment

### Pre-Deployment Checklist

```bash
# ✅ Environment
- [ ] Set APP_ENV=production
- [ ] Set APP_DEBUG=false
- [ ] Set APP_URL to production domain
- [ ] Configure production database
- [ ] Set up SSL certificate (HTTPS)
- [ ] Change BAYARCASH_MODE=production
- [ ] Configure production mail server
```

### Optimization

```bash
# Clear all caches
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear

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

# Optimize Composer autoloader
composer install --optimize-autoloader --no-dev

# Build production assets
npm run build
```

### File Permissions

```bash
chmod -R 755 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
chmod 600 .env
```

### Cron Job

Add to crontab (`crontab -e`):

```bash
* * * * * cd /path-to-gengsewa && php artisan schedule:run >> /dev/null 2>&1
```

### Queue Worker (Supervisor)

Create `/etc/supervisor/conf.d/gengsewa-worker.conf`:

```ini
[program:gengsewa-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /path-to-gengsewa/artisan queue:work --sleep=3 --tries=3
autostart=true
autorestart=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/path-to-gengsewa/storage/logs/worker.log
```

Then:
```bash
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start gengsewa-worker:*
```

### Security Checklist

```bash
# ✅ Security
- [ ] Enable HTTPS (force SSL)
- [ ] Change default passwords
- [ ] Remove demo accounts
- [ ] Set secure session configuration
- [ ] Enable rate limiting
- [ ] Configure firewall
- [ ] Set up automated backups
- [ ] Enable error monitoring (Sentry/Bugsnag)
```

### Web Server Configuration

**Nginx Example** (`/etc/nginx/sites-available/gengsewa`):

```nginx
server {
    listen 80;
    listen [::]:80;
    server_name gengsewa.com www.gengsewa.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name gengsewa.com www.gengsewa.com;
    root /var/www/gengsewa/public;

    ssl_certificate /etc/letsencrypt/live/gengsewa.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/gengsewa.com/privkey.pem;

    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;

    index index.php;

    charset utf-8;

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

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

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

Enable and restart:
```bash
sudo ln -s /etc/nginx/sites-available/gengsewa /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
```

---

## Admin Panel

### Access

**URL**: `/admin`

**Default Admin**: Must be set via database or change user role to 'admin'

```sql
UPDATE users SET role = 'admin' WHERE email = 'your@email.com';
```

### Features

**Dashboard:**
- Total users, hosts, listings, bookings
- Revenue statistics
- Recent bookings

**Manage:**
- Rental Types (Car, Boat, Villa, etc.)
- Locations (Cities/Areas)
- Users (View, Edit, Change Roles)
- Bookings (Approve, Complete, Cancel)
- Listings (All host listings)

**Settings:**
- General (Site name, logo, footer)
- Payment & Fees (BayarCash credentials, platform fee)
- SEO & Branding (Meta tags, theme, colors)
- Receipt Templates (Professional or Compact design)

**Bookings Management:**
- View all bookings
- Filter by status, date range
- Export to CSV
- View receipts
- Update booking status

---

## Troubleshooting

### Common Issues

**500 Internal Server Error**

```bash
# Check logs
tail -50 storage/logs/laravel.log

# Clear all caches
php artisan config:clear
php artisan cache:clear
php artisan view:clear
php artisan route:clear
```

**Database Connection Error**

- Verify `.env` database credentials
- Check MySQL service is running: `sudo systemctl status mysql`
- Test connection: `mysql -u root -p -e "SHOW DATABASES;"`

**Permission Denied**

```bash
chmod -R 755 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
```

**Payment Not Working**

- Verify BayarCash credentials in Admin Settings
- Check webhook URL is publicly accessible
- Review logs: `storage/logs/laravel.log`
- Ensure BAYARCASH_MODE matches environment

**Assets Not Loading**

```bash
npm install
npm run build
php artisan storage:link
```

Clear browser cache (Ctrl+Shift+R)

**Livewire Component Not Found**

```bash
php artisan livewire:discover
php artisan view:clear
```

---

## Important Files & Directories

### Configuration
- `.env` - Environment variables
- `config/` - Laravel configuration files

### Application Code
- `app/Livewire/` - Livewire components (Admin, Host pages)
- `app/Models/` - Database models
- `app/Http/Controllers/` - Controllers
- `app/Helpers/` - Helper classes

### Views
- `resources/views/` - Blade templates
- `resources/views/livewire/` - Livewire component views

### Assets
- `resources/css/app.css` - Tailwind CSS
- `resources/js/app.js` - Alpine.js initialization
- `public/` - Public assets

### Image Storage
- `public/images/flags/` - Country flags (keep with .gitkeep)
- `public/images/logos/` - Site logos
- `public/images/listings/` - Listing images
- `public/images/favicon/` - Favicons
- `public/images/og-images/` - Social media preview images

**Note**: All image directories include `.gitkeep` files to preserve folder structure in Git.

### Database
- `database/migrations/` - Database migrations
- `database/seeders/` - Database seeders

---

## Support & Resources

- **Laravel Docs**: https://laravel.com/docs
- **Livewire Docs**: https://livewire.laravel.com
- **BayarCash SDK**: https://github.com/webimpian/bayarcash-php-sdk
- **Tailwind CSS**: https://tailwindcss.com

---

## Version History

**v1.0** - October 2025
- Initial release
- BayarCash payment integration
- Admin panel with settings
- Booking management with CSV export
- Professional receipt templates
- Role-based access (Admin, Host, Guest)

---

**© 2025 GengSewa. All rights reserved.**
