# RevLinks Training Portal - API Backend

## Overview
This is the PHP REST API backend for the RevLinks Training Portal. It provides endpoints for application management, authentication, payment processing, and email services.

## Architecture
- **PHP 8+** with PDO for database operations
- **MySQL** database (energies_school)
- **JSON REST API** responses
- **PHPMailer** for email services
- **Paystack** for payment processing
- **JWT** for authentication

## Directory Structure

```
api/
├── config/              # Configuration files
│   ├── Database.php     # Database connection class
│   ├── app.php          # Application configuration
│   ├── database.php     # Database settings
│   ├── email.php        # Email configuration
│   ├── env.php          # Environment loader
│   ├── error.php        # Error handler
│   ├── cors.php         # CORS configuration
│   └── response.php     # JSON response helper
├── controllers/         # Business logic controllers
├── middleware/          # Request/response middleware
├── models/              # Database models
├── routes/              # API route definitions
│   ├── auth.php         # Authentication routes
│   ├── applications.php # Application routes
│   ├── registration.php # Registration routes
│   ├── payments.php     # Payment routes
│   └── dashboard.php    # Dashboard routes
├── services/            # External service integrations
├── helpers/             # Utility functions
├── uploads/             # File upload directory
├── logs/                # Application logs
├── database/            # Database schema
│   └── schema.sql       # Complete database schema
├── index.php            # API entry point
├── .htaccess            # Apache configuration
└── README.md            # This file
```

## Installation

### 1. Database Setup
1. Create a MySQL database named `energies_school`
2. Import the schema file:
   ```bash
   mysql -u your_username -p energies_school < api/database/schema.sql
   ```

### 2. Environment Configuration
1. Copy the example environment file:
   ```bash
   cp .env.example .env
   ```
2. Edit `.env` with your actual configuration values
3. Update database credentials, Paystack keys, and email settings

### 3. File Permissions
Ensure the following directories are writable:
```bash
chmod 755 api/logs
chmod 755 api/uploads
```

### 4. Web Server Configuration
The API is designed to work with standard cPanel hosting. Ensure:
- PHP 8.0 or higher is installed
- PDO MySQL extension is enabled
- PHPMailer is installed (via Composer)
- Mod_rewrite is enabled (for Apache)

## Database Schema

The database includes the following tables:
- `settings` - Application configuration
- `admins` - Admin user accounts
- `applications` - Student applications
- `registration_codes` - Registration codes for admitted students
- `payments` - Payment transactions
- `email_logs` - Email sending history
- `activity_logs` - System activity logs

See `api/database/schema.sql` for complete schema details.

## API Endpoints

### Base URL
```
/api
```

### Authentication Routes (Phase 2)
- `POST /api/auth/login` - Admin login
- `POST /api/auth/logout` - Admin logout
- `GET /api/auth/me` - Get current admin user

### Application Routes (Phase 3)
- `POST /api/applications` - Submit new application
- `GET /api/applications` - List applications (admin)
- `GET /api/applications/:id` - Get single application
- `PATCH /api/applications/:id/status` - Update application status
- `DELETE /api/applications/:id` - Delete application (soft delete)

### Registration Routes (Phase 4)
- `POST /api/registration/verify` - Verify registration code
- `POST /api/registration/send-code` - Send registration code (admin)

### Payment Routes (Phase 5)
- `POST /api/payments/initialize` - Initialize payment
- `POST /api/payments/verify` - Verify payment
- `POST /api/payments/webhook` - Paystack webhook

### Dashboard Routes (Phase 3)
- `GET /api/dashboard/stats` - Get dashboard statistics
- `GET /api/dashboard/recent` - Get recent applications
- `GET /api/dashboard/activity` - Get activity logs

## Response Format

All API responses follow this format:

### Success Response
```json
{
  "success": true,
  "message": "Success message",
  "data": {},
  "timestamp": 1234567890
}
```

### Error Response
```json
{
  "success": false,
  "message": "Error message",
  "errors": {},
  "timestamp": 1234567890
}
```

### Paginated Response
```json
{
  "success": true,
  "message": "Success message",
  "data": [],
  "pagination": {
    "current_page": 1,
    "per_page": 20,
    "total": 100,
    "last_page": 5
  },
  "timestamp": 1234567890
}
```

## Security Features

- Prepared statements for all database queries
- Input validation and sanitization
- JWT-based authentication
- CORS configuration
- CSRF protection
- Rate limiting structure
- Secure file uploads
- Error logging (no sensitive data in responses)
- httpOnly cookies for session management

## Development Phases

### Phase 1 (Current)
- ✅ Backend folder structure
- ✅ Configuration files
- ✅ Database layer
- ✅ SQL schema

### Phase 2 (Next)
- Authentication system
- JWT implementation
- Admin user management

### Phase 3
- Application CRUD operations
- Dashboard statistics
- Admin panel integration

### Phase 4
- Registration code system
- Email service integration
- Code verification

### Phase 5
- Paystack payment integration
- Payment verification
- Webhook handling

### Phase 6
- Testing and optimization
- Security hardening
- Performance tuning

### Phase 7
- Production deployment
- Monitoring setup
- Backup configuration

## Error Handling

Errors are logged to `api/logs/error_YYYY-MM-DD.log`. In development mode, detailed error messages are returned. In production, generic error messages are shown for security.

## Default Admin User

After importing the schema, a default admin user is created:
- Email: `admin@revlinks.ng`
- Password: `admin123` (bcrypt hashed)

**Important:** Change this password immediately after first login.

## Maintenance

### Database Backups
Regular backups of the `energies_school` database should be scheduled.

### Log Rotation
Log files should be rotated regularly to prevent disk space issues.

### Dependency Updates
Keep PHPMailer and other dependencies updated via Composer.

## Support

For issues or questions, contact the development team or refer to the project documentation.
