<?php

namespace App\Http\ViewComposers;

use Illuminate\View\View;
use Illuminate\Support\Facades\Auth;
use App\Models\Enrollment;
use App\Models\FeePayment;

class StudentBalanceComposer
{
    /**
     * Bind data to the view.
     *
     * @param  \Illuminate\View\View  $view
     * @return void
     */
    public function compose(View $view)
    {
        if (Auth::check() && Auth::user()->role === 'student') {
            $student = Auth::user();
            
            // Get enrolled courses
            $enrollments = Enrollment::where('student_id', $student->id)
                ->with('course')
                ->get();
            
            // Calculate total outstanding balance
            $totalOutstanding = 0;
            $feeAlerts = [];
            
            foreach ($enrollments as $enrollment) {
                if ($enrollment->course) {
                    $courseFee = $enrollment->course->fees;
                    $paidAmount = FeePayment::where('student_id', $student->id)
                        ->where(function($q) use ($enrollment) {
                            $q->where('course_id', $enrollment->course_id);
                            if ($enrollment->course_offering_id) {
                                $q->orWhere('course_offering_id', $enrollment->course_offering_id);
                            }
                        })
                        ->sum('amount');
                    
                    $balance = $courseFee - $paidAmount;
                    
                    if ($balance > 0) {
                        $totalOutstanding += $balance;
                        $feeAlerts[] = [
                            'course' => $enrollment->course,
                            'balance' => $balance,
                            'paid' => $paidAmount,
                            'total' => $courseFee,
                        ];
                    }
                }
            }
            
            $view->with('studentOutstandingBalance', $totalOutstanding);
            $view->with('studentFeeAlerts', $feeAlerts);
        } else {
            $view->with('studentOutstandingBalance', 0);
            $view->with('studentFeeAlerts', []);
        }
    }
}

