<?php

namespace App\Http\Controllers;

use App\Models\Result;
use App\Models\Student;
use App\Models\Subject;
use App\Models\Classes;
use Illuminate\Http\Request;

class ResultController extends Controller
{
    public function index()
    {
        $results = Result::with(['student', 'subject', 'class'])->latest()->paginate(20);
        return view('admin.results.index', compact('results'));
    }

    public function create()
    {
        $students = Student::all();
        $subjects = Subject::all();
        $classes = Classes::all();
        return view('admin.results.create', compact('students', 'subjects', 'classes'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'student_id' => 'required|exists:students,id',
            'subject_id' => 'required|exists:subjects,id',
            'class_id' => 'required|exists:classes,id',
            'session_year' => 'required|string',
            'term' => 'required|string',
            'first_test' => 'nullable|integer|min:0|max:100',
            'second_test' => 'nullable|integer|min:0|max:100',
            'exam_score' => 'nullable|integer|min:0|max:100',
        ]);

        // Calculate total and grade
        $total = ($validated['first_test'] ?? 0) + ($validated['second_test'] ?? 0) + ($validated['exam_score'] ?? 0);
        $validated['total_score'] = $total;
        $validated['grade'] = $this->calculateGrade($total);
        $validated['remarks'] = $this->calculateRemarks($total);

        Result::create($validated);

        return redirect()->route('admin.results.index')->with('success', 'Result added successfully!');
    }

    public function show(Result $result)
    {
        return view('admin.results.show', compact('result'));
    }

    public function edit(Result $result)
    {
        $students = Student::all();
        $subjects = Subject::all();
        $classes = Classes::all();
        return view('admin.results.edit', compact('result', 'students', 'subjects', 'classes'));
    }

    public function update(Request $request, Result $result)
    {
        $validated = $request->validate([
            'student_id' => 'required|exists:students,id',
            'subject_id' => 'required|exists:subjects,id',
            'class_id' => 'required|exists:classes,id',
            'session_year' => 'required|string',
            'term' => 'required|string',
            'first_test' => 'nullable|integer|min:0|max:100',
            'second_test' => 'nullable|integer|min:0|max:100',
            'exam_score' => 'nullable|integer|min:0|max:100',
        ]);

        $total = ($validated['first_test'] ?? 0) + ($validated['second_test'] ?? 0) + ($validated['exam_score'] ?? 0);
        $validated['total_score'] = $total;
        $validated['grade'] = $this->calculateGrade($total);
        $validated['remarks'] = $this->calculateRemarks($total);

        $result->update($validated);

        return redirect()->route('admin.results.index')->with('success', 'Result updated successfully!');
    }

    public function destroy(Result $result)
    {
        $result->delete();
        return redirect()->route('admin.results.index')->with('success', 'Result deleted successfully!');
    }

    // Student Portal: View my results
    public function studentResults()
    {
        $user = auth()->user();
        $student = $user->student;
        $results = Result::where('student_id', $student->id)->with(['subject', 'class'])->get();
        return view('student.results', compact('results', 'student'));
    }

    private function calculateGrade($score)
    {
        if ($score >= 70) return 'A';
        if ($score >= 60) return 'B';
        if ($score >= 50) return 'C';
        if ($score >= 40) return 'D';
        if ($score >= 30) return 'E';
        return 'F';
    }

    private function calculateRemarks($score)
    {
        if ($score >= 70) return 'Excellent';
        if ($score >= 60) return 'Very Good';
        if ($score >= 50) return 'Good';
        if ($score >= 40) return 'Average';
        if ($score >= 30) return 'Below Average';
        return 'Poor';
    }
}