<?php
session_start();
if(isset($_POST['class_id']) && isset($_POST['class_id']))
{
    $teacher_id=$_SESSION['teacher']['id'];
    $session_id=htmlentities($_POST['session_id']);
    $class_id=htmlentities($_POST['class_id']);
    $time=time();
    include '../manage/function.php';
    include '../classes/classroom_class.php';
    include '../classes/class_subjects_class.php';
    include '../classes/assessment_class.php';
    include '../classes/students_class.php';
    include '../classes/result_class.php';
    
    $assessment=new Assessment("../manage/connection.php");
    $classroom=new ClassRoom("../manage/connection.php");
    $classSubject=new ClassSubject("../manage/connection.php");
    $dstudent=new Student("../manage/connection.php");
    $result=new Result("../manage/connection.php");
    
    $total_subjects=count($classSubject->getAllClassSubjects($class_id));
    $added_count=0;
    $update_count=0;
    $students_list=array();
    
    // i fetched students by session and class in order to get students that participated, instead of getting student from students table with class id, student may be promoted and results needs to be generated and it will generate with new students

    foreach($dstudent->studBySession($session_id, $class_id) as $studentInfo)
    {
        $total_marks=$assessment->sumAssessment($studentInfo['id'], $session_id, $class_id)['total'];
        $exam=$assessment->sumAssessment($studentInfo['id'], $session_id, $class_id)['exam'];
        $ca1=$assessment->sumAssessment($studentInfo['id'], $session_id, $class_id)['ca_1'];
        $ca2=$assessment->sumAssessment($studentInfo['id'], $session_id, $class_id)['ca_2'];
        $studInfo=$dstudent->getStudent($studentInfo['id']);
        $stud=$studInfo['firstname'].' '.$studInfo['lastname'];
    
        array_push($students_list, array("student_id"=>$studentInfo['id'], "student_name"=>$stud,"session_id"=>$session_id,
        "class_id"=>$class_id, "ca_1"=>$ca1, "ca_2"=>$ca2, "exam"=>$exam, "total_marks"=>$total_marks));
     
    
    }
    // Sort students
    usort($students_list, mySort('total_marks'));
    

    
    $all_marks=array();//
    $other_almrk=array(0=>1);

    // 
    $dprevious=0;
    foreach($students_list as $studentList)
    {
        $dprevious=$studentList['total_marks'];//assigning new marks to previous marks  
        array_push($all_marks, $studentList['total_marks']); //push student marks to all_marks for existing counting
        
        $exist_count=0;// declear existance
        
        foreach($all_marks as $almrk)
        {
            // if previous marks is equal to the current mark, increse the existing count found
            if($almrk==$dprevious)
            {
                $exist_count++;
            }
            $other_almrk[$studentList['total_marks']]=$exist_count;// replace value of previous existing_count of  key(marks) with new existing_count with the same key(marks)
        }
    }

    // Calculate position and add to database
    $position=0;
    $previousMark=0;
    foreach($students_list as $student)
    {
        
        // if($previousMark!=$student['total_marks'])
        // {
        //     $position++;
        // }
        // $previousMark=$student['total_marks'];
        if($previousMark!=$student['total_marks'])
        {
            $position+=($other_almrk[$previousMark]);//Adding position based on prevoise marks exitance count in order to skip
        }
        $previousMark=$student['total_marks'];

        // calculate average
        $class_average=($student['total_marks']/$total_subjects);
        $class_grade='';
        // Check if result exist on database, update, else add new
        // Add to storage
        if($result->findStudentResult($student['student_id'], $session_id, $class_id))
        {
            // Update
            if($result->updateResult($student['student_id'], $session_id, $class_id, $student['ca_1'], $student['ca_2'], $student['exam'], $student['total_marks'], $position, $class_average))
            {
                // Updated
                $update_count++;
            }
        }
        else
        {
            // add new
            if($result->addResult($student['student_id'], $session_id, $class_id, 'teacher', $teacher_id, $student['ca_1'], $student['ca_2'], $student['exam'], $student['total_marks'], $position, $class_grade, $class_average, $time))
            {
                // Added
                $added_count++;
            }
        }
        // echo '<div> '.$student['student_name'].' '.$student['total_marks'].' POSITION '.$position.'</div>';
    }

    if($added_count!=0 || $update_count!=0)
    {
        // Clear grades Firstname
        $result->clearStudentResult($student['student_id'], $session_id, $class_id);

        $group_count=4;
        $allres=$dstudent->allResults($session_id, $class_id);
        $group_count=count($allres)>4?round(count($allres)/4):count($allres);
        $group_a=array("start"=>1, "stop"=>$group_count);//1 - 4
        $group_b=array("start"=>$group_count, "stop"=>$group_count*2); //4 - 8
        $group_c=array("start"=>$group_count*2, "stop"=>$group_count*3); // 8 - 12
        $group_d=array("start"=>$group_count*3, "stop"=>$group_count*4); // 12 - 16
        
        $gn=1;
        foreach($allres as $stud_grade)
        {
            $grade_group="";
            if($gn>=$group_a['start'] && $gn<=$group_a['stop'])
            {
                $grade_group="A";
            }
            elseif($gn>$group_b['start'] && $gn<=$group_b['stop'])
            {
                $grade_group="B";
            }
            elseif($gn>$group_c['start'] && $gn<=$group_c['stop'])
            {
                $grade_group="C";
            }
            else//if($gn>$group_d['start'] && $gn<=$group_d['stop'])
            {
                $grade_group="D";
            }
            $gn++;

            // Check existing Grade
            $res_rade=$result->findStudentGrades($session_id, $class_id, $grade_group);
            // Update Students Grade
            $updateGrade=$result->updateStudentGrade($stud_grade['student_id'], $stud_grade['total'], $session_id, $class_id, $res_rade);//stud_grad['Todal'] added in order to compere current total with previous totl adn set grade the same
            
            // echo $stud_grade['student_id']." $grade_group<br/>";
        }
        echo 'Result Generated';
        
    }
    else
    {
        echo 'Could Not Generate Result';
    }
}

function mySort($key)
{
    return function($a,$b) use ($key)
    {
        return strnatcmp($b[$key], $a[$key]);
    };
}
?>