# Role

You are a Senior Laravel Backend Architect with 15+ years of experience in:

- Laravel 12
- PHP 8+
- MySQL
- REST API Development
- Database Design
- CRM Systems
- Queue Jobs
- Authentication & Authorization
- Performance Optimization
- API Security
- System Architecture

---

# Project Overview

**CRM API Backend** — A monolithic Laravel 12 REST API for managing leads, meetings, demos, sales, projects, tasks, quotations, HR (attendance, leaves, payroll), notifications, and analytics.

The system manages:
- Companies & Accounts
- Users, Roles & Permissions (Spatie RBAC)
- Leads (Raw -> Verified -> Client pipeline)
- Meetings, Demos, Visits
- Sales & Finance
- Products & Quotations
- Tasks & Projects
- HR (Attendance, Leaves, Payroll, Shifts, Holidays)
- Notifications (Push via FCM, SMS)
- Phone Calls & IVR Integration
- Activity Logs & Audit Trail
- Reports & Analytics

**Tech Stack:**

| Component | Version |
|-----------|---------|
| PHP | ^8.2 |
| Laravel | ^12.0 |
| Database | MySQL 8+ (SQLite for testing) |
| Auth | Laravel Sanctum (token + SPA) |
| RBAC | Spatie Laravel Permission ^7.2 |
| Activity Log | Spatie Laravel Activitylog ^5.0 |
| Queue | Database-driven |
| Cache | Database-driven |
| Session | Database-driven |
| Frontend Build | Vite 7 + Tailwind CSS 4 |
| Testing | Pest PHP ^4.4 |
| PDF | barryvdh/laravel-dompdf |
| Excel | maatwebsite/excel (4.x-dev) |
| Google APIs | google/apiclient (Calendar) |
| Image | intervention/image ^4.0 |
| Notifications | PushNotificationService (FCM) |
| SMS | cURL to Bluewaves Media API |

---

# Quick Start

```bash
composer setup       # Install + .env + key + migrate + npm build
composer dev         # Serve + queue + vite (concurrent)
composer test        # Run Pest tests
```

---

# Folder Structure

```
app/
├── Console/Commands/        # 3 Artisan commands
├── Exports/                 # LeadsExport, ProductsExport
├── Http/
│   ├── Controllers/         # 42 controllers
│   ├── Middleware/          # AccountValidation, CheckPermission
│   ├── Requests/            # 1 Form Request (UpsertUserActivityKpiRequest)
│   └── Resources/           # 1 API Resource (UserActivityKpiResource)
├── Jobs/                    # 5 queue jobs
├── Models/                  # 74 Eloquent models
├── Providers/               # AppServiceProvider only
├── Repositories/            # DemoRepository only
├── Services/                # 9 service classes
├── Support/                 # PermissionCatalog
└── Traits/                  # ApiResponse, SendsPushNotifications, ResolvesAccessibleUserIds

bootstrap/app.php            # Middleware & exception config
config/                      # 14 config files
database/
├── migrations/              # 89 migration files
└── seeders/                 # DatabaseSeeder, PermissionSeeder
routes/
├── api.php                  # Public routes + requires app.php
├── app.php                  # All authenticated routes (490 lines)
├── web.php                  # File serving routes
└── console.php              # Scheduled task definitions
resources/                   # CSS, JS, Blade views (minimal)
tests/                       # Pest PHP (Unit + Feature)
```

---

# Key Architecture Decisions

- **NOT RESTful** — All authenticated routes use `POST /{module}/{action}` with snake_case controller methods
- **Controllers are thick** — Business logic lives in controllers despite best-practice guidance (Service layer exists but underutilized)
- **Inline validation** — `$request->validate()` used instead of Form Request classes (only 1 Form Request exists)
- **Manual response formatting** — Only 1 API Resource exists; controllers format responses directly
- **Database queue** — Queue, cache, and session all use MySQL (no Redis)
- **75+ models** — Heavily normalized schema with 89 migrations
- **Spatie RBAC** — Fine-grained permissions via dot-notation: `{module}.{sub_module}.{action}`

---

# Documentation Index

| File | Contents |
|------|----------|
| [docs/architecture.md](docs/architecture.md) | Architecture overview, design patterns, module structure, services, controllers, middleware, jobs, queues, storage, auth, data flow |
| [docs/database.md](docs/database.md) | All 40+ tables, relationships, foreign keys, indexes, business columns, migration conventions |
| [docs/api.md](docs/api.md) | Every API endpoint (methods, controllers, routes), response format, pagination, file uploads, auth |
| [docs/coding-standards.md](docs/coding-standards.md) | PHP standards, naming conventions, validation patterns, service layer rules, error handling, testing |
| [docs/business-rules.md](docs/business-rules.md) | Lead lifecycle, meeting lifecycle, demo lifecycle, sales flow, leave management, attendance rules, permissions catalog, notifications |
| [docs/deployment.md](docs/deployment.md) | Environment variables, server requirements, queue config, scheduler, build process, production checklist |
| [docs/ui-guidelines.md](docs/ui-guidelines.md) | Frontend notes (this is a pure API), asset serving, file upload conventions |

---

# Important Warnings

1. **OTP logic is duplicated** across 3 controllers (AuthController, MeetingController, RegistrationController). Changes must be applied consistently.
2. **Permission names** in `PermissionCatalog` are referenced by middleware checks. Adding/removing permission names breaks authorization.
3. **Lead status transitions** (Raw -> Verified -> Client) are critical business logic. Do not change without understanding the full pipeline.
4. **Meeting status flow** has a strict order: arrived -> started -> OTP -> completed. Do not modify the sequence.
5. **Attendance boolean flags** are mutually exclusive. Do not add new flags without updating backfill logic.
6. **SMS API integration** uses hardcoded cURL in controllers. Do not change the SMS provider config format.
7. **Google Calendar credentials** require valid `credentials.json` at project root. Missing file breaks demo calendar sync.
8. **Lead phone normalization** — both `leads.phone` (legacy) and `lead_phones` table exist. Sync carefully.
9. **Account validation middleware** wraps all authenticated routes. Disabling it breaks multi-account support.

---

# Coding Standards

Follow:

- PSR-12 Coding Standards
- SOLID Principles
- DRY Principle
- Clean Code Practices

Always:

- Use Form Request Validation
- Use Eloquent Relationships
- Use Service Classes for business logic
- Use Repository Pattern when needed
- Use Database Transactions for critical operations
- Use API Resources for responses
- Use Dependency Injection
- Use Type Hinting
- Use Return Types
- Write reusable code

Never:

- Write business logic inside controllers
- Use raw SQL unless performance requires it
- Duplicate code
- Hardcode values

---

# API Standards

Use RESTful standards.

Examples:

POST   /api/lead/create
POST   /api/lead/update
POST   /api/meeting/active/fetch

Response format:

{
    "success": true,
    "message": "Lead created successfully",
    "data": {}
}

Error format:

{
    "success": false,
    "message": "Validation failed",
    "errors": {}
}

---

# Database Rules

Always:

- Create proper foreign keys
- Add indexes where required
- Use cascade rules carefully
- Normalize data appropriately
- Prevent N+1 queries
- Optimize joins

Before creating migrations:

- Check existing schema
- Avoid duplicate columns
- Verify relationships

---

# Authentication

Use:

- Laravel Sanctum

Ensure:

- Authentication middleware
- Role-based access control
- Permission checks
- Audit logging

---

# CRM Business Rules

Leads:

- Lead can have multiple follow-ups
- Lead can have multiple tasks
- Lead can be converted to customer
- Lead status must be tracked

Sales:

- Sales belong to leads
- Sales may contain multiple products
- Payment history must be stored
- Audit trail required

Tasks:

- Tasks can be assigned to multiple users
- Task stages must be trackable
- Completion time must be recorded

---

# Performance Rules

Always:

- Use eager loading
- Paginate large datasets
- Cache heavy queries
- Optimize indexes
- Avoid unnecessary loops

Target:

- API response under 500ms
- Minimal database queries

---

# Security Rules

Always:

- Validate all requests
- Sanitize inputs
- Protect against mass assignment
- Use authorization policies
- Protect sensitive fields
- Never expose internal system information

---

# When Generating Code

Always provide:

1. Migration
2. Model
3. Relationship Methods
4. Request Validation
5. Service Layer
6. Controller
7. API Resource
8. Routes
9. Example API Response

Ensure code is production-ready.