# Coding Conventions & Standards

## PHP Standards
- PHP 8.1+ features (typed properties, match expressions)
- Always declare return types for public methods
- No comments unless explaining complex logic
- Use `esc()` when outputting user data in views

## Naming Conventions

| Type | Convention | Example |
|------|------------|---------|
| Classes | PascalCase | `Admin`, `UserController` |
| Methods/Variables | camelCase | `getUsers()`, `$userId` |
| Constants | UPPER_SNAKE_CASE | `DB_HOST` |
| Database tables | UPPER_SNAKE_CASE | `GDC_CMOD.dbo.USERS` |
| Views | lowercase_underscores | `admin/index.php` |
| Routes | lowercase | `/admin/users` |

## Controller Patterns

```php
namespace App\Controllers;

class Admin extends BaseController {
    public function index() { }
}

// API Controllers use ResponseTrait
use App\Controllers\BaseController;
use CodeIgniter\API\ResponseTrait;

class Users extends BaseController {
    use ResponseTrait;
    protected $db;

    public function __construct() {
        $this->db = \Config\Database::connect();
        helper(['url', 'form', 'text']);
    }
}
```

## Database Operations

```php
$this->db = \Config\Database::connect();

// Parameterized queries only
$query = $this->db->query("SELECT * FROM table WHERE id = ?", [$id]);
$row = $query->getRowArray();
$results = $query->getResultArray();

// Transactions
$this->db->transBegin();
try {
    $this->db->query("INSERT INTO ...", [$data]);
    $this->db->transCommit();
} catch (\Throwable $e) {
    $this->db->transRollback();
}
```

## Request/Response Patterns

```php
// GET input
$date1 = $this->request->getVar('date1') ?? date('Y-m-d');

// POST JSON
$input = $this->request->getJSON(true);

// JSON response
return $this->respond(['data' => $results]);
return $this->response->setJSON(['message' => 'Success']);

// View response
return view('admin/index', $data);

// Redirect with errors
return redirect()->back()->with('errors', ['key' => 'message']);
```

## Session Structure

```php
session()->set([
    'isLoggedIn' => true,
    'userid' => (string) $user['USERID'],
    'userroleid' => (int) $user['USERROLEID'],
    'userrole' => (string) $role,
]);
```

## Security Guidelines
- Use parameterized queries (never interpolate directly)
- Hash passwords with `password_hash()` / `password_verify()`
- Validate and sanitize all input before use
- Use `esc()` when outputting user data in views

## Validation Endpoints
- `POST /api/{resource}/validate/{id}` - validate a record
- `DELETE /api/{resource}/validate/{id}` - unvalidate a record
