# Developer Quick Start Guide

## Elohome Development Setup in 5 Minutes

### 1️⃣ Initial Setup
```bash
cd /workspaces/elohome-ecommerce

# Install PHP dependencies
composer install

# Copy environment file
cp .env.example .env

# Generate encryption key
php artisan key:generate
```

### 2️⃣ Database Setup
```bash
# Create database
mysql -u root -p -e "CREATE DATABASE elohome_ecommerce;"

# Run migrations
php artisan migrate

# Seed with sample data
php artisan db:seed
```

### 3️⃣ Frontend Setup
```bash
# Install Node dependencies
npm install

# Build assets
npm run dev    # Development with watch
npm run build  # Production build
```

### 4️⃣ Start Development
```bash
# In one terminal
php artisan serve

# In another terminal (optional)
npm run dev

# Access http://localhost:8000
```

### 5️⃣ Admin Panel Access
```
URL: http://localhost:8000/admin/dashboard
Email: admin@elohome.rw
Password: password123
```

---

## Common Development Tasks

### Add a New Product
```bash
# Create migration
php artisan make:migration create_products_table

# Create model
php artisan make:model Product

# Create controller
php artisan make:controller ProductController
```

### Create a New Feature
```bash
# 1. Create migration for database changes
php artisan make:migration add_new_field_to_products_table

# 2. Update model relationships
vim app/Models/Product.php

# 3. Create controller
php artisan make:controller NewFeatureController

# 4. Add routes
vim routes/web.php

# 5. Create views
mkdir resources/views/new-feature
vim resources/views/new-feature/index.blade.php

# 6. Run migration
php artisan migrate
```

### Clear Cache & Config
```bash
php artisan cache:clear
php artisan config:clear
php artisan view:clear
php artisan route:clear
```

### Generate API Documentation
```bash
# Using Scribe
php artisan scribe:generate
```

### Run Tests
```bash
# Run all tests
php artisan test

# Run specific test
php artisan test tests/Feature/ProductTest.php

# Run with coverage
php artisan test --coverage
```

---

## Key File Locations

| Purpose | Location |
|---------|----------|
| Models | `/app/Models/` |
| Controllers | `/app/Http/Controllers/` |
| Routes | `/routes/web.php`, `/routes/api.php` |
| Views | `/resources/views/` |
| Database | `/database/migrations/`, `/database/seeders/` |
| Config | `/config/` |
| Services | `/app/Services/` |
| Requests | `/app/Http/Requests/` |
| Middleware | `/app/Http/Middleware/` |
| Tests | `/tests/` |

---

## Useful Commands

### Database
```bash
php artisan migrate              # Run migrations
php artisan migrate:rollback     # Rollback last batch
php artisan migrate:refresh      # Rollback all and re-migrate
php artisan migrate:fresh --seed # Fresh database with seeds
php artisan tinker               # Interactive shell
```

### Models & Factories
```bash
php artisan make:model Product        # Create model
php artisan make:model Product -m     # With migration
php artisan make:model Product -mcs   # With migration, controller, seeder
php artisan make:factory ProductFactory
```

### Controllers
```bash
php artisan make:controller ProductController
php artisan make:controller Admin/ProductController  # Nested
php artisan make:controller ProductController --resource  # RESTful
php artisan make:controller ProductController --model=Product
```

### Requests & Rules
```bash
php artisan make:request StoreProductRequest
php artisan make:rule UniqueEmail
```

### Mail & Notifications
```bash
php artisan make:mail OrderConfirmation
php artisan make:notification OrderShipped
```

### Queue & Jobs
```bash
php artisan make:job SendEmail
php artisan queue:work  # Process queued jobs
```

### Misc
```bash
php artisan route:list                    # List all routes
php artisan route:cache                   # Cache routes
php artisan storage:link                  # Create storage symlink
php artisan make:seeder CategorySeeder
php artisan db:seed --class=CategorySeeder
```

---

## Database Schema Quick Reference

### Users
```sql
id, first_name, last_name, email, phone, password
date_of_birth, gender, avatar
email_verified_at, is_active, last_login_at
language_preference, currency_preference
provider, provider_id, timestamps
```

### Products
```sql
id, sku (unique), name, slug
description, short_description
category_id, brand_id
price, cost_price, discount_price, discount_percentage
quantity, status, featured
image, specifications (JSON)
views_count, rating_count, average_rating
warranty_months
meta_title, meta_description, meta_keywords
timestamps, soft_deletes
```

### Orders
```sql
id, order_number (unique), user_id
status, payment_status
billing_address_id, shipping_address_id
shipping_method, shipping_cost
subtotal, tax_amount, discount_amount, total_amount
notes, tracking_number
shipped_at, delivered_at, timestamps
```

### Order Items
```sql
id, order_id, product_id
quantity, price, discount_amount, tax_amount, total_amount
product_snapshot (JSON)
timestamps
```

### Other Tables
- categories, brands, product_images
- carts, wishlist_items, addresses
- reviews, payments, coupons
- banners, blogs, notifications

---

## Testing Checklist

### Unit Tests
- [ ] Model relationships
- [ ] Model scopes
- [ ] Service layer logic
- [ ] Validation rules

### Feature Tests
- [ ] User registration
- [ ] User login
- [ ] Product browsing
- [ ] Cart operations
- [ ] Order creation
- [ ] Payment processing

### API Tests
- [ ] GET product list
- [ ] POST create order
- [ ] Auth token validation
- [ ] Error handling

---

## Git Workflow

### Creating a Feature
```bash
# Create feature branch
git checkout -b feature/product-search

# Make changes, commit
git add .
git commit -m "Add product search"

# Push branch
git push origin feature/product-search

# Create Pull Request on GitHub
```

### Commit Message Format
```
<type>(<scope>): <subject>

<body>

<footer>
```

Types: feat, fix, docs, style, refactor, test, chore

Example:
```
feat(products): add advanced search functionality

Implement full-text search with filters for:
- Category filtering
- Price range filtering
- Brand selection

Fixes #123
```

---

## Debugging Tips

### Enable Debug Mode
```bash
# .env
APP_DEBUG=true
```

### Log Output
```php
Log::emergency('Emergency message');
Log::alert('Alert message');
Log::critical('Critical message');
Log::error('Error message');
Log::warning('Warning message');
Log::notice('Notice message');
Log::info('Info message');
Log::debug('Debug message');
```

### Tinker Shell
```bash
php artisan tinker

# Try database queries
>>> App\Models\Product::count()
>>> App\Models\Product::where('status', true)->first()
>>> User::find(1)->orders
```

### Browser Debugging
```javascript
// Laravel Debugbar
// Automatically shows in development

// Vue DevTools Browser Extension
// Install for Vue.js debugging

// Chrome DevTools
// F12 for JavaScript debugging
```

---

## Performance Tips

### Query Optimization
```php
// Eager load relationships
Product::with('category', 'brand')->get();

// Use select to limit columns
Product::select('id', 'name', 'price')->get();

// Chunk large datasets
Product::chunk(100, function($products) {
    // Process each chunk
});
```

### Caching
```php
// Cache query results
$products = Cache::remember('products', now()->addHours(1), function() {
    return Product::all();
});

// Invalidate cache
Cache::forget('products');
```

### Database
```bash
# Add database indexes for frequently searched columns
php artisan make:migration add_indexes_to_products_table
```

---

## Security Checklist

- [ ] Validate all user inputs
- [ ] Use password hashing (bcrypt)
- [ ] Enable CSRF protection
- [ ] Validate file uploads
- [ ] Use rate limiting
- [ ] Keep dependencies updated
- [ ] Use environment variables for secrets
- [ ] Remove debug information in production
- [ ] Use HTTPS in production
- [ ] Regular security audits

---

## File Structure Best Practices

```
app/
├── Models/              # Eloquent models
├── Http/
│   ├── Controllers/     # Request handlers
│   ├── Requests/        # Form validation
│   ├── Resources/       # API responses
│   └── Middleware/      # Request filters
├── Services/            # Business logic
├── Exceptions/          # Custom exceptions
├── Events/              # Event classes
├── Listeners/           # Event listeners
├── Mail/                # Mailable classes
└── Providers/           # Service providers
```

---

## Recommended VSCode Extensions

- Laravel Extension Pack
- PHP Intelephense
- Database Client
- Thunder Client (API testing)
- Prettier (Code formatting)
- ESLint (JavaScript linting)
- Vue Volar (Vue.js support)
- Better Comments

---

## Useful Resources

- [Laravel Documentation](https://laravel.com/docs)
- [Laravel Ecosystem](https://laravel.io)
- [Spatie Packages](https://spatie.be/opensource)
- [Stripe Documentation](https://stripe.com/docs)
- [Tailwind CSS](https://tailwindcss.com)
- [Vue.js Guide](https://vuejs.org)

---

## Troubleshooting

### Port 8000 Already in Use
```bash
php artisan serve --port=8001
```

### Clear All Cache
```bash
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
```

### Permission Denied Storage
```bash
sudo chown -R www-data:www-data storage bootstrap/cache
chmod -R 775 storage bootstrap/cache
```

### Database Connection Failed
```bash
# Check .env credentials
# Verify MySQL is running
# Try creating fresh database
mysql -u root -p -e "DROP DATABASE IF EXISTS elohome_ecommerce; CREATE DATABASE elohome_ecommerce;"
php artisan migrate:fresh --seed
```

---

**Happy Coding! 🚀**

For support, contact: support@elohome.rw
