# CBT School Management System - Installation Guide

## Requirements

- **PHP** >= 8.0 (with extensions: BCMath, Ctype, Fileinfo, JSON, Mbstring, OpenSSL, PDO, Tokenizer, XML, GD, MySQLi)
- **Composer** (Dependency Manager for PHP)
- **MySQL** >= 5.7 or MariaDB >= 10.3
- **Web Server**: Apache (with mod_rewrite) or Nginx
- **Node.js** >= 16 (for frontend asset compilation)
- **Redis** (optional, for caching/queues)

## Quick Installation

### 1. Clone/Extract Project

```bash
cd /var/www/html/
# Extract the project or clone from repository
```

### 2. Install PHP Dependencies

```bash
composer install --no-dev --optimize-autoloader
```

### 3. Configure Environment

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

Edit `.env` file:

```env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cbt_school
DB_USERNAME=root
DB_PASSWORD=your_password

APP_URL=http://localhost/CBT/public
```

### 4. Create Database

```sql
CREATE DATABASE cbt_school CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
```

Or run the full schema:

```bash
mysql -u root -p cbt_school < database/schema.sql
```

### 5. Run Migrations & Seeders

```bash
php artisan migrate --seed
```

### 6. Create Storage Link

```bash
php artisan storage:link
```

### 7. Install & Build Frontend Assets

```bash
npm install
npm run production
```

### 8. Set Permissions

```bash
chmod -R 775 storage bootstrap/cache
chmod -R 775 public/assets
```

### 9. Configure Queue Worker

```bash
php artisan queue:table
php artisan migrate
php artisan horizon:install
```

Start queue worker:

```bash
php artisan horizon
```

### 10. Configure Cron Jobs

Add to crontab (`crontab -e`):

```cron
* * * * * cd /path-to-project && php artisan schedule:run >> /dev/null 2>&1
```

## Web Server Configuration

### Apache (XAMPP)
The `.htaccess` file is already included. Make sure `mod_rewrite` is enabled.

Place the project in `C:\xampp\htdocs\CBT\` and access via:
```
http://localhost/CBT/public
```

### Nginx
```nginx
server {
    listen 80;
    server_name cbt-school.com;
    root /var/www/html/CBT/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

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

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}
```

## Default Login Credentials

| Role | Email | Password |
|------|-------|----------|
| Super Admin | admin@cbtschool.com | password |
| Teacher | teacher@cbtschool.com | password |
| Student | student@cbtschool.com | password |

## Environment Variables Reference

### Payment Gateways
```env
PAYSTACK_PUBLIC_KEY=your_paystack_public_key
PAYSTACK_SECRET_KEY=your_paystack_secret_key
FLUTTERWAVE_PUBLIC_KEY=your_flutterwave_public_key
FLUTTERWAVE_SECRET_KEY=your_flutterwave_secret_key
MONNIFY_API_KEY=your_monnify_api_key
MONNIFY_SECRET_KEY=your_monnify_secret_key
```

### SMS Gateway (Twilio)
```env
TWILIO_SID=your_twilio_sid
TWILIO_AUTH_TOKEN=your_twilio_token
TWILIO_FROM=+1234567890
```

### AI Integration (OpenAI)
```env
OPENAI_API_KEY=your_openai_api_key
```

### Social Login
```env
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_secret
```

## Features Overview

### Authentication & Security
- Multi-role authentication (Admin, Teacher, Student, Parent)
- Email verification
- Password reset
- Two-factor authentication (2FA)
- Google/Facebook social login
- Laravel Sanctum API tokens
- CSRF, XSS, SQL injection protection
- Rate limiting
- Activity logging

### Student Management
- Registration with admission number generation
- Student profiles with passport photo
- Guardian/parent information
- Student promotion and transfer
- Attendance tracking
- ID card generation
- Bulk import/export (CSV/Excel)

### Teacher Management
- Registration with staff ID
- Subject and class assignment
- Salary management
- Attendance tracking
- Performance metrics

### Question Bank
- Multiple question types (MCQ, Multiple Response, True/False, Fill-in-Blank, Essay, Theory)
- Rich text editor support
- Image, audio, video questions
- Mathematical equations support
- Difficulty levels (Easy, Medium, Hard)
- Categories and tags
- Bulk import (CSV/Excel)
- Export (CSV)

### CBT Examination Engine
- Configurable exam setup (duration, pass mark, etc.)
- Fullscreen mode enforcement
- Countdown timer with auto-submit
- Question shuffle and random options
- Question navigation with flagging
- Auto-save progress
- Anti-cheating (tab detection, copy prevention, fullscreen enforcement)
- Negative marking support
- Instant results and grading
- AI proctoring support (webcam, face recognition)

### Results & Analytics
- Automatic objective marking
- Manual grading for essay/theory
- Grade computation and GPA calculation
- Position ranking
- Performance analytics with charts
- Export to PDF, CSV
- Interactive dashboards (Chart.js, ApexCharts)

### Payment System
- Paystack, Flutterwave, Monnify integration
- Fee categories and installments
- Payment receipts and history
- Subscription management (SaaS)
- Financial reports

### Additional Modules
- Library management (books, issues, fines)
- Certificate generation with QR codes
- Exam timetables and scheduling
- Practice test portal
- Parent portal for monitoring
- Multi-school SaaS architecture
- Dark mode support
- Notification system (Email, SMS, Push)
- Support ticket system

## API Documentation

The REST API is available at `/api/` endpoint.

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

{
    "email": "student@cbtschool.com",
    "password": "password"
}
```

Response:
```json
{
    "success": true,
    "data": {
        "user": {...},
        "token": "1|abc123..."
    }
}
```

### API Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| POST | /api/auth/login | User login |
| POST | /api/auth/register | User registration |
| POST | /api/auth/logout | User logout |
| GET | /api/user | Get authenticated user |
| GET | /api/students | List students |
| POST | /api/students | Create student |
| GET | /api/exams | List exams |
| GET | /api/exams/{id}/start | Start exam |
| POST | /api/exams/{id}/submit | Submit exam |
| GET | /api/results | List results |
| POST | /api/payments/initialize | Initialize payment |

## Directory Structure

```
CBT/
├── app/
│   ├── Console/Commands/     # Artisan commands (Cron jobs)
│   ├── Exceptions/           # Exception handler
│   ├── Http/
│   │   ├── Controllers/      # Application controllers
│   │   │   ├── Admin/        # Admin controllers
│   │   │   ├── Api/          # API controllers
│   │   │   ├── Student/      # Student controllers
│   │   │   ├── Teacher/      # Teacher controllers
│   │   │   └── Parent/       # Parent controllers
│   │   ├── Middleware/        # HTTP middleware
│   │   └── Requests/         # Form requests
│   ├── Models/                # Eloquent models
│   ├── Notifications/         # Notification classes
│   ├── Providers/             # Service providers
│   └── Services/              # Business logic services
├── bootstrap/                 # Framework bootstrap
├── config/                    # Configuration files
├── database/
│   ├── migrations/            # Database migrations
│   ├── seeders/               # Database seeders
│   └── schema.sql             # Full SQL schema
├── public/                    # Web root
│   ├── assets/
│   │   ├── css/cbt.css        # Main stylesheet
│   │   └── js/cbt.js          # Main JavaScript
│   └── index.php              # Application entry point
├── resources/
│   ├── views/                 # Blade templates
│   │   ├── layouts/           # Layout templates
│   │   ├── auth/              # Authentication views
│   │   ├── admin/             # Admin dashboard views
│   │   ├── student/           # Student views
│   │   ├── teacher/           # Teacher views
│   │   └── parent/            # Parent views
│   ├── css/                   # Uncompiled CSS
│   └── js/                    # Uncompiled JS
├── routes/
│   ├── web.php                # Web routes
│   ├── api.php                # API routes
│   └── console.php            # Console routes
└── storage/                   # Application storage
```

## Security Best Practices

1. **Always use HTTPS** in production
2. **Keep `.env` file secure** - never commit to version control
3. **Use strong passwords** for all accounts
4. **Regular backups** via `php artisan cbt:backup`
5. **Monitor logs** in `storage/logs/`
6. **Keep dependencies updated** via `composer update`
7. **Enable 2FA** for admin accounts
8. **Use rate limiting** on API routes
9. **Validate all inputs** (handled by Laravel)
10. **Use prepared statements** (handled by Eloquent)

## Maintenance

### Backup Database
```bash
php artisan cbt:backup
```

### Clear Cache
```bash
php artisan cache:clear
php artisan config:clear
php artisan view:clear
```

### Check System Health
```bash
php artisan health:check
```

## Support

For issues and feature requests, please use the built-in support ticket system or contact the system administrator.

---

**Version**: 1.0.0
**License**: MIT
