# 🤝 Contributing to School Management System

Thank you for your interest in contributing to the School Management System! We welcome all contributions from bug reports, feature suggestions, code improvements, and documentation updates.

---

## 📋 Table of Contents

1. [Code of Conduct](#-code-of-conduct)
2. [How to Contribute](#-how-to-contribute)
3. [Code Standards](#-code-standards)
4. [Pull Request Process](#-pull-request-process)
5. [Reporting Bugs](#-reporting-bugs)
6. [Suggesting Features](#-suggesting-features)

---

## 📜 Code of Conduct

### Our Pledge

We as contributors and maintainers pledge to make participation in our project a harassment-free experience for everyone, regardless of:
- Age
- Gender
- Level of experience
- Nationality
- Personal appearance
- Race
- Religion
- Sexual identity

### Expected Behavior

- Use welcoming and inclusive language
- Respect differing viewpoints and experiences
- Gracefully accept constructive criticism
- Focus on what is best for the community
- Show empathy towards other community members

### Unacceptable Behavior

- Use of sexualized language or imagery
- Trolling, insulting/derogatory comments
- Public or private harassment
- Publishing others' private information without permission
- Other unprofessional conduct

---

## 🚀 How to Contribute

### 1. Setup Development Environment

```bash
# Fork the project on GitHub then clone it
git clone https://github.com/YOUR_USERNAME/school_system.git
cd school_system

# Add upstream remote
git remote add upstream https://github.com/ORIGINAL_OWNER/school_system.git

# Install dependencies
composer install
npm install

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

# Setup database
php artisan migrate
```

### 2. Create a New Branch

Use clear and descriptive branch names:

```bash
# For new features
git checkout -b feature/add-student-dashboard

# For bug fixes
git checkout -b fix/attendance-calculation-error

# For improvements
git checkout -b improve/database-performance

# For documentation
git checkout -b docs/update-readme
```

### 3. Write Code

Follow the [Code Standards](#-code-standards) mentioned below.

### 4. Testing

```bash
# Run tests
php artisan test

# Run specific test
php artisan test --filter=StudentControllerTest
```

### 5. Commit Changes

Use clear commit messages in English:

```bash
# Good examples:
git commit -m "Add student attendance report feature"
git commit -m "Fix payment calculation bug in Fee model"
git commit -m "Improve database query performance for marks"
git commit -m "Update installation documentation"

# Bad examples (avoid these):
git commit -m "update"
git commit -m "fix bug"
git commit -m "changes"
```

#### Recommended Commit Message Format

```
<type>: <subject>

<body>
```

**Types**:
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation update
- `style`: Code formatting (no logic changes)
- `refactor`: Code refactoring
- `test`: Adding or updating tests
- `chore`: Maintenance tasks

**Example**:
```
feat: Add export to Excel functionality for student grades

- Implement Excel export using Maatwebsite/Excel
- Add new route and controller method
- Create export view with formatting
- Add download button in grades page
```

### 6. Push Changes

```bash
git push origin feature/your-feature-name
```

### 7. Open Pull Request

Go to GitHub and open a Pull Request from your branch to the main branch.

---

## 💻 Code Standards

### PHP Code Standards

#### 1. Follow PSR-12

```php
<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Http\Request;

class StudentController extends Controller
{
    /**
     * Display a listing of students.
     */
    public function index(): View
    {
        $students = Student::with('grade')
            ->latest()
            ->paginate(20);

        return view('students.index', compact('students'));
    }
}
```

#### 2. Use Laravel Pint

```bash
# Format code automatically
./vendor/bin/pint

# Check without modifying
./vendor/bin/pint --test
```

#### 3. Type Hints

Always use type hints:

```php
// ✅ Good
public function store(Request $request): RedirectResponse
{
    $validated = $request->validate([
        'name' => 'required|string|max:255',
    ]);
    
    return redirect()->route('students.index');
}

// ❌ Bad
public function store($request)
{
    // ...
}
```

#### 4. Clear Naming

```php
// ✅ Good
$averageGrade = $student->marks->avg('score');
$hasPassedExam = $mark->score >= 50;

// ❌ Bad
$avg = $s->m->avg('s');
$x = $m->s >= 50;
```

#### 5. Use Eloquent Properly

```php
// ✅ Good - Use Eager Loading
$students = Student::with(['grade', 'parent', 'marks'])->get();

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

### Blade Templates

```blade
{{-- ✅ Good --}}
@foreach ($students as $student)
    <div class="student-card">
        <h3>{{ $student->name }}</h3>
        <p>{{ $student->grade->name ?? 'N/A' }}</p>
    </div>
@endforeach

{{-- ❌ Bad --}}
<?php foreach($students as $student): ?>
    <div>
        <?php echo $student->name; ?>
    </div>
<?php endforeach; ?>
```

### JavaScript Standards

```javascript
// ✅ Good - Use const/let, arrow functions
const calculateTotal = (items) => {
    return items.reduce((sum, item) => sum + item.price, 0);
};

// ❌ Bad - var, old function expressions
var calculateTotal = function(items) {
    var sum = 0;
    for (var i = 0; i < items.length; i++) {
        sum += items[i].price;
    }
    return sum;
};
```

### CSS/TailwindCSS

```html
<!-- ✅ Good - Use utility classes with semantic HTML -->
<button class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
    Submit
</button>

<!-- ❌ Bad - inline styles -->
<button style="padding: 8px 16px; background: blue; color: white;">
    Submit
</button>
```

### Database Migrations

```php
// ✅ Good - Clear and organized
Schema::create('student_marks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('student_id')->constrained()->cascadeOnDelete();
    $table->foreignId('subject_id')->constrained()->cascadeOnDelete();
    $table->foreignId('exam_id')->nullable()->constrained()->nullOnDelete();
    $table->decimal('score', 5, 2);
    $table->timestamps();
    
    $table->index(['student_id', 'subject_id']);
});
```

---

## 🔄 Pull Request Process

### Before Submitting PR

- [ ] Ensure code runs without errors
- [ ] Run `./vendor/bin/pint` to format code
- [ ] Run `php artisan test` to ensure tests pass
- [ ] Update documentation if needed
- [ ] Ensure commits are organized with clear messages

### Pull Request Template

When opening a PR, use this template:

```markdown
## Description
Brief description of changes made.

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Refactoring

## Testing
How were these changes tested?

- [ ] Added new tests
- [ ] Manual testing
- [ ] All existing tests pass

## Screenshots (if applicable)
Add screenshots of UI changes if any.

## Additional Notes
Any other notes for reviewers.
```

### Code Review

- PR will be reviewed by at least one maintainer
- Reviewers may request changes
- Collaborate with reviewers to improve code
- After approval, PR will be merged

---

## 🐛 Reporting Bugs

### Before Reporting

1. **Search existing Issues**: The issue may already be reported
2. **Check documentation**: Ensure it's not a usage issue
3. **Try latest version**: The issue may already be fixed

### Bug Report Template

```markdown
**Description**
Clear and concise description of the issue.

**Steps to Reproduce**
1. Go to '...'
2. Click on '...'
3. Scroll to '...'
4. See error

**Expected Behavior**
Description of what should happen.

**Screenshots**
If applicable, add screenshots.

**Environment**
- OS: [e.g. Windows 11, Ubuntu 22.04]
- PHP Version: [e.g. 8.2.1]
- Laravel Version: [e.g. 12.0]
- Browser: [e.g. Chrome 120, Firefox 121]

**Additional Information**
Any other information about the issue.

**Logs or Error Messages**
```
// Add error messages here
```
```

---

## 💡 Suggesting Features

### Feature Request Template

```markdown
**Is your feature related to a problem?**
Clear description of the problem. Example: "I'm frustrated when [...]"

**Proposed Solution**
Clear description of what you want to happen.

**Alternative Solutions**
Description of any alternative solutions you've considered.

**Additional Context**
Any other context or screenshots about the feature request.

**Expected Benefits**
- Improve user experience
- Increase performance
- Easier maintenance
```

---

## 📝 Documentation Updates

Good documentation is as important as good code!

### Types of Documentation

1. **README.md**: Project overview
2. **DATABASE_SETUP.md**: Setup and installation guide
3. **Inline Comments**: Code comments
4. **DocBlocks**: Function and class documentation

### Example of Good DocBlock

```php
/**
 * Calculate the total fees paid by a student.
 *
 * This method sums all payments made by the student and returns
 * the total amount. It excludes refunded payments.
 *
 * @param Student $student The student to calculate fees for
 * @param string|null $academicYear Optional academic year filter
 * @return float The total amount paid
 *
 * @throws \InvalidArgumentException If student has no grade assigned
 */
public function calculateTotalFees(Student $student, ?string $academicYear = null): float
{
    // Implementation...
}
```

---

## 🏆 Recognition

All contributors will be mentioned in:
- Contributors list on GitHub
- CONTRIBUTORS.md file (if exists)
- Release Notes for new versions

---

## 📞 Communication

If you have questions about contributing:
- Open an Issue with `question` label
- Contact project maintainers
- Search closed Issues for similar questions

---

## 📚 Useful Resources

### Laravel
- [Laravel Documentation](https://laravel.com/docs)
- [Laravel Best Practices](https://github.com/alexeymezenin/laravel-best-practices)
- [Laracasts](https://laracasts.com)

### Git & GitHub
- [GitHub Flow](https://guides.github.com/introduction/flow/)
- [Git Best Practices](https://git-scm.com/book/en/v2)

### PHP
- [PSR-12 Coding Style](https://www.php-fig.org/psr/psr-12/)
- [PHP The Right Way](https://phptherightway.com)

---

## ✅ Contributor Checklist

Before submitting a contribution:

- [ ] Read this contributing guide
- [ ] Read the code of conduct
- [ ] Created a new branch from main/master
- [ ] Followed code standards
- [ ] Added/updated tests if needed
- [ ] Ran all tests and ensured they pass
- [ ] Ran Laravel Pint to format code
- [ ] Updated documentation if needed
- [ ] Wrote clear commit messages
- [ ] Filled out Pull Request template completely

---

<p align="center">
  <strong>Thank you for contributing to School Management System! 🎉</strong>
</p>
