# ❓ Frequently Asked Questions (FAQ)

Comprehensive guide for common questions about the School Management System.

---

## 📋 Table of Contents

1. [Installation & Setup](#-installation--setup)
2. [Database](#-database)
3. [Users & Permissions](#-users--permissions)
4. [Students & Teachers](#-students--teachers)
5. [Grades & Exams](#-grades--exams)
6. [Fees & Payments](#-fees--payments)
7. [Troubleshooting](#-troubleshooting)
8. [Performance & Optimization](#-performance--optimization)
9. [Security](#-security)

---

## 🔧 Installation & Setup

### Q: What are the system requirements?

**A:** You need:
- PHP 8.2 or higher
- Composer 2.x
- Node.js 18.x or higher
- MySQL 5.7+ or 8.x
- Git 2.x

See [DATABASE_SETUP.md](DATABASE_SETUP.md) for details.

---

### Q: How do I install the project on my machine?

**A:** Follow these steps:

```bash
# 1. Clone the project
git clone <repository-url>
cd school_system

# 2. Install dependencies
composer install
npm install

# 3. Setup environment
cp .env.example .env
php artisan key:generate

# 4. Configure database in .env
# Then run migrations
php artisan migrate

# 5. Run the project
php artisan serve
npm run dev
```

---

### Q: `composer install` fails, what should I do?

**A:** Try these solutions:

```bash
# 1. Check PHP version
php -v  # Should be 8.2+

# 2. Remove old files
rm -rf vendor composer.lock
composer install

# 3. Use --ignore-platform-reqs if some requirements are unavailable
composer install --ignore-platform-reqs

# 4. Update Composer itself
composer self-update
```

---

## 🗄️ Database

### Q: How do I create the database?

**A:** Use MySQL Command Line or phpMyAdmin:

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

Then update `.env`:
```env
DB_DATABASE=school_db
DB_USERNAME=root
DB_PASSWORD=
```

---

### Q: How do I rebuild the database from scratch?

**A:** Use this command (⚠️ will delete all data):

```bash
php artisan migrate:fresh
```

To also add seed data:
```bash
php artisan migrate:fresh --seed
```

---

### Q: What are the main database tables?

**A:** Main tables:
- `users` - Users
- `students` - Students
- `teachers` - Teachers
- `grades` - Academic grades/classes
- `subjects` - Subject courses
- `marks` - Student grades
- `attendances` - Attendance records
- `fees` - Tuition fees
- `payments` - Payment records
- `exams` - Examinations
- `books` - Books
- `borrowings` - Borrowing records

See [DATABASE_SETUP.md](DATABASE_SETUP.md#-database-information) for details.

---

### Q: How do I backup the database?

**A:** Use mysqldump:

```bash
# Create backup
mysqldump -u root -p school_db > backup_$(date +%Y%m%d).sql

# Restore from backup
mysql -u root -p school_db < backup_20260114.sql
```

---

## 👥 Users & Permissions

### Q: How do I create an Admin user?

**A:** Use Laravel Tinker:

```bash
php artisan tinker
```

Then:
```php
$admin = \App\Models\User::create([
    'name' => 'Admin',
    'email' => 'admin@school.com',
    'password' => bcrypt('password123'),
    'email_verified_at' => now(),
]);

$admin->assignRole('admin');
```

---

### Q: What roles are available in the system?

**A:** Four default roles:
1. **Admin**: Full system access
2. **Teacher**: Manage classes and grades
3. **Student**: View personal information
4. **Parent**: Monitor their children

---

### Q: How do I assign a role to a user?

**A:** Using Tinker:

```php
$user = \App\Models\User::find(1);
$user->assignRole('teacher');

// Or remove a role
$user->removeRole('student');

// Or check role
if ($user->hasRole('admin')) {
    // ...
}
```

---

### Q: I forgot the Admin password, how do I reset it?

**A:**

```bash
php artisan tinker
```

```php
$admin = \App\Models\User::where('email', 'admin@school.com')->first();
$admin->password = bcrypt('new_password123');
$admin->save();
```

---

## 🎓 Students & Teachers

### Q: How do I add a new student?

**A:** Two methods:

**1. Through the interface:**
- Go to Students page
- Click "Add New Student"
- Fill in details and save

**2. Through Tinker:**
```php
$student = \App\Models\Student::create([
    'name' => 'John Doe',
    'grade_id' => 1,
    'date_of_birth' => '2010-05-15',
    'gender' => 'male',
    'address' => 'New York, USA',
]);
```

---

### Q: How do I link a student to a parent?

**A:**

```php
// Create parent first
$parent = \App\Models\ParentModel::create([
    'name' => 'Jane Doe',
    'phone' => '123456789',
    'email' => 'jane@example.com',
]);

// Link to student
$student = \App\Models\Student::find(1);
$student->parent_id = $parent->id;
$student->save();
```

---

### Q: How do I assign a subject to a teacher?

**A:**

```php
$subject = \App\Models\Subject::find(1);
$subject->teacher_id = 5; // Teacher ID
$subject->save();
```

---

## 📊 Grades & Exams

### Q: How do I add a grade for a student?

**A:**

```php
$mark = \App\Models\Mark::create([
    'student_id' => 1,
    'subject_id' => 3,
    'exam_id' => 2, // Optional
    'score' => 85.5,
]);
```

---

### Q: How do I calculate a student's average grade?

**A:**

```php
$student = \App\Models\Student::find(1);
$average = $student->marks()->avg('score');

echo "Average: " . round($average, 2);
```

---

### Q: How do I create a new exam?

**A:**

```php
$exam = \App\Models\Exam::create([
    'name' => 'Midterm Exam',
    'subject_id' => 1,
    'grade_id' => 2,
    'exam_date' => '2026-03-15',
    'total_marks' => 100,
]);
```

---

## 💰 Fees & Payments

### Q: How do I set fees for a grade?

**A:**

```php
$fee = \App\Models\Fee::create([
    'grade_id' => 1,
    'amount' => 500,
    'academic_year' => '2025-2026',
    'description' => 'First term fees',
]);
```

---

### Q: How do I record a payment for a student?

**A:**

```php
$payment = \App\Models\Payment::create([
    'student_id' => 1,
    'amount' => 200,
    'payment_date' => now(),
    'payment_method' => 'cash', // or 'bank_transfer'
    'description' => 'Advance payment',
]);
```

---

### Q: How do I check outstanding fees for a student?

**A:**

```php
$student = \App\Models\Student::with(['grade.fees', 'payments'])->find(1);

// Total fees
$totalFees = $student->grade->fees()->sum('amount');

// Total paid
$totalPaid = $student->payments()->sum('amount');

// Outstanding
$remaining = $totalFees - $totalPaid;

echo "Outstanding: $" . number_format($remaining, 2);
```

---

## 🐛 Troubleshooting

### Q: I get "419 Page Expired" error

**A:** This is related to CSRF token:

```bash
# Clear cache
php artisan optimize:clear

# Ensure @csrf is in forms
```

In Blade file:
```blade
<form method="POST">
    @csrf
    <!-- ... -->
</form>
```

---

### Q: I get "Class not found" error

**A:**

```bash
composer dump-autoload
php artisan optimize:clear
```

---

### Q: Images and CSS don't appear

**A:**

```bash
# Ensure Vite is running
npm run dev

# Or for production
npm run build

# Create symbolic link for storage
php artisan storage:link
```

---

### Q: How do I view errors in Laravel?

**A:**

```bash
# View logs directly
tail -f storage/logs/laravel.log

# Or use Laravel Pail
php artisan pail
```

---

### Q: The project is very slow

**A:** See [Performance & Optimization](#-performance--optimization) section.

---

## ⚡ Performance & Optimization

### Q: How do I optimize project performance?

**A:**

```bash
# 1. Cache configurations
php artisan config:cache
php artisan route:cache
php artisan view:cache

# 2. Optimize Composer
composer install --optimize-autoloader --no-dev

# 3. Use Queue for heavy tasks
php artisan queue:work

# 4. Use Redis for cache (if available)
# In .env:
# CACHE_STORE=redis
```

---

### Q: How do I avoid N+1 Query problem?

**A:** Use Eager Loading:

```php
// ❌ Bad - N+1 problem
$students = Student::all();
foreach ($students as $student) {
    echo $student->grade->name; // Extra query per student
}

// ✅ Good - Eager Loading
$students = Student::with('grade')->get();
foreach ($students as $student) {
    echo $student->grade->name; // No extra queries
}
```

---

### Q: How do I inspect database queries?

**A:** Use Laravel Debugbar or:

```bash
# In .env
DB_QUERY_LOG=true

# Then in code
\DB::enableQueryLog();
// ... your queries
dd(\DB::getQueryLog());
```

---

## 🔒 Security

### Q: How do I protect the project from attacks?

**A:**

1. **Use HTTPS** in production
2. **Never share .env file**
3. **Use strong passwords**
4. **Enable CSRF Protection**:
   ```blade
   <form>
       @csrf
   </form>
   ```
5. **Check permissions**:
   ```php
   $this->authorize('update', $student);
   ```
6. **Validate inputs**:
   ```php
   $validated = $request->validate([
       'name' => 'required|string|max:255',
       'email' => 'required|email|unique:users',
   ]);
   ```

---

### Q: How do I prevent SQL Injection?

**A:** Use Eloquent or Query Builder (automatically safe):

```php
// ✅ Safe
$user = User::where('email', $email)->first();

// ✅ Safe
$users = DB::table('users')->where('role', 'admin')->get();

// ❌ Dangerous - don't use raw queries with user input
// $users = DB::select("SELECT * FROM users WHERE email = '$email'");
```

---

### Q: How do I protect routes from unauthorized access?

**A:** Use Middleware:

```php
// In routes/web.php
Route::middleware(['auth', 'role:admin'])->group(function () {
    Route::get('/admin/dashboard', [AdminController::class, 'index']);
});
```

---

## 🌐 Production

### Q: How do I deploy the project to a server?

**A:**

```bash
# 1. On the server
git clone <repository-url>
cd school_system

# 2. Install
composer install --optimize-autoloader --no-dev
npm install
npm run build

# 3. Setup .env
cp .env.example .env
# Edit .env with production details

php artisan key:generate
php artisan migrate --force

# 4. Permissions
chmod -R 755 storage bootstrap/cache

# 5. Cache
php artisan config:cache
php artisan route:cache
php artisan view:cache
```

---

### Q: What are the important .env settings for production?

**A:**

```env
APP_ENV=production
APP_DEBUG=false
APP_URL=https://yourdomain.com

# Use strong passwords
DB_PASSWORD=strong_secure_password

# Enable HTTPS
SESSION_SECURE_COOKIE=true
```

---

## 📞 Additional Help

### Q: I didn't find an answer to my question, what should I do?

**A:**

1. **Search documentation**: [README.md](README.md) | [DATABASE_SETUP.md](DATABASE_SETUP.md)
2. **Search Issues**: Your question may have been asked before
3. **Open a new Issue**: Describe the problem in detail
4. **Contact the team**: See [CONTRIBUTING.md](CONTRIBUTING.md)

---

<p align="center">
  <strong>💡 Have another question? Don't hesitate to open an Issue!</strong>
</p>
