# Physiotherapy Clinic Management System

A complete API-first physiotherapy clinic management system built with Laravel 10, SQLite, AdminLTE (Bootstrap 5), and Sanctum authentication.

## Features

- **API-First Architecture**: All business logic exposed via RESTful JSON APIs
- **Multi-language Support**: Arabic and English with RTL support
- **Role-based Access Control**: Admin, Manager, Therapist, Receptionist
- **Two-Factor Authentication**: Optional TOTP-based 2FA with recovery codes
- **Patient Management**: Full CRUD with demographics, medical history, referral tracking
- **Appointment System**: Conflict checking, calendar view, reminders
- **Multi-currency**: BHD, SAR, AED, QAR, KWD, OMR (Gulf currencies)
- **Invoicing & Payments**: Partial payments, outstanding balances
- **Packages**: Session packages with validity periods
- **Ledger**: Income/expense tracking with automatic entries
- **Wage Management**: Therapist productivity tracking and wage calculation
- **Dashboards**: Role-specific dashboards with key metrics

## Tech Stack

- **Backend**: Laravel 10, PHP 8.1+
- **Database**: SQLite (auto-creates database file)
- **Authentication**: Laravel Sanctum (API tokens)
- **2FA**: pragmarx/google2fa-laravel with Bacon QR Code
- **Admin Panel**: AdminLTE 3 (Bootstrap 4/5)
- **Frontend**: Blade views with JavaScript API consumption via Axios/Fetch

## Installation

### 1. Clone and Install Dependencies

```bash
cd physiotherapy-clinic
composer install
npm install && npm run build
```

### 2. Environment Setup

```bash
cp .env.example .env
php artisan key:generate
```

The `.env` file is pre-configured for SQLite:
```
DB_CONNECTION=sqlite
DB_DATABASE=/full/path/to/physiotherapy-clinic/database/database.sqlite
```

### 3. Create SQLite Database

```bash
mkdir -p database
touch database/database.sqlite
```

### 4. Run Migrations and Seeders

```bash
php artisan migrate --force
php artisan db:seed --force
```

This creates:
- Default admin user (admin@clinic.com / password)
- Default therapist user (therapist@clinic.com / password)
- Gulf currencies (BHD base currency)
- Chart of accounts (income/expense)

### 5. Serve the Application

```bash
php artisan serve
```

Access at: http://localhost:8000

## Default Login Credentials

| Role | Email | Password |
|------|-------|----------|
| Admin | admin@clinic.com | password |
| Therapist | therapist@clinic.com | password |

## API Documentation

### Authentication

#### Login
```http
POST /api/login
Content-Type: application/json

{
  "email": "admin@clinic.com",
  "password": "password"
}
```

Response:
```json
{
  "message": "Logged in successfully",
  "user": { ... },
  "token": "1|xxxxxxxxxxxxxxxx"
}
```

#### Register
```http
POST /api/register
Content-Type: application/json

{
  "name": "New User",
  "email": "user@clinic.com",
  "password": "password",
  "password_confirmation": "password"
}
```

#### Logout
```http
POST /api/logout
Authorization: Bearer {token}
```

### 2FA Endpoints

```http
# Get 2FA status
GET /api/2fa/status

# Enable 2FA (returns QR code)
GET /api/2fa/enable

# Confirm 2FA with TOTP code
POST /api/2fa/confirm
{ "code": "123456" }

# Disable 2FA
POST /api/2fa/disable
{ "password": "password", "code": "123456" }

# Regenerate recovery codes
GET /api/2fa/recovery-codes
```

### Patients

```http
GET    /api/patients              # List (paginated)
POST   /api/patients              # Create
GET    /api/patients/{id}         # Show
PUT    /api/patients/{id}         # Update
DELETE /api/patients/{id}         # Delete
GET    /api/patients/{id}/profile # Full profile
```

Query parameters for list:
- `search` - Search by name, email, phone, code
- `status` - Filter by active/inactive
- `page`, `per_page` - Pagination

### Appointments

```http
GET    /api/appointments
POST   /api/appointments
GET    /api/appointments/{id}
PUT    /api/appointments/{id}
DELETE /api/appointments/{id}

# Calendar feed
GET /api/appointments/calendar/feed?start=2024-01-01&end=2024-01-31

# Available time slots
GET /api/appointments/available-slots?therapist_id=1&date=2024-01-15&duration=60
```

### Invoices & Payments

```http
# Invoices
GET    /api/invoices
POST   /api/invoices
GET    /api/invoices/{id}
PUT    /api/invoices/{id}
DELETE /api/invoices/{id}
GET    /api/invoices/summary/report

# Payments
GET    /api/payments
POST   /api/payments
GET    /api/payments/{id}
DELETE /api/payments/{id}
GET    /api/payments/summary/report
```

### Ledger

```http
GET /api/ledger
POST /api/ledger

# Reports
GET /api/ledger/summary/pl?date_from=2024-01-01&date_to=2024-01-31
GET /api/ledger/summary/income?date_from=2024-01-01&date_to=2024-01-31
GET /api/ledger/summary/expenses?date_from=2024-01-01&date_to=2024-01-31
```

### Therapists & Wages

```http
GET /api/therapists
GET /api/therapists/{id}
PUT /api/therapists/{id}

# Performance
GET /api/therapists/{id}/performance?period_start=2024-01-01&period_end=2024-01-31

# Wages
GET /api/therapists/{id}/wage-calculate?period_start=2024-01-01&period_end=2024-01-31
POST /api/therapists/{id}/wage
```

### Dashboard

```http
GET /api/dashboard
```

Response includes stats, recent appointments, charts data.

## Role-Based Access

| Feature | Admin | Manager | Therapist | Receptionist |
|---------|-------|---------|-----------|--------------|
| Patients | All | All | Own only | All |
| Appointments | All | All | Own only | All |
| Invoices | All | All | View | All |
| Payments | All | All | - | Create |
| Ledger | All | View | - | - |
| Wages | All | Manage | View own | - |
| Settings | All | Limited | - | - |

## Two-Factor Authentication

1. After first login, go to Security settings
2. Click "Enable 2FA"
3. Scan QR code with Google Authenticator or similar app
4. Enter the 6-digit code to confirm
5. Save recovery codes in a secure location

To login with 2FA:
1. Enter email and password
2. When prompted, enter TOTP code from authenticator app
3. Or use a recovery code if you lost access to your device

## Web UI (AdminLTE)

The web interface consumes the same API endpoints via JavaScript:

- **Dashboard**: `/dashboard` - Overview stats and recent appointments
- **Patients**: `/patients` - Patient list with search and filters
- **Appointments**: `/appointments` - Calendar and list views
- **Security**: `/2fa` - 2FA management

### JavaScript API Helper

The included `public/js/api.js` provides a centralized API client:

```javascript
// Get patients with search
const patients = await api.getPatients({ search: 'John', page: 1 });

// Create patient
const newPatient = await api.createPatient({
  first_name: 'John',
  last_name: 'Doe',
  phone: '12345678'
});

// Get dashboard data
const dashboard = await api.getDashboard();
```

## Localization

The system supports English and Arabic:

- Translation files: `resources/lang/en/`, `resources/lang/ar/`
- Switch language: Click globe icon in navbar
- RTL support: Automatic for Arabic locale

## Folder Structure

```
app/
  Http/
    Controllers/
      Api/           # API controllers (business logic)
      Auth/          # Web auth controllers
    Requests/        # Form validation classes
    Resources/       # API Resources (JSON formatting)
  Models/            # Eloquent models
  Policies/          # Authorization policies
  Services/          # Business logic services
      AppointmentService.php
      LedgerService.php
      WageService.php
      ReminderService.php

resources/
  views/
    layouts/         # AdminLTE layout
    auth/            # Login, register, 2FA pages
    patients/        # Patient list page
  lang/              # Translations (en, ar)

routes/
  api.php            # API routes
  web.php            # Web routes (views only)
```

## Console Commands

```bash
# Send due reminders
php artisan reminders:send

# Calculate wages for period
php artisan wages:calculate --period-start=2024-01-01 --period-end=2024-01-31
```

## Testing

Run PHPUnit tests:
```bash
php artisan test
```

## License

MIT License
