# AGENTS.md - Development Guidelines

This file contains essential information for AI agents working on this codebase.

## Project Overview

PHP website for "Harmonie de Montpellier-Jacou" (music band) with a Vue.js 2 frontend for score management.
- **Backend**: PHP with MySQL (legacy codebase)
- **Frontend**: Vue.js 2 + Bootstrap Vue (in `frontend/score/`)
- **API**: RESTful PHP API in `api/` directory

## Build Commands

### Frontend (Vue.js)
```bash
cd frontend/score
npm install
npm run serve      # Development server
npm run build      # Production build
npm run lint       # ESLint check
```

### PHP
No build step required. Deploy to PHP-enabled web server.

## Testing

### PHP API Tests

Run functional tests for the PHP API:

```bash
cd api
php tests.php
```

The tests cover:
- **Auth**: Login, bad credentials, missing token, invalid token
- **Scores**: CRUD operations, error handling for non-existent resources
- **Create Score with Pieces**: Functional tests with pieces verification
- **Files**: Get files tree, delete file error handling

### Vue/Svelte

No test framework configured for frontend.

Run single test (when configured):
```bash
# Example for Jest (not yet configured)
npm test -- --testNamePattern="test name"
```

## Code Style Guidelines

### PHP
- Use `<?php` opening tags (avoid short `<?` tags for consistency)
- Classes: PascalCase (e.g., `Score`, `Database`)
- Methods: camelCase (e.g., `readScore`, `getEntryName`)
- Variables: snake_case or camelCase (be consistent within files)
- Indent: 3 spaces (legacy style) - maintain consistency with surrounding code
- Place opening braces on same line as class/function declaration
- Use `include_once` for required files
- **Note**: Uses legacy MySQL functions (consider upgrading to PDO/MySQLi)

### JavaScript/Vue
- ESLint configuration in `package.json`:
  - Extends: `plugin:vue/essential`, `eslint:recommended`
  - Parser: `babel-eslint`
- Use ES6+ features (async/await, arrow functions)
- Components: PascalCase
- Data properties: camelCase
- Use 2-space indentation
- Semicolons required

### General
- UTF-8 encoding for all files
- French language for user-facing content
- Maintain GPL v2 license headers in PHP files

## File Organization

```
/
├── api/              # REST API endpoints
│   ├── config/       # Database configuration
│   ├── objects/      # Data models
│   └── score/        # API endpoints
├── frontend/score/   # Vue.js application
│   ├── src/          # Source code
│   └── public/       # Static assets
├── Scripts/          # PHP page controllers
├── fpdf/             # PDF generation library
├── Imgs/             # Image assets
├── Textes/           # Text content files
└── index.php         # Main entry point
```

## Database

MySQL database connection configured in `api/config/database.php`:
- Uses legacy `mysql_*` functions
- Database name: `ohmj2`
- Tables: `repertoire` (for scores)

## Error Handling

- PHP: Uses `@` error suppression operator in some places
- Vue: Uses try/catch with console.log for errors
- Return HTTP 200 on success in API responses

## Security Notes

- API uses `Access-Control-Allow-Origin: *` (CORS enabled for all)
- SQL queries use string concatenation (vulnerable to SQL injection)
- Database credentials stored in plain text in `api/config/database.php`
- Sanitize user inputs before database queries

## Git

- No CI/CD configured
- Commit to main branch
- Standard `.gitignore` for Node.js projects

## Dependencies

### Frontend
- Vue 2.6.11
- Bootstrap Vue 2.17.3
- Axios 0.21.0
- Vue CLI 4.5.0

### PHP
- FPDF library for PDF generation
- MySQL extension (legacy)

## Important Notes

- **No external CDN dependencies allowed** - All assets must be local (fonts, JS libraries, etc.)
- Use local copies in `static/` folder instead of CDN

## Notes

- This is a legacy codebase with mixed coding styles
- Prefer consistency with existing code over strict style enforcement
- Site targets French-speaking users
- Production URL: `ohmj2.free.fr`

## Design Guidelines

- **Style**: Clean, sober, and modern
- **Icons**: Use SVG icons instead of emojis for better consistency
- **Buttons**: Integrate related actions (view + download) in a single row with consistent styling
- **Hide unnecessary labels**: Don't show "Piece 1" or "Version 1" when there's only one
- **Visual hierarchy**: Use spacing, subtle borders, and hover effects for interactivity

## Temporary Work Files

- Use `_builds/` directory for temporary scripts and working files
- Only `scripts/convert_final_v2.js` should be kept in the scripts folder (committed to git)
- CSV output files belong in `_builds/`

## Authentication

- **Login**: Use `apiService.login('admin', 'password')` from frontend
- **API calls**: Include token in Authorization header:
  ```
  Authorization: Bearer <token>
  ```
- **Token format**: JWT (HS256) - see `api/lib/Auth.php`
- **Frontend**: Token stored in localStorage, auto-attached to API requests via axios interceptor
- **Test**: http://localhost:5173 - login with admin/password
- **API base URL**: http://localhost:8000/api/

### Starting the PHP Server

For file uploads to work, start the server with the custom upload config:
```bash
cd api
php -c php-upload.ini -S localhost:8000 router.php
```

## Current Tech Stack (2024)

- **Frontend**: SvelteKit (NOT Vue.js 2) in `/partitions/`
- **Backend**: PHP API in `/api/`
- **Scores storage**: `/legacy/Scores/` (directory-based, not MySQL)

## Security Audit Commands

When modifying backend or frontend code, run these security audits:

### Backend Security Audit

```bash
# 1. Start the PHP server
cd api
php -S localhost:8000 router.php &

# 2. Clear rate limiting files (important!)
rm -f /tmp/rate_* 2>/dev/null

# 3. Run all security tests
php tests.php

# Expected: 50/50 tests passed (100%)
```

### Frontend Security Check

```bash
cd partitions

# 1. Check for security issues in dependencies
npm audit

# 2. Build and check for CSP violations
npm run build

# 3. Check that environment variables are configured
cp .env.example .env
# Edit .env and set VITE_API_URL to your backend URL
```

### Manual Security Verification

```bash
# Test JWT authentication
curl -s http://localhost:8000/login \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"password"}'

# Test CORS headers
curl -s -I http://localhost:8000/scores \
  -H "Origin: https://evil.com"

# Test directory traversal protection
curl -s http://localhost:8000/download/../../../etc/passwd \
  -H "Authorization: Bearer <token>"
# Expected: 403 or 404 (not 200)

# Test security headers
curl -s -I http://localhost:8000/login \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"password"}'
# Check for: X-Content-Type-Options, X-Frame-Options, X-XSS-Protection, HSTS
```

### Environment Setup for Security

**Backend (api/.env):**
```bash
JWT_SECRET=your_very_long_random_secret_key_here
```

**Frontend (partitions/.env):**
```bash
# Development
VITE_API_URL=http://localhost:8000

# Production (use HTTPS!)
VITE_API_URL=https://api.yourdomain.com
```

### Security Checklist Before Deployment

- [ ] JWT_SECRET is set and strong (use: `openssl rand -base64 32`)
- [ ] CORS origins are restricted to your domain only
- [ ] HTTPS is enforced in production
- [ ] Rate limiting is active
- [ ] All 50 tests pass
- [ ] npm audit shows no critical vulnerabilities
- [ ] CSP headers are configured
- [ ] No secrets in code or git history
