<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StudentResultsController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        // Use stored registration_number or fallback to username
        $registrationNumber = $user->registration_number ?? strtoupper($user->username);

        // Fetch joined result + course data
        $results = DB::table('results')
            ->join('courses', 'courses.course_code', '=', 'results.course_code')
            ->where('results.registration_number', $registrationNumber)
            ->select(
                'courses.course_code',
                'courses.course_description',
                'courses.level',
                'courses.semester',
                'results.coursework_mark',
                'results.exam_mark'
            )
            ->get()
            ->map(function ($row) {
                $special = ['PC1106', 'PC1107', 'PC1111', 'PC1112', 'PC1205', 'PC1206', 'PC1212', 'PC1213'];

                // ✅ Calculate final mark (coursework out of 40 + exam out of 60)
                $finalMark = ($row->coursework_mark ?? 0) + ($row->exam_mark ?? 0);
                $row->final_mark = $finalMark;

                // ✅ Grade logic
                if (in_array($row->course_code, $special)) {
                    if ($finalMark >= 91) $row->grade = 'Distinction';
                    elseif ($finalMark >= 75) $row->grade = 'Merit';
                    elseif ($finalMark >= 60) $row->grade = 'Credit';
                    elseif ($finalMark >= 50) $row->grade = 'Pass';
                    else $row->grade = 'Fail – Rewrite';
                } else {
                    if ($finalMark >= 75) $row->grade = 'Distinction';
                    elseif ($finalMark >= 70) $row->grade = 'Merit';
                    elseif ($finalMark >= 60) $row->grade = 'Credit';
                    elseif ($finalMark >= 50) $row->grade = 'Pass';
                    elseif ($finalMark >= 40) $row->grade = 'Fail – Supplementary';
                    else $row->grade = 'Fail – Repeat';
                }

                // ✅ Visual decision tag (no emojis now — use 'P', 'F', etc.)
                if (str_starts_with($row->grade, 'Distinction') || str_starts_with($row->grade, 'Merit') || str_starts_with($row->grade, 'Credit')) {
                    $row->decision = 'P'; // Pass
                } elseif (str_starts_with($row->grade, 'Pass')) {
                    $row->decision = 'P'; // Still Pass
                } else {
                    $row->decision = 'F'; // Fail
                }

                // ✅ Grouping
                $row->group = "{$row->level} - {$row->semester}";

                return $row;
            });

        // ✅ Group by level and semester
        $groups = $results->groupBy('group');

        if ($results->isEmpty()) {
            Log::warning("No results found for registration number: $registrationNumber");
        }

        return view('student.results', compact('groups'));
    }
}
