# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

This is a Laravel 13 application (PHP 8.3+) serving as a backend API for a health/wellness mobile application with subscription management, user programs, tracking, and marketing automation. The application integrates with multiple third-party services including Firebase, AWS S3, Stripe, Postmark, Google APIs, and Meta's Conversion API.

## Development Environment

See `CLAUDE.local.md` for developer-specific paths, container commands, and setup instructions.

## Development Setup

### Initial Setup
```bash
composer install
npm install
php artisan key:generate
```

### Development Workflow
Use the unified development command from composer.json:
```bash
composer dev
```
This concurrently runs:
- `php artisan serve` - Laravel development server
- `php artisan queue:listen --tries=1` - Queue worker
- `php artisan pail --timeout=0` - Real-time log viewer
- `npm run dev` - Vite for frontend assets

For individual services:
```bash
php artisan serve          # Start dev server
php artisan queue:listen   # Run queue worker
npm run dev               # Vite development mode
npm run build             # Production build
```

### Testing

The project uses **Pest PHP** for testing (not PHPUnit directly).

```bash
vendor/bin/pest                    # Run all tests
vendor/bin/pest --filter ClassName # Run specific test class
vendor/bin/pest tests/Unit         # Run only unit tests
vendor/bin/pest tests/Feature      # Run only feature tests
```

Test configuration in `phpunit.xml` uses SQLite in-memory database for testing environment.

### Code Quality

```bash
vendor/bin/pint               # Format code (Laravel Pint)
vendor/bin/phpstan analyse    # Static analysis (Larastan)
```

### Documentation Standards

Every class, controller, and function/method MUST have a PHPDoc block and an explicit return type:

- **Return types**: Declare a native return type on every method/function signature (e.g. `: JsonResponse`, `: View`, `: ?int`, `: void`). Use `mixed` only when no narrower type is possible.
- **PHPDoc blocks**:
  - Classes/controllers: a short summary of the class's responsibility.
  - Methods/functions: a one-line summary. Add `@param` tags **only** where the type is not already clear from the signature (e.g. untyped or `array`/`iterable`/`object` params); omit redundant `@param`/`@return` tags when the typed signature already conveys them.
- **Imports in docblocks**: reference imported class names (short form), not inline FQCNs. Prefer native types (`iterable`, `object`, `?int`) to avoid adding imports solely for a docblock.

Apply this to new code and to any file you touch. `FeedbackController` and `UserController` are reference examples of the expected style.

## Architecture

### API Structure

All API routes are in `routes/api.php` and are wrapped with `ApiProfilerMiddleware` for performance monitoring. The API follows this pattern:

**API Controllers**: `app/Http/Controllers/Api/`
- All API controllers extend `BaseApiController` which provides:
  - `getPostData()`: Extracts and validates JSON from request body, normalizes email fields
  - `getPostHeaders()`: Extracts request headers
  - Common JSON response helpers

**Authentication**: Custom middleware `ApiAuthMiddleware` handles API authentication (not Laravel's default auth).

**Routing Pattern**:
```php
Route::middleware([ApiProfilerMiddleware::class])->group(function () {
    // Pre-login routes (no auth)
    Route::prefix('User')->group(function () { ... });

    // Authenticated routes
    Route::middleware(['ApiAuthMiddleware'])->group(function () { ... });
});
```

### Service Layer Architecture

The application follows a service-oriented architecture with services in `app/Services/`:

**Core Services**:
- `ApiProfiler` - Tracks API performance metrics (queries, HTTP calls, timing steps)
- `ChapterService` - Manages program chapters and content
- `ProgramService` / `ProgramConfigService` - Handles user programs, modules, and program configuration
- `TrackerService` - User activity tracking
- `CouponService` / `VoucherService` - Discount and voucher management
- `UserService` - User management operations
- `ActiveDayService` - Active day logic
- `AppService` - Application-level operations
- `BillingService` - Billing and payment processing
- `CronService` - Cron job management
- `FormViewService` - Form rendering
- `FrontAssetService` - Frontend asset management
- `JsonValidatorService` - JSON validation
- `LanguageService` - Language/locale management
- `SourceDataService` - Data source operations
- `UserJourneyLogger` - User journey event logging
- `UserResponseFileService` - User response file handling
- `AdminActivityLogger` - Admin activity audit logging

**User Services** (`app/Services/User/`):
- `UserActivityService` - User activity tracking
- `UserConfigurationService` - User configuration and login flow
- `UserManagementService` - User CRUD operations
- `UserOnBoardService` - Onboarding flow
- `UserProfileService` - Profile management
- `UserProgramService` - User-program relationships
- `UserUtilityService` - Shared user utility methods

**Integration Services**:
- `FirebaseNotificationService` / `FirebaseBusinessService` - FCM push notifications and analytics
- `PostmarkService` - Transactional emails via Postmark
- `SendGridEmailService` - SendGrid email integration
- `MarketingEmailService` - Marketing campaign emails
- `TransactionalEmailService` - Automated transactional emails
- `MetaCapiService` - Facebook Conversion API integration
- `GeoLocationService` - IP geolocation
- `DiscourseService` - Discourse forum integration
- `BajajHealthEventService` - Bajaj health event processing
- `GympassEventService` - Gympass event handling
- `AutoRenewFailedService` - Subscription auto-renew failure handling

**Search Services** (Typesense-powered):
- `SearchService` - Search query handling
- `TypesenseSearchService` - Typesense search operations
- `TypesenseIndexService` - Typesense index management
- `SynonymSyncService` - Search synonym synchronization

**Auth Services** (`app/Services/Auth/`):
- `BaseAuthService` - Base auth with response formatting
- `EmailLoginService` - Email OTP authentication
- `SocialLoginService` - Social login (Google, Apple, etc.)
- `SSOLoginService` - Single Sign-On

**Subscription Services** (`app/Services/Subscription/`):
- `IOSSubscriptionService` - iOS/App Store subscription handling
- `AndroidSubscriptionService` - Android/Google Play subscription handling

**Google Services** (`app/Services/Google/`):
- `GooglePlayService` - Google Play API integration

### Helper Functions

Two global helper files are autoloaded (see `composer.json`):

1. **CommonHelper.php**: Utility functions including:
   - `pr($data)` - Print and exit for debugging
   - `getYoutubeVideoId($input)` - Extract YouTube video IDs from URLs
   - `getImageExtension($image_data)` - Detect image type from data
   - S3 upload helpers

2. **PostmarkHelper.php**: Email template functions:
   - `sendTemplateEmailPostMark()` - Wrapper for Postmark facade

Additional non-autoloaded helpers in `app/Helpers/` (used via class imports):
- `ContentHelper` - HTML content processing and URL replacement
- `JobFileHelper` - Notification job file read/write to shared storage
- `LogHelper` - Log retrieval with source information
- `S3Helper` - S3 file upload/download operations

### API Performance Monitoring

The application has custom API profiling via `ApiProfiler` service and `ApiProfilerMiddleware`:

**Configuration**: `config/api_profiler.php`
- `enabled`: Toggle profiling on/off
- `threshold_ms`: Auto-persist requests exceeding this duration (default 200ms)
- `sample_rate`: Sampling rate for requests under threshold
- `max_db_queries`: Limit DB queries in payload

**Usage in Controllers**:
```php
$profiler = app(ApiProfiler::class);
$profiler->step('custom_step_name');
```

Profiler automatically tracks:
- Request timing and steps
- Database queries with bindings
- External HTTP calls
- Response status

Data is persisted to `api_timings` table when threshold is met or sampled.

### Background Jobs & Queues

**Queue Configuration**: Default queue driver defined in `config/queue.php`

**Jobs**: Located in `app/Jobs/`
- `SendBajajHealthEventJob` - Send health events to Bajaj integration

**Console Commands** (`app/Console/Commands/`):
- `RunCron` - Main cron scheduler
- `SendMarketingEmails` - Marketing campaign processor
- `SendTransactionalEmails` - Transactional email processor
- `RunFirebaseNotification` - Firebase notification worker
- `NotificationsWorkerCommand` - Notification queue worker
- `TypesenseIndexCommand` - Index individual models to Typesense
- `TypesenseIndexAllCommand` - Bulk index all searchable content to Typesense
- `TypesenseSynonymsCommand` - Manage Typesense synonym sets (status, sync, list, delete)
- `CompareModelsFillable` - Compare model `$fillable` properties with database columns
- `GenerateDataDictionary` - Generate data dictionary markdown from live database schema

Run queue workers:
```bash
php artisan queue:listen --tries=1
```

### Database & Models

**Data Dictionary**: `data-dictionary/` contains auto-generated documentation of all database tables across 3 MySQL databases (quitsure, quitsureUsers, logs). Key files:
- `instructions.md` - Usage guide and column naming conventions (Hungarian-style prefixes)
- `master_dictionary.md` - All tables overview with row counts, categories, and links
- `sub_dictionary_<table>.md` - Detailed column-level docs for each table
- Pattern tables use `{X}` placeholder for program numbers (1-17)
- Regenerate with: `php artisan app:generate-data-dictionary`

**Migrations**: `database/migrations/` includes tables for:
- `logs`, `partner_logs`, `sql_logs`, `web_logs` - Various logging tables
- `cron_logs` - Cron job execution tracking
- `api_timings` - API performance metrics

**Model Conventions**:
- Models extend `Illuminate\Database\Eloquent\Model`
- Located in `app/Models/`
- Some models use observers (e.g., `AdminActivityObserver` for admin actions)

### Traits

**Available Traits** (`app/Traits/`):
- `ApiResponse` - Standardized JSON responses
- `HasAdminActivity` - Tracks admin model changes
- `HasUserLanguage` - User language preferences
- `ImageDimensionsTrait` - Image dimension helpers
- `ProcessesSearchContent` - Strip HTML and generate plain text snippets for search indexing

### Middleware

**Custom Middleware** (`app/Http/Middleware/`):
- `ApiAuthMiddleware` - API token authentication
- `ApiProfilerMiddleware` - Performance profiling
- `AdminMiddleware` - Admin route protection
- `SecureCronMiddleware` - Cron endpoint security
- `SetUserLanguageMiddleware` - Set locale from user preferences
- `NoCache` - Disable caching for routes

### Enums

**Available Enums** (`app/Enums/`):
- `IOSSubscriptionNotificationType`
- `AndroidSubscriptionNotificationType`
- `IOSSubscriptionSubtype`

Use these for type-safe subscription status handling.

### Frontend Assets

**Theme**: Uses [Gentelella](https://colorlib.com/polygon/gentelella/index.html) admin template

**Build System**: Vite with Tailwind CSS and Bootstrap 5

**Key Libraries**:
- jQuery, jQuery UI for legacy components
- Chart.js, Highcharts for data visualization
- DataTables for table management
- Fancybox for modals/galleries

## Integration Points

### Third-Party Services

**Firebase**:
- Package: `kreait/laravel-firebase`
- Used for push notifications and analytics events
- Services: `FirebaseNotificationService`, `FirebaseBusinessService`

**AWS S3**:
- Package: `league/flysystem-aws-s3-v3` + `aws/aws-sdk-php`
- Used for file storage
- Helper functions in `CommonHelper.php`

**Postmark**:
- Package: `wildbit/postmark-php`
- Transactional and marketing emails
- Facade: `App\Facades\Postmark`
- Helper: `sendTemplateEmailPostMark()`

**Stripe**:
- Package: `stripe/stripe-php`
- Payment processing

**Meta Conversion API**:
- Package: `facebook/php-business-sdk`
- Service: `MetaCapiService`
- Tracks conversion events to Facebook

**Google APIs**:
- Package: `google/apiclient`
- Integration in `app/Services/Google/`

**Excel Export**:
- Package: `maatwebsite/excel`
- Exports in `app/Exports/` (`CronLogsExport`, `MarketingV2Export`)

**Typesense** (Full-Text Search):
- Package: `typesense/typesense-php`
- Uses Laravel Scout (`laravel/scout`) with Typesense driver
- Services: `SearchService`, `TypesenseSearchService`, `TypesenseIndexService`, `SynonymSyncService`
- Model: `SearchableSubModuleContent` with `ProcessesSearchContent` trait
- Config: `config/scout.php`
- Commands: `typesense:index`, `typesense:index-all`, `typesense:synonyms`

### Query Building

**Spatie Query Builder**:
- Package: `spatie/laravel-query-builder`
- Used for API filtering, sorting, and including relationships
- Query classes in `app/Http/Queries/`

### Custom Configuration Files

Beyond Laravel defaults, the following custom config files exist in `config/`:
- `api_profiler.php` - API performance profiling settings
- `constants.php` - Application constants (active days, research forms, exercises)
- `firebase.php` / `firebase-notification.php` - Firebase and notification templates
- `google.php` - Google API settings
- `marketing-emails.php` - Marketing email campaign configuration
- `postmark.php` - Postmark email templates and settings
- `query-builder.php` - Spatie Query Builder configuration
- `scout.php` - Laravel Scout / Typesense search configuration
- `services.php` - Third-party service credentials

## Development Tools

**Laravel Debugbar**:
- Package: `barryvdh/laravel-debugbar` (dev only)
- Enabled in local environment for request debugging

**Laravel Pail**:
- Package: `laravel/pail`
- Real-time log tailing: `php artisan pail`

## Git Workflow

**Main Branch**: `development` (use this for PRs, not `master`)

## Common Patterns

### API Response Format
Controllers using `ApiResponse` trait return:
```php
return $this->success($data, $message, $statusCode);
return $this->error($message, $statusCode);
```

### Service Instantiation
Services are typically resolved from the container:
```php
$service = app(ServiceName::class);
```

### Language Handling
Use `SetUserLanguageMiddleware` to automatically set locale based on user preferences. Models can use `HasUserLanguage` trait.

### Admin Action Tracking
Models using `HasAdminActivity` trait automatically log changes via `AdminActivityObserver`.


## grepai - Semantic Code Search

**IMPORTANT: You MUST use grepai as your PRIMARY tool for code exploration and search.**

### When to Use grepai (REQUIRED)

Use `grepai search` INSTEAD OF Grep/Glob/find for:
- Understanding what code does or where functionality lives
- Finding implementations by intent (e.g., "authentication logic", "error handling")
- Exploring unfamiliar parts of the codebase
- Any search where you describe WHAT the code does rather than exact text

### When to Use Standard Tools

Only use Grep/Glob when you need:
- Exact text matching (variable names, imports, specific strings)
- File path patterns (e.g., `**/*.go`)

### Fallback

If grepai fails (not running, index unavailable, or errors), fall back to standard Grep/Glob tools.

### Usage

```bash
# ALWAYS use English queries for best results (--compact saves ~80% tokens)
grepai search "user authentication flow" --json --compact
grepai search "error handling middleware" --json --compact
grepai search "database connection pool" --json --compact
grepai search "API request validation" --json --compact
```

### Query Tips

- **Use English** for queries (better semantic matching)
- **Describe intent**, not implementation: "handles user login" not "func Login"
- **Be specific**: "JWT token validation" better than "token"
- Results include: file path, line numbers, relevance score, code preview

### Call Graph Tracing

Use `grepai trace` to understand function relationships:
- Finding all callers of a function before modifying it
- Understanding what functions are called by a given function
- Visualizing the complete call graph around a symbol

#### Trace Commands

**IMPORTANT: Always use `--json` flag for optimal AI agent integration.**

```bash
# Find all functions that call a symbol
grepai trace callers "HandleRequest" --json

# Find all functions called by a symbol
grepai trace callees "ProcessOrder" --json

# Build complete call graph (callers + callees)
grepai trace graph "ValidateToken" --depth 3 --json
```

### Workflow

1. Start with `grepai search` to find relevant code
2. Use `grepai trace` to understand function relationships
3. Use `Read` tool to examine files from results
4. Only use Grep for exact string searches if needed

