<?php

namespace App\Http\Controllers\Result;

use App\Models\Result\Exam;
use Illuminate\Http\Request;
use App\Models\Result\MarkHead;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Academic\StudentClass;
use App\Models\Result\MarkHeadAssign;
use App\Models\Academic\SubjectsAssign;

class MarksHeadAssignController extends Controller
{
    public function assignList(Request $request)
    {
        
        $exam_id          = $request->exam ?? getCurrentActiveExamId();
        $student_class_id = $request->student_class;

        $assignMarksHead = [];

        $exams = Exam::orderBy('id', 'desc')
            ->select('id', 'exam_name', 'year')
            ->get();

        $studentClasses = StudentClass::pluck('class_name', 'id');

        $mark_heads = MarkHead::pluck('head_name', 'id')->toArray();

        $assignMarksHeadQuery = MarkHeadAssign::with([
            'studentClass',
            'subject',
            'exam',
            'exam.academic_year'
        ]);

        // ✅ Apply filters safely
        if ($exam_id) {
            $assignMarksHeadQuery->where('exam_id', $exam_id);
        }

        if ($student_class_id) {
            $assignMarksHeadQuery->where('student_class_id', $student_class_id);
        }

        // ✅ CORRECT groupBy syntax
        $assignMarksHead = $assignMarksHeadQuery
            ->orderBy('student_class_id')
            ->get()
            ->groupBy([
                'student_class_id'
            ]);

        // dd($mark_heads, $exam_id, $assignMarksHead);

        return view(
            "pages.result.mark_head_assign.index",
            compact(
                'studentClasses',
                'mark_heads',
                'assignMarksHead',
                'exams',
                'exam_id',
                'student_class_id'
            )
        );
    }


    public function assignList2(Request $request)
    {
        $exam_id = $request->exam;
        $student_class_id = $request->student_class;
        $mark_head = [];
        $assignMarksHead = [];
        $exams = Exam::orderBy('id', 'desc')->select('id','exam_name','year')->get();
        $studentClasses = StudentClass::pluck('class_name', 'id');
    
        $mark_heads = MarkHead::pluck('head_name', 'id')->toArray();
        $assignMarksHeadQuery = MarkHeadAssign::with(['studentClass', 'subject', 'exam', 'exam.academic_year']);
        if ($exam_id) {
            $assignMarksHeadQuery->where('exam_id', $exam_id);
            if($student_class_id){
                $assignMarksHeadQuery->where('student_class_id', $student_class_id);
            }
            $assignMarksHead = $assignMarksHeadQuery->orderBy('student_class_id')->get()->groupBy('student_class_id');
        }   
        return view("pages.result.mark_head_assign.index", compact('studentClasses', 'mark_heads', 'assignMarksHead', 'exams', 'exam_id', 'student_class_id'));
    }

    public function assignCreate()
    {
        $subjects_assigns = '';
        $filter_mark_heads = '';
        $exam_id = '';
        $student_class_id = '';
        $mark_head = [];
        $assignMarksHead = [];
        $exams = Exam::orderBy('id', 'desc')->select('id','exam_name','year')->get();
        $studentClasses = StudentClass::pluck('class_name', 'id');
        $mark_heads = MarkHead::all();
        return view("pages.result.mark_head_assign.create", compact('subjects_assigns', 'filter_mark_heads', 'exam_id', 'student_class_id', 'studentClasses', 'mark_heads', 'exams', 'mark_head', 'assignMarksHead' ));
    }
    public function assignCopyCreate(){
        $original_exams = DB::select("
            SELECT DISTINCT t1.id, t1.exam_name, t3.year
            FROM exams t1
            INNER JOIN mark_head_assigns t2 ON t1.id = t2.exam_id
            LEFT JOIN academic_years t3 ON t1.year = t3.id
            ORDER BY t3.year DESC, t1.id DESC
        ");


        $copied_exams = DB::select("
            SELECT t1.id, t1.exam_name, t3.year FROM exams t1
            LEFT JOIN mark_head_assigns t2 ON t1.id = t2.exam_id
            LEFT JOIN academic_years t3 ON t1.year = t3.id WHERE t2.exam_id IS NULL
        ");

        // dd($original_exams, $copied_exams);

        return view("pages.result.mark_head_assign.mark-copy", compact('original_exams','copied_exams'));
    }

    public function assignCopyStore(Request $request){
        $validatedData = $request->validate([
            'copied_exam' => 'required|integer',
            'original_exam' => 'required|integer',
        ]);
        
        $copied_exam_id = $request->copied_exam;
        
        // Check if the copied_exam_id already exists in MarkHeadAssign
        $exist = MarkHeadAssign::where('exam_id', $copied_exam_id)->exists();
        
        if ($exist) {
            // Return warning if the copied_exam_id already exists
            return redirect()->back()->with('warning', 'Assign Heads already exist for the selected copied exam.');
        }
        
        // Get all records for the original exam
        $original_exams = MarkHeadAssign::where('exam_id', $request->original_exam)->get();
        
        foreach ($original_exams as $original_exam) {
            // Create new MarkHeadAssign records with copied_exam_id
            MarkHeadAssign::create([
                'exam_id' => $copied_exam_id,
                'student_class_id' => $original_exam->student_class_id,
                'subject_id' => $original_exam->subject_id,
                'head_marks' => $original_exam->head_marks,
            ]);
        }
        return redirect()->back()->with('success', 'Assign Heads successfully created.');
    }

    public function assignSearch(Request $request)
    {
        // dd( $request->all());
        $subjects_assigns = '';
        $filter_mark_heads = '';
        $student_class_id = '';
        $exam_id = '';
        $mark_head = $request->mark_head;
        $student_class = $request->student_class;
        $student_class_id = $request->student_class;
        $exam_id = $request->exam;
        if ($mark_head && $student_class != null) {
            $subjects_assigns = SubjectsAssign::where('student_class_id', $student_class)->get();
            $filter_mark_heads = MarkHead::whereIn('id', $mark_head)->get();
        }
        $assignMarksHead = MarkHeadAssign::with('studentClass', 'subject')->where('exam_id', $exam_id)->where('student_class_id', $student_class_id)->get()->groupBy('student_class_id');
        $exams = Exam::orderBy('id', 'desc')->select('id','exam_name','year')->get();
        $studentClasses = StudentClass::pluck('class_name', 'id');
        $mark_heads = MarkHead::all();
        $marks_heads = MarkHead::pluck('head_name', 'id')->toArray();

        return view("pages.result.mark_head_assign.create", compact('subjects_assigns', 'filter_mark_heads', 'exam_id', 'student_class_id', 'studentClasses', 'mark_heads', 'exams', 'mark_head', 'marks_heads', 'assignMarksHead'));
    }


    public function assignStore(Request $request)
    {
        $subjects = $request->subject_id;
        $student_class_id = $request->student_class_id;
        $exam_id = $request->exam_id;

        if(empty($exam_id)){
            return redirect()->back()->with('warning', 'Please select exam');
        }

        foreach ($subjects as $index => $subject) {
            $head_id = $request->head_id[$subject];
            $marks = $request->marks[$subject];
            $marks_head_array = array();

            for ($i = 0; $i < count($head_id); $i++) {
                $marks_head_array[$head_id[$i]] = $marks[$i];
            }
            $markHeadAssign = new MarkHeadAssign();
            $markHeadAssign->exam_id = $exam_id;
            $markHeadAssign->student_class_id = $student_class_id;
            $markHeadAssign->subject_id = $subject;
            $markHeadAssign->head_marks = json_encode($marks_head_array);
            $markHeadAssign->save();
        }
        return redirect(route('markHeadAssign.index'))->with('message', 'Mark Head Successfully Assigned');
    }

    public function assignEdit($student_class_id, $exam_id)
    {

        $assignMarksHead = MarkHeadAssign::with('studentClass', 'subject')->where('exam_id', $exam_id)->where('student_class_id', $student_class_id)->get()->groupBy('student_class_id');
        $singleMarksHead = $assignMarksHead[$student_class_id]->first();

        $subjects_assigns = '';
        $filter_mark_heads = '';
        $mark_head = [];
        $head_marks_array = json_decode($singleMarksHead->head_marks, true);

        $mark_head = array_keys($head_marks_array);

        if ($mark_head && $student_class_id != null) {
            $subjects_assigns = SubjectsAssign::where('student_class_id', $student_class_id)->get();
            $filter_mark_heads = [];
        }

        $exams = Exam::orderBy('id', 'desc')->select('id','exam_name','year')->get();
        $studentClasses = StudentClass::pluck('class_name', 'id');
        $mark_heads = MarkHead::all();
        $marks_heads = MarkHead::pluck('head_name', 'id')->toArray();
        return view("pages.result.mark_head_assign.edit", compact('subjects_assigns', 'filter_mark_heads', 'exam_id', 'student_class_id', 'studentClasses', 'mark_heads', 'exams', 'mark_head', 'marks_heads', 'assignMarksHead'));
    }

    public function assignCopy($student_class_id, $exam_id)
    {

        $assignMarksHead = MarkHeadAssign::with('studentClass', 'subject')->where('exam_id', $exam_id)->where('student_class_id', $student_class_id)->get()->groupBy('student_class_id');
        $singleMarksHead = $assignMarksHead[$student_class_id]->first();

        $subjects_assigns = '';
        $filter_mark_heads = '';
        $mark_head = [];
        $head_marks_array = json_decode($singleMarksHead->head_marks, true);

        $mark_head = array_keys($head_marks_array);


        if ($mark_head && $student_class_id != null) {
            $subjects_assigns = SubjectsAssign::where('student_class_id', $student_class_id)->get();
            $filter_mark_heads = [];
        }

        $exam = Exam::pluck('exam_name', 'id');
        $studentClasses = StudentClass::pluck('class_name', 'id');
        $mark_heads = MarkHead::all();
        $marks_heads = MarkHead::pluck('head_name', 'id')->toArray();

        return view("pages.result.mark_head_assign.copy", compact('subjects_assigns', 'filter_mark_heads', 'exam_id', 'student_class_id', 'studentClasses', 'mark_heads', 'exam', 'mark_head', 'marks_heads', 'assignMarksHead'));
    }

    public function assignUpdate(Request $request, $student_class_id)
    {

        $exam_id = $request->exam_id;
        $subjects = $request->subject_id;
        MarkHeadAssign::where('exam_id', $exam_id)->where('student_class_id', $student_class_id)->delete();

        foreach ($subjects as $index => $subject) {

            $head_id = $request->head_id[$subject];
            $marks = $request->marks[$subject];
            $marks_head_array = array();

            for ($i = 0; $i < count($head_id); $i++) {
                $marks_head_array[$head_id[$i]] = $marks[$i];
            }

            $markHeadAssign = new MarkHeadAssign();
            $markHeadAssign->exam_id = $request->exam_id;
            $markHeadAssign->student_class_id = $student_class_id;
            $markHeadAssign->subject_id = $subject;
            $markHeadAssign->head_marks = json_encode($marks_head_array);
            $markHeadAssign->save();

            // $markHeadAssign = [
            //     'exam_id' => $request->exam_id,
            //     'student_class_id' => $student_class_id,
            //     'subject_id' => $subject,
            //     'head_marks' => json_encode($marks_head_array),
            // ];

            // MarkHeadAssign::where('exam_id', $request->exam_id)->where('student_class_id', $student_class_id)->where('subject_id', $subject)->update($markHeadAssign);
        }

        return redirect(route('markHeadAssign.index'))->with('message', 'Mark Head Successfully Updated');
    }

    public function assignSearchUpdate(Request $request)
    {
        $mark_head = $request->mark_head;
        $student_class_id = $request->student_class;
        $exam_id = $request->exam;

        $subjects_assigns = '';
        $filter_mark_heads = '';


        if ($mark_head && $student_class_id != null) {
            $subjects_assigns = SubjectsAssign::where('student_class_id', $student_class_id)->get();
            $filter_mark_heads = MarkHead::whereIn('id', $mark_head)->get();
        }

        $assignMarksHead = MarkHeadAssign::with('studentClass', 'subject')
            ->where([['exam_id', $exam_id], ['student_class_id', $student_class_id]])
            ->get()
            ->groupBy('student_class_id');

        $exams = Exam::orderBy('id', 'desc')->select('id','exam_name','year')->get();
        $studentClasses = StudentClass::pluck('class_name', 'id');
        $mark_heads = MarkHead::all();
        $marks_heads = MarkHead::pluck('head_name', 'id')->toArray();

        return view("pages.result.mark_head_assign.edit", compact(
            'subjects_assigns',
            'filter_mark_heads',
            'exam_id',
            'student_class_id',
            'studentClasses',
            'mark_heads',
            'exams',
            'mark_head',
            'marks_heads',
            'assignMarksHead'
        ));
    }


    public function assignDestroy($student_class_id, $exam_id)
    {
        MarkHeadAssign::where('exam_id', $exam_id)->where('student_class_id', $student_class_id)->delete();
        return redirect()->route('markHeadAssign.index')->with('success', 'Assign Head Mark deleted successfully.');
    }
}
