<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\Transaction;

class StudentDashboardController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $registrationNumber = strtoupper($user->username);

        // ✅ Get programme details from registrations + programmes
        $programmeData = DB::table('registrations')
            ->join('programmes', 'registrations.programme_code', '=', 'programmes.programme_code')
            ->where(DB::raw('UPPER(registrations.registration_number)'), $registrationNumber)
            ->select(
                'programmes.description',
                'programmes.attendance_mode',
                'programmes.total_credits',
                'programmes.duration',
                'programmes.status'
            )
            ->first();

        // ✅ Get transactions and calculate balance
        $transactions = Transaction::where('registration_number', $registrationNumber)->get();
        $totalDebit = $transactions->sum('debit');
        $totalCredit = $transactions->sum('credit');
        $balance = $totalDebit - $totalCredit;

        // ✅ Pass data to dashboard view
        return view('student.dashboard', [
            'user' => $user,
            'programme' => $programmeData?->description ?? 'N/A',
            'attendanceMode' => $programmeData?->attendance_mode ?? 'N/A',
            'credits' => $programmeData?->total_credits ?? 'N/A',
            'duration' => $programmeData?->duration ?? 'N/A',
            'status' => $programmeData?->status ?? 'N/A',
            'balance' => $balance,
        ]);
    }
}
