# Frontend-Backend Integration Verification Guide

## Status: PARTIALLY INTEGRATED ⚠️

The frontend and backend are structurally connected but need verification and fixes.

---

## ✅ WHAT'S WORKING

### 1. API Connection Setup
- **Frontend Config**: [frontend/src/app/config/api.js](frontend/src/app/config/api.js)
  - Base URL: `http://localhost:8000/public/index.php`
  - Uses query params: `?route=<endpoint>`
  - Includes JWT Bearer token in headers

- **Backend Router**: [backend - Copy/public/index.php](backend - Copy/public/index.php)
  - CORS: ✅ Enabled for all origins
  - Methods: ✅ GET, POST, PUT, DELETE supported
  - Route dispatcher: ✅ Maps to controllers

### 2. Authentication Flow
- **Step 1**: Login → POST `/login` with `login_id` + `password`
- **Step 2**: Backend returns OTP + user info
- **Step 3**: Verify OTP → POST `/verify-otp` with `login_id` + `otp`
- **Step 4**: Backend returns JWT token
- **Storage**: ✅ Token saved in localStorage as `authToken`
- **Usage**: ✅ Token sent as `Authorization: Bearer {token}` header

### 3. Route Definitions
All routes defined in [backend - Copy/app/routes/api.php](backend - Copy/app/routes/api.php):
- ✅ Auth routes: login, verify-otp, change-password
- ✅ Student routes: students, create-student, update-student, etc.
- ✅ Faculty routes: faculty, create-faculty, etc.
- ✅ Department routes: departments, create-department, etc.
- ✅ More: examination, attendance, fees, users, roles, etc.

### 4. Frontend API Service
[frontend/src/app/services/apiService.js](frontend/src/app/services/apiService.js) defines:
- ✅ authAPI (login, verifyOtp, changePassword, profile)
- ✅ studentsAPI (getAll, create, update, delete, stats)
- ✅ facultyAPI
- ✅ departmentsAPI
- ✅ examinationsAPI
- ✅ attendanceAPI
- ✅ feesAPI
- ✅ usersAPI
- ✅ rolesAPI

---

## ⚠️ ISSUES FOUND

### Issue 1: Database Not Configured
**File**: [backend - Copy/.env](backend - Copy/.env)
```
DB_HOST=localhost
DB_PORT=3307
DB_NAME=erp_system
DB_USER=root
DB_PASS=
JWT_SECRET=erp_secret_key
```
**Problem**: Port 3307 is unusual (default is 3306). MySQL must be running and accessible.
**Fix**: 
```bash
# Check MySQL status
mysql -h localhost -P 3307 -u root

# Or use default port - update .env:
# DB_PORT=3306
```

### Issue 2: Database Schema Not Initialized
**File**: [backend - Copy/database/schema.sql](backend - Copy/database/schema.sql)
**Problem**: Tables might not exist in database
**Fix**:
```bash
# Initialize database
cd backend\ -\ Copy
php database/initialize_db.php
```

### Issue 3: API Responses May Not Match Frontend Expectations
**Frontend expects**: `{ data: {...}, message: "..." }`
**Backend returns**: Uses Controller success/error methods
**Verification needed**: Test each endpoint to confirm response format

### Issue 4: Authentication Middleware Might Be Too Strict
**File**: [backend - Copy/app/middleware/AuthMiddleware.php](backend - Copy/app/middleware/AuthMiddleware.php)
- All routes (except login/verify-otp) require valid JWT token
- Frontend must send token for all protected calls
- ✅ Properly implemented

---

## 🔧 REQUIRED FIXES

### Fix 1: Update Backend Database Connection (CRITICAL)
Edit [backend - Copy/app/config/database.php](backend - Copy/app/config/database.php) to handle connection errors gracefully.

### Fix 2: Add Environment Validation
Add startup checks in [backend - Copy/public/index.php](backend - Copy/public/index.php):
```php
// Check database connection on startup
// Check required environment variables
// Log errors for debugging
```

### Fix 3: Improve Frontend Error Handling
Current: Generic error messages
Needed: Specific error handling for different HTTP status codes

### Fix 4: Verify All Backend Services Are Implemented
Check that all services have required methods:
- StudentService.php ✓ (found)
- FacultyService.php ✓ (found)
- DepartmentService.php ✓ (found)
- Etc.

### Fix 5: Test Token Expiration Handling
Frontend needs to handle expired tokens and redirect to login.

---

## 🚀 VERIFICATION STEPS

### Step 1: Check Backend Connectivity
```bash
# Test backend is running
curl http://localhost:8000/public/index.php?route=test
# Should return something (success or error, not connection refused)
```

### Step 2: Test Database Connection
```bash
# Via PHP
php -r "require 'backend - Copy/app/config/Database.php'; $db = new Database(); $db->connect();"
# Should connect without error
```

### Step 3: Test Authentication Flow
```bash
# 1. Login (get OTP)
curl -X POST http://localhost:8000/public/index.php?route=login \
  -H "Content-Type: application/json" \
  -d '{"login_id":"admin","password":"password"}'

# Expected: { "success": true, "data": { "otp": "...", "user": {...} } }

# 2. Verify OTP
curl -X POST http://localhost:8000/public/index.php?route=verify-otp \
  -H "Content-Type: application/json" \
  -d '{"login_id":"admin","otp":"123456"}'

# Expected: { "success": true, "data": { "token": "...", "user": {...} } }
```

### Step 4: Test Protected Routes
```bash
# Using token from Step 3
curl http://localhost:8000/public/index.php?route=students \
  -H "Authorization: Bearer TOKEN_HERE"

# Should return student list or error if unauthorized
```

### Step 5: Test Frontend API Service
Open browser console and run:
```javascript
// Test login
import { authAPI } from '@/app/services/apiService'
authAPI.login({ login_id: 'admin', password: 'password' })

// Should return promise with response
```

---

## 📊 INTEGRATION READINESS

| Component | Status | Notes |
|-----------|--------|-------|
| API Base URL | ✅ | Configured in frontend/.env |
| CORS | ✅ | Enabled in backend |
| Routes | ✅ | All routes defined |
| Authentication | ⚠️ | Working but needs token expiry handling |
| Database | ⚠️ | Connection needs verification |
| Services | ⚠️ | Need individual endpoint testing |
| Error Handling | ⚠️ | Generic errors, needs improvement |
| Frontend State | ⚠️ | Using localStorage, could use Context API |

---

## 📝 NEXT ACTIONS

1. **Immediate**: Start MySQL, verify database connection
2. **Critical**: Test backend connectivity with curl commands above
3. **Important**: Test authentication flow end-to-end
4. **High**: Fix any broken endpoints
5. **Medium**: Improve error handling and validation
6. **Nice to Have**: Add API response logging, better state management

---

## 📞 DEBUGGING TIPS

- **Frontend**: Check browser Network tab for requests/responses
- **Backend**: Check error logs in database/initialize_db.php output
- **Database**: Use MySQL client to verify tables and data
- **Authorization**: Verify Bearer token is being sent in headers
