# Development Guide - TinyQC

## Prerequisites

| Requirement | Version | Description |
|-------------|---------|-------------|
| PHP | 8.1+ | Server-side scripting |
| SQL Server | 2016+ | Database server |
| Composer | Latest | PHP dependency manager |
| Web Server | Any | Apache/Nginx/IIS |

---

## Installation

### 1. Clone the Repository

```bash
git clone <repository-url> tinyqc
cd tinyqc
```

### 2. Install Dependencies

```bash
composer install
```

### 3. Configure Environment

```bash
copy env .env
```

Edit `.env` with your database settings:

```env
database.default.hostname = localhost
database.default.port = 1433
database.default.database = tinyqc
database.default.username = sa
database.default.password = your_password
database.default.DBDriver = SQLSRV
```

### 4. Set Up Database

1. Create a new SQL Server database
2. Run migrations if applicable
3. Seed initial data if needed

### 5. Configure Web Server

Point your web server to the `public` directory:

**Apache (httpd.conf or virtual host):**
```apache
<VirtualHost *:80>
    ServerName tinyqc.local
    DocumentRoot "D:/data/www/tinyqc/public"
    <Directory "D:/data/www/tinyqc">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
```

**Nginx:**
```nginx
server {
    listen 80;
    server_name tinyqc.local;
    root D:/data/www/tinyqc/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
```

### 6. Access the Application

Open http://localhost in your browser (or your configured domain).

---

## Project Structure

```
tinyqc/
├── app/
│   ├── Config/          # Configuration files
│   │   ├── Database.php # Database settings
│   │   └── Routes.php   # Route definitions
│   ├── Controllers/     # Application controllers
│   │   ├── Api/         # API controllers
│   │   ├── Dashboard.php
│   │   ├── Dept.php
│   │   ├── Test.php
│   │   ├── Control.php
│   │   ├── Entry.php
│   │   ├── PageController.php
│   │   └── Report.php
│   ├── Models/          # Database models
│   │   ├── BaseModel.php
│   │   ├── DeptModel.php
│   │   ├── TestModel.php
│   │   ├── ControlModel.php
│   │   ├── DictDeptModel.php
│   │   ├── DictTestModel.php
│   │   ├── DictControlModel.php
│   │   ├── ControlTestModel.php
│   │   ├── ResultModel.php
│   │   ├── DailyResultModel.php
│   │   ├── MonthlyCommentModel.php
│   │   └── ResultCommentModel.php
│   └── Views/           # View templates
│       ├── layout/      # Layout templates
│       ├── dashboard.php
│       ├── dept/        # Department views
│       ├── test/        # Test views
│       ├── control/     # Control views
│       ├── entry/       # Entry views
│       └── report/      # Report views
├── public/              # Web root
│   ├── index.php        # Entry point
│   ├── js/
│   │   ├── app.js
│   │   ├── tables.js
│   │   └── charts.js
│   └── .htaccess
├── tests/               # Unit tests
├── writable/            # Writable directory
├── env                  # Environment template
├── composer.json
└── phpunit.xml.dist
```

---

## Development Commands

### Running the Application

**Using PHP built-in server (development):**
```bash
php spark serve
```

**Or using built-in server:**
```bash
php -S localhost:8080 -t public
```

### Running Tests

```bash
# Run all tests
./vendor/bin/phpunit

# Run with coverage report
./vendor/bin/phpunit --coverage-html coverage/
```

### Code Style

Follow these coding standards:
- **PSR-12:** PHP coding standard
- **CamelCase:** For variables and functions
- **PascalCase:** For classes
- **snake_case:** For database tables and columns

---

## Adding New Features

### Step 1: Create the Model

Location: `app/Models/`

```php
<?php
namespace App\Models;

use App\Models\BaseModel;

class NewFeatureModel extends BaseModel
{
    protected $table = 'new_feature';
    protected $primaryKey = 'id';
    protected $allowedFields = ['field1', 'field2', 'created_at', 'updated_at'];
}
```

### Step 2: Create the API Controller

Location: `app/Controllers/Api/`

```php
<?php
namespace App\Controllers\Api;

use App\Controllers\BaseController;
use App\Models\NewFeatureModel;

class NewFeatureApiController extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new NewFeatureModel();
    }

    public function index()
    {
        $data = $this->model->findAll();
        return $this->response->setJSON($data);
    }

    // Add CRUD methods...
}
```

### Step 3: Add Routes

Location: `app/Config/Routes.php`

```php
$routes->group('api', ['filter' => 'cors'], function ($routes) {
    $routes->get('new-feature', 'NewFeatureApiController::index');
    $routes->post('new-feature', 'NewFeatureApiController::create');
    // Add more routes...
});
```

### Step 4: Create Views

Location: `app/Views/newfeature/`

```php
<?= $this->extend('layout/form_layout') ?>
<?= $this->section('content') ?>
<!-- View content -->
<?= $this->endSection() ?>
```

### Step 5: Add Menu Item

Update the layout file to include the new feature in navigation.

---

## Frontend Development

### JavaScript Files

| File | Purpose |
|------|---------|
| `public/js/app.js` | Main application JavaScript |
| `public/js/tables.js` | Table functionality |
| `public/js/charts.js` | Chart functionality |

### UI Components

The application uses:
- **TailwindCSS:** Utility-first CSS
- **Alpine.js:** Reactive JavaScript
- **DaisyUI:** Component library
- **FontAwesome:** Icons

### Modal Dialogs

Views use modal-based dialogs for form interactions:
- `dialog_form.php` pattern for create/edit forms
- AJAX submission via API controllers

---

## Database Operations

### Using the Model

```php
// Get all records
$model = new DeptModel();
$depts = $model->findAll();

// Find by ID
$dept = $model->find($id);

// Create
$model->insert(['name' => 'New Dept']);

// Update
$model->update($id, ['name' => 'Updated Name']);

// Delete
$model->delete($id);
```

### BaseModel Features

The `BaseModel` provides:
- Automatic camelCase/snake_case conversion
- Standardized CRUD operations
- Soft delete support (if enabled)

---

## Debugging

### Debug Bar

The application includes a debug toolbar for development:
- Access via `writable/debugbar/` directory
- Review queries, logs, and timing

### Logging

```php
log_message('error', 'Something went wrong');
log_message('debug', 'Debug information');
```

Logs are stored in `writable/logs/`.

---

## Common Tasks

### Database Migrations

```bash
# Create migration
php spark make:migration create_users_table

# Run migrations
php spark migrate

# Rollback migrations
php spark migrate:rollback
```

### Database Seeding

```bash
# Create seeder
php spark make:seeder UserSeeder

# Run seeder
php spark db:seed UserSeeder
```

### Clear Cache

```bash
php spark cache:clear
```

---

## Testing

### Writing Tests

Location: `tests/`

```php
<?php
use Tests\Support\TestCase;

class DeptModelTest extends TestCase
{
    public function testCanCreateDept()
    {
        $model = new \App\Models\DeptModel();
        $result = $model->insert(['name' => 'Test Dept']);
        $this->assertTrue($result > 0);
    }
}
```

### Running Tests

```bash
# Run all tests
./vendor/bin/phpunit

# Run specific test file
./vendor/bin/phpunit tests/Models/DeptModelTest.php

# Run with coverage
./vendor/bin/phpunit --coverage-html coverage/
```

---

## Deployment

### Production Checklist

1. Set `CI_ENVIRONMENT` to `production` in `.env`
2. Disable debugging in `app/Config/Boot/production.php`
3. Set proper file permissions on `writable/` directory
4. Configure web server for production
5. Set up HTTPS/SSL
6. Configure error logging
7. Test backup and restore procedures

### Directory Permissions

```bash
# writable directory must be writable
chmod 755 writable/
chmod 644 app/Config/*.php
```

---

## Additional Resources

- [CodeIgniter 4 Documentation](https://codeigniter.com/docs)
- [TailwindCSS Documentation](https://tailwindcss.com/docs)
- [Alpine.js Documentation](https://alpinejs.dev/start)
- [DaisyUI Documentation](https://daisyui.com/docs/)
- [PHPUnit Documentation](https://phpunit.de/documentation.html)
