<?php

namespace App\Http\Controllers;

use App\Models\Result;
use App\Models\Marksheet;
use App\Models\Student;
use App\Models\Classes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;

class ResultController extends Controller
{
    /**
     * Display result search page
     */
    public function index()
    {
        $classes = Classes::where('status', 1)->get();
        $examTypes = Result::getExamTypes();
        
        return view('results.index', compact('classes', 'examTypes'));
    }

    /**
     * Search results by student ID
     */
    public function search(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'student_id' => 'required|string|exists:students,student_id',
            'exam_type' => 'required|in:weekly,monthly,half_yearly,final,model_test,pre_test',
            'exam_year' => 'required|integer|min:2020|max:2030'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                           ->withErrors($validator)
                           ->withInput();
        }

        $student = Student::where('student_id', $request->student_id)
                          ->with('class')
                          ->firstOrFail();

        $results = Result::with('student')
                        ->where('student_id', $student->id)
                        ->where('exam_type', $request->exam_type)
                        ->where('exam_year', $request->exam_year)
                        ->orderBy('subject_code')
                        ->get();

        // Marksheet info
        $marksheet = Marksheet::where('student_id', $student->id)
                              ->where('exam_type', $request->exam_type)
                              ->where('exam_year', $request->exam_year)
                              ->first();

        // Calculate statistics
        $totalMarks = $results->sum('total_marks');
        $obtainedMarks = $results->sum('obtained_marks');
        $percentage = $totalMarks > 0 ? round(($obtainedMarks / $totalMarks) * 100, 2) : 0;
        $gpa = Result::calculateGPA($results);
        $grade = $this->getGradeFromGPA($gpa);
        
        $stats = [
            'total_subjects' => $results->count(),
            'total_marks' => $totalMarks,
            'obtained_marks' => $obtainedMarks,
            'percentage' => $percentage,
            'gpa' => $gpa,
            'grade' => $grade,
            'passed' => $results->where('status', 'pass')->count(),
            'failed' => $results->where('status', 'fail')->count()
        ];

        return view('results.show', compact('student', 'results', 'marksheet', 'stats', 'request'));
    }
    
    public function classEntryForm(Request $request)
{
    $classId = $request->class_id;
    $examId = $request->exam_id; // যদি পরীক্ষা সিলেক্ট করার অপশন থাকে

    // ওই ক্লাসের সকল সক্রিয় ছাত্র-ছাত্রীদের খুঁজে বের করা
    $students = \App\Models\Student::where('class_id', $classId)
                                   ->where('status', 1)
                                   ->orderBy('roll_number', 'asc')
                                   ->get();
    
    $class = \App\Models\Classes::find($classId);

    return view('results.class-entry', compact('students', 'class', 'request'));
}

    /**
     * Class wise result entry page
     */
    /**
 * Class wise result entry page
 */
public function classResult(Request $request)
{
    // GET প্যারামিটার থেকে ডাটা নিন
    $classId = $request->class_id;
    $examType = $request->exam_type;
    $examYear = $request->exam_year;
    
    // যদি কোনো প্যারামিটার না থাকে, তাহলে সিলেক্ট ফর্ম দেখান
    if (!$classId || !$examType || !$examYear) {
        $classes = \App\Models\Classes::where('status', 1)->get();
        $examTypes = \App\Models\Result::getExamTypes();
        return view('results.select-class', compact('classes', 'examTypes'));
    }
    
    // যদি প্যারামিটার থাকে, তাহলে রেজাল্ট এন্ট্রি ফর্ম দেখান
    $class = \App\Models\Classes::findOrFail($classId);
    $students = \App\Models\Student::where('class_id', $classId)
                          ->where('status', 1)
                          ->orderBy('roll_number')
                          ->get();

    $subjects = \App\Models\Result::getSubjects($classId);
    
    $existingResults = \App\Models\Result::where('class_id', $classId)
                                 ->where('exam_type', $examType)
                                 ->where('exam_year', $examYear)
                                 ->exists();

    return view('results.class-entry', compact('class', 'students', 'subjects', 'examType', 'examYear', 'existingResults'));
}
    
    // ট্যাবুলিশন শিটের জন্য ক্লাস ও পরীক্ষা সিলেক্ট করার ফর্ম
public function tabulationForm()
{
    $classes = \App\Models\Classes::where('status', 1)->get();
    return view('results.tabulation-form', compact('classes'));
}

// সিলেক্ট করা তথ্যের ভিত্তিতে শিট তৈরি করা
public function tabulationSheet(Request $request)
{
    $classId = $request->class_id;
    $examName = $request->exam_name;

    // ছাত্র-ছাত্রীদের রেজাল্টসহ খুঁজে বের করা
    $results = \App\Models\Result::with('student')
                ->where('class_id', $classId)
                ->where('exam_name', $examName)
                ->get()
                ->groupBy('student_id');

    return view('results.tabulation-sheet', compact('results', 'request'));
}

    /**
     * Save bulk results
     */
    public function storeBulk(Request $request)
{
    // ১. ভ্যালিডেশন
    $request->validate([
        'class_id' => 'required',
        'exam_type' => 'required',
        'exam_year' => 'required',
        'results' => 'required|array',
    ]);

    try {
        DB::beginTransaction();

        foreach ($request->results as $studentData) {
            $studentId = $studentData['student_id'];
            $roll = $studentData['roll'];

            foreach ($studentData['marks'] as $subjectCode => $markData) {
                // প্রাপ্ত নম্বর খালি থাকলে সেটি স্কিপ করবে
                if ($markData['obtained'] === null) continue;

                // একই ছাত্রের একই বিষয়ের রেজাল্ট থাকলে আপডেট করবে, না থাকলে নতুন তৈরি করবে
                App\Models\Result::updateOrCreate(
                    [
                        'student_id'   => $studentId,
                        'class_id'     => $request->class_id,
                        'exam_type'    => $request->exam_type,
                        'exam_year'    => $request->exam_year,
                        'subject_code' => $subjectCode,
                    ],
                    [
                        'student_roll'   => $roll,
                        'exam_name'      => $request->exam_name,
                        'subject'        => $subjectCode, // ডাটাবেসের 'subject' কলামে কোডটি রাখছি
                        'total_marks'    => $markData['total'],
                        'obtained_marks' => $markData['obtained'],
                        'remarks'        => $markData['remarks'] ?? '',
                        // গ্রেড ক্যালকুলেশন ফাংশন এখানে কল করতে পারেন
                        'grade'          => $this->calculateGrade($markData['obtained']), 
                    ]
                );
            }
        }

        DB::commit();
        return response()->json(['success' => true, 'message' => 'ফলাফল সফলভাবে সংরক্ষিত হয়েছে!']);

    } catch (\Exception $e) {
        DB::rollback();
        return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
    }
}

// গ্রেড বের করার একটি সহজ ফাংশন
private function calculateGrade($marks) {
    if ($marks >= 80) return 'A+';
    if ($marks >= 70) return 'A';
    if ($marks >= 60) return 'A-';
    if ($marks >= 50) return 'B';
    if ($marks >= 40) return 'C';
    if ($marks >= 33) return 'D';
    return 'F';
}

    /**
     * Generate marksheets for all students
     */
    private function generateMarksheets($classId, $examType, $examName, $examYear)
    {
        $students = Student::where('class_id', $classId)->where('status', 1)->get();
        $totalStudents = $students->count();

        foreach ($students as $student) {
            $results = Result::where('student_id', $student->id)
                            ->where('class_id', $classId)
                            ->where('exam_type', $examType)
                            ->where('exam_year', $examYear)
                            ->get();

            $totalMarks = $results->sum('total_marks');
            $obtainedMarks = $results->sum('obtained_marks');
            $percentage = $totalMarks > 0 ? round(($obtainedMarks / $totalMarks) * 100, 2) : 0;
            $gpa = Result::calculateGPA($results);
            $grade = $this->getGradeFromGPA($gpa);

            // Calculate rank
            $rank = DB::table('results')
                ->select('student_id', DB::raw('SUM(obtained_marks) as total'))
                ->where('class_id', $classId)
                ->where('exam_type', $examType)
                ->where('exam_year', $examYear)
                ->groupBy('student_id')
                ->orderBy('total', 'desc')
                ->get()
                ->search(function($item) use ($student) {
                    return $item->student_id == $student->id;
                }) + 1;

            Marksheet::updateOrCreate(
                [
                    'student_id' => $student->id,
                    'class_id' => $classId,
                    'exam_type' => $examType,
                    'exam_year' => $examYear
                ],
                [
                    'exam_name' => $examName,
                    'total_marks' => $totalMarks,
                    'obtained_marks' => $obtainedMarks,
                    'percentage' => $percentage,
                    'gpa' => $gpa,
                    'grade' => $grade,
                    'rank' => $rank,
                    'total_students' => $totalStudents,
                    'published_date' => now(),
                    'published_by' => auth()->id()
                ]
            );
        }
    }

    /**
     * Get grade from GPA
     */
    private function getGradeFromGPA($gpa)
    {
        if ($gpa >= 5.00) return 'A+';
        if ($gpa >= 4.00) return 'A';
        if ($gpa >= 3.50) return 'A-';
        if ($gpa >= 3.00) return 'B';
        if ($gpa >= 2.00) return 'C';
        if ($gpa >= 1.00) return 'D';
        return 'F';
    }

    /**
     * Get subject info
     */
    private function getSubjectInfo($code, $classId)
    {
        $subjects = Result::getSubjects($classId);
        foreach ($subjects as $subject) {
            if ($subject['code'] == $code) {
                return $subject;
            }
        }
        return ['code' => $code, 'name' => 'Unknown'];
    }

    /**
     * Download marksheet PDF
     */
    public function downloadMarksheet($studentId, $examType, $examYear)
    {
        $student = Student::with('class')->findOrFail($studentId);
        
        $results = Result::where('student_id', $studentId)
                        ->where('exam_type', $examType)
                        ->where('exam_year', $examYear)
                        ->orderBy('subject_code')
                        ->get();

        if ($results->isEmpty()) {
            return redirect()->back()->with('error', 'ফলাফল পাওয়া যায়নি');
        }

        $marksheet = Marksheet::where('student_id', $studentId)
                             ->where('exam_type', $examType)
                             ->where('exam_year', $examYear)
                             ->first();

        $pdf = Pdf::loadView('results.marksheet-pdf', compact('student', 'results', 'marksheet', 'examType', 'examYear'));
        
        return $pdf->download('marksheet_' . $student->student_id . '_' . $examType . '_' . $examYear . '.pdf');
    }

    /**
     * Tabulation sheet
     */
    /**
 * Tabulation sheet logic
 */
    /**
     * Result analytics
     */
    public function analytics(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'class_id' => 'required|exists:classes,id',
            'exam_type' => 'required|string',
            'exam_year' => 'required|integer'
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator);
        }

        $marksheets = Marksheet::where('class_id', $request->class_id)
                               ->where('exam_type', $request->exam_type)
                               ->where('exam_year', $request->exam_year)
                               ->get();

        $analytics = [
            'total_students' => $marksheets->count(),
            'passed' => $marksheets->where('gpa', '>=', 1.00)->count(),
            'failed' => $marksheets->where('gpa', '<', 1.00)->count(),
            'a_plus' => $marksheets->where('gpa', '>=', 5.00)->count(),
            'a_grade' => $marksheets->whereBetween('gpa', [4.00, 4.99])->count(),
            'a_minus' => $marksheets->whereBetween('gpa', [3.50, 3.99])->count(),
            'b_grade' => $marksheets->whereBetween('gpa', [3.00, 3.49])->count(),
            'c_grade' => $marksheets->whereBetween('gpa', [2.00, 2.99])->count(),
            'd_grade' => $marksheets->whereBetween('gpa', [1.00, 1.99])->count(),
            'average_gpa' => $marksheets->avg('gpa'),
            'highest_gpa' => $marksheets->max('gpa'),
            'lowest_gpa' => $marksheets->min('gpa')
        ];

        return view('results.analytics', compact('analytics', 'request'));
    }
    
    public function analyticsForm()
{
    $classes = \App\Models\Classes::where('status', 1)->get();
    return view('results.analytics-form', compact('classes'));
}

public function analyticsReport(Request $request)
{
    $classId = $request->class_id;
    $examName = $request->exam_name;

    $results = \App\Models\Result::where('class_id', $classId)
                ->where('exam_name', 'LIKE', "%{$examName}%")
                ->get();

    // উদাহরনস্বরূপ কিছু ডাটা ক্যালকুলেশন
    $totalStudents = $results->groupBy('student_id')->count();
    $passed = $results->where('grade', '!=', 'F')->groupBy('student_id')->count();
    $failed = $totalStudents - $passed;

    return view('results.analytics-report', compact('results', 'totalStudents', 'passed', 'failed', 'request'));
}

public function show($id)
{
    $result = Result::with('student', 'class')->findOrFail($id);
    
    return view('results.show', compact('result'));
}

    /**
     * Send result via SMS
     */
    public function sendSMS(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'student_id' => 'required|exists:students,id',
            'exam_type' => 'required|string',
            'exam_year' => 'required|integer'
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $student = Student::find($request->student_id);
        $marksheet = Marksheet::where('student_id', $request->student_id)
                             ->where('exam_type', $request->exam_type)
                             ->where('exam_year', $request->exam_year)
                             ->first();

        if (!$marksheet) {
            return response()->json(['error' => 'মার্কশিট পাওয়া যায়নি'], 404);
        }

        // SMS পাঠান
        $message = "প্রিয় {$student->name_bn}, আপনার {$marksheet->exam_name} {$marksheet->exam_year} এর ফলাফল: GPA {$marksheet->gpa}, Grade {$marksheet->grade}। মোট প্রাপ্ত নম্বর: {$marksheet->obtained_marks}/{$marksheet->total_marks}। ধন্যবাদ।";
        
        // এখানে আপনার SMS API কল করুন
        // $this->sendSMS($student->phone, $message);

        return response()->json([
            'success' => true,
            'message' => 'SMS পাঠানো হয়েছে'
        ]);
    }
}