# KPI System - Quick Start Guide

## Initial Setup

### 1. Database Setup (Already Completed)
```bash
php artisan migrate
php artisan db:seed --class=RoleSeeder
php artisan db:seed --class=KpiSeeder  # Optional: sample data
```

### 2. Create Your First Admin User

```php
use App\Models\User;
use App\Models\Role;

// Create admin user
$admin = User::create([
    'name' => 'Admin User',
    'email' => 'admin@example.com',
    'password' => bcrypt('password'),
    'department_id' => null, // Admins don't need a department
]);

// Assign admin role
$admin->assignRole('admin');
```

### 3. Create Department Head User

```php
use App\Models\User;
use App\Models\Department;

// Get or create a department
$itDept = Department::firstOrCreate(
    ['name' => 'Information Technology'],
    ['description' => 'IT Department']
);

// Create head user
$head = User::create([
    'name' => 'IT Department Head',
    'email' => 'head@example.com',
    'password' => bcrypt('password'),
    'department_id' => $itDept->id,
]);

// Assign head role
$head->assignRole('head');
```

### 4. Create Staff User

```php
use App\Models\User;
use App\Models\Department;

$itDept = Department::where('name', 'Information Technology')->first();

// Create staff user
$staff = User::create([
    'name' => 'IT Staff Member',
    'email' => 'staff@example.com',
    'password' => bcrypt('password'),
    'department_id' => $itDept->id,
]);

// Assign staff role
$staff->assignRole('staff');
```

## Common Workflows

### Admin Workflow: Setting Up KPIs for 2026

```php
use App\Models\Kpi;
use App\Models\KpiYear;
use App\Models\Department;
use App\Models\KpiDepartmentAssignment;

// 1. Create a new KPI
$kpi = Kpi::create([
    'title' => 'Customer Satisfaction Score',
    'description' => 'Measure customer satisfaction on a scale of 0-100',
]);

// 2. Create a year instance for 2026
$kpiYear = KpiYear::create([
    'kpi_id' => $kpi->id,
    'year' => 2026,
    'default_goal_value' => 85, // Default target
]);

// 3. Assign to IT department with custom target
$itDept = Department::where('name', 'Information Technology')->first();

KpiDepartmentAssignment::create([
    'kpi_year_id' => $kpiYear->id,
    'department_id' => $itDept->id,
    'target_value' => 90, // IT department's specific target
]);

// 4. Assign to HR department with different target
$hrDept = Department::where('name', 'Human Resources')->first();

KpiDepartmentAssignment::create([
    'kpi_year_id' => $kpiYear->id,
    'department_id' => $hrDept->id,
    'target_value' => 85, // HR department's target
]);
```

### Staff Workflow: Entering Monthly Progress

```php
use App\Models\KpiProgress;
use App\Models\KpiDepartmentAssignment;

// Get the assignment for your department
$assignment = KpiDepartmentAssignment::whereHas('department', function($query) {
    $query->where('name', 'Information Technology');
})->first();

// Enter progress for January 2026
KpiProgress::create([
    'kpi_department_assignment_id' => $assignment->id,
    'month' => 1, // January
    'year' => 2026,
    'progress_value' => 8.5, // Actual progress value
    'remarks' => 'Good progress in January, customer feedback positive',
]);

// Enter progress for February 2026
KpiProgress::create([
    'kpi_department_assignment_id' => $assignment->id,
    'month' => 2, // February
    'year' => 2026,
    'progress_value' => 7.8,
    'remarks' => 'Slight dip due to system downtime',
]);
```

### Head Workflow: Viewing Department Performance

```php
use App\Models\Department;

// Get your department
$myDepartment = auth()->user()->department;

// Get all KPIs for 2026
$kpis = $myDepartment->kpiAssignmentsForYear(2026);

// Get progress summary with calculations
$summary = $myDepartment->kpiProgressSummary(2026);

// Example output:
foreach ($summary as $item) {
    echo "KPI: {$item['kpi_title']}\n";
    echo "Target: {$item['target_value']}\n";
    echo "Total Progress: {$item['total_progress']}\n";
    echo "Average: {$item['average_progress']}\n";
    echo "---\n";
}
```

## Useful Queries

### Get All KPIs for a Department (with Progress)

```php
use App\Models\Department;

$department = Department::find(1);
$year = 2026;

$kpis = $department->kpiAssignments()
    ->whereHas('kpiYear', fn($q) => $q->where('year', $year))
    ->with(['kpiYear.kpi', 'progress'])
    ->get();

foreach ($kpis as $assignment) {
    echo "KPI: {$assignment->kpiYear->kpi->title}\n";
    echo "Target: {$assignment->target_value}\n";
    echo "Completion: {$assignment->getCompletionPercentage($year)}%\n";
}
```

### Get Progress for Specific Month

```php
use App\Models\KpiProgress;

// Get all progress for March 2026
$marchProgress = KpiProgress::where('month', 3)
    ->where('year', 2026)
    ->with('kpiDepartmentAssignment.department', 'kpiDepartmentAssignment.kpiYear.kpi')
    ->get();

foreach ($marchProgress as $progress) {
    echo "Department: {$progress->kpiDepartmentAssignment->department->name}\n";
    echo "KPI: {$progress->kpiDepartmentAssignment->kpiYear->kpi->title}\n";
    echo "Progress: {$progress->progress_value}\n";
}
```

### Get Departments At Risk (< 50% completion)

```php
use App\Models\KpiDepartmentAssignment;

$year = 2026;

$atRisk = KpiDepartmentAssignment::with(['department', 'kpiYear.kpi'])
    ->get()
    ->filter(function ($assignment) use ($year) {
        return $assignment->getCompletionPercentage($year) < 50;
    });

foreach ($atRisk as $assignment) {
    echo "⚠️ {$assignment->department->name} - {$assignment->kpiYear->kpi->title}\n";
    echo "   Completion: {$assignment->getCompletionPercentage($year)}%\n";
}
```

### Get Top Performing Departments

```php
use App\Models\Department;

$year = 2026;

$departments = Department::with(['kpiAssignments' => function($query) use ($year) {
    $query->whereHas('kpiYear', fn($q) => $q->where('year', $year));
}])->get();

$performance = $departments->map(function ($dept) use ($year) {
    $avgCompletion = $dept->kpiAssignments->avg(function ($assignment) use ($year) {
        return $assignment->getCompletionPercentage($year);
    });
    
    return [
        'department' => $dept->name,
        'avg_completion' => $avgCompletion,
    ];
})->sortByDesc('avg_completion');

foreach ($performance as $item) {
    echo "{$item['department']}: {$item['avg_completion']}%\n";
}
```

## Testing Users

After running the seeders, you can create test users:

```php
// In tinker or a seeder:

// Admin
$admin = User::factory()->create([
    'name' => 'Admin User',
    'email' => 'admin@test.com',
    'password' => bcrypt('password'),
]);
$admin->assignRole('admin');

// IT Department Head
$itHead = User::factory()->create([
    'name' => 'IT Head',
    'email' => 'it-head@test.com',
    'password' => bcrypt('password'),
    'department_id' => Department::where('name', 'Information Technology')->first()->id,
]);
$itHead->assignRole('head');

// IT Staff
$itStaff = User::factory()->create([
    'name' => 'IT Staff',
    'email' => 'it-staff@test.com',
    'password' => bcrypt('password'),
    'department_id' => Department::where('name', 'Information Technology')->first()->id,
]);
$itStaff->assignRole('staff');
```

## Navigation Links

Add these to your navigation menu based on user role:

```blade
@auth
    @if(auth()->user()->isAdmin())
        <a href="{{ route('admin.kpi.index') }}">Manage KPIs</a>
        <a href="{{ route('admin.kpi.assignments') }}">Department Assignments</a>
        <a href="{{ route('admin.kpi.dashboard') }}">KPI Dashboard</a>
    @endif

    @if(auth()->user()->isHead())
        <a href="{{ route('head.department.kpis') }}">My Department KPIs</a>
    @endif

    @if(auth()->user()->isStaff())
        <a href="{{ route('staff.kpis.view') }}">View KPIs</a>
        <a href="{{ route('staff.progress.entry') }}">Enter Progress</a>
    @endif
@endauth
```

## Tips & Best Practices

### 1. Set Realistic Targets
- Don't set targets too high or too low
- Consider historical data when available
- Allow for seasonal variations

### 2. Enter Progress Regularly
- Encourage staff to enter progress monthly
- Set reminders for progress entry deadlines
- Review and approve entries if needed

### 3. Monitor Performance
- Department heads should review weekly
- Admins should monitor trends monthly
- Address at-risk KPIs proactively

### 4. Use Remarks Effectively
- Document reasons for variations
- Note external factors affecting performance
- Reference specific initiatives or events

### 5. Year-End Review
- Compare actual vs target for all KPIs
- Identify trends and patterns
- Use data to set next year's targets

## Common Issues

### Issue: Staff can't see their KPIs
**Solution:**
- Ensure user has `staff` role assigned
- Verify user has `department_id` set
- Check that KPIs are assigned to their department for the current year

### Issue: Head can't access department view
**Solution:**
- Ensure user has `head` role assigned
- Verify user has `department_id` set
- Check route middleware is applied correctly

### Issue: Progress not calculating correctly
**Solution:**
- Verify all progress entries have correct month/year
- Check for duplicate entries (should be prevented by unique constraint)
- Ensure target_value is set on the assignment

## Next Steps

1. **Customize the UI**: Update Flux UI components to match your branding
2. **Add Notifications**: Send reminders when progress is due
3. **Create Reports**: Build PDF/Excel export functionality
4. **Add Charts**: Visualize progress with charts (Chart.js, ApexCharts)
5. **Implement Approvals**: Add approval workflow for progress entries
6. **Track History**: Add audit log for changes
7. **Mobile App**: Create mobile-friendly views for staff entry

Enjoy your new KPI tracking system! 🎉
