<?php
session_start();
if(isset($_SESSION['teacher'])){
$username = $_SESSION['teacher'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">


    <?php include '../admin/includes/styles.php'; ?>
    <title> Add a mark |  <?php echo $school_name; ?> </title>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php
    include "includes/sidebar.php";
    $sql = "SELECT * FROM teachers WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":username", $username);

    $result = $conn->fetchSingle();
    $teacher_name = $result->name;
    ?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">Add a mark</h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->teacher_url(); ?>">Home</a></li>
                            <li class="breadcrumb-item active">Add a mark</li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">

                <div class="row">
                    <div class="col-md-12">
                        <div class="callout callout-success" style="margin-top: 30px;">
                            <p>Note: You can only add marks for the subject and classes you are teaching</p>
                        </div>
                        <div class="card card-info">
                            <div class="card-header">
                                <h3 class="card-title"><i class="fa fa-flask"></i> Mark</h3>
                            </div>
                            <!-- /.card-header -->
                            <!-- form start -->
                            <form class="form-horizontal" method="post" id="mark-add">
                                <div class="card-body">
                                    <div class="form-row">
                                        <div class="col-md-3">
                                            <label for="class"> Class <span class="text-danger">*</span></label>
                                            <select name="class" id="classID" class="form-control select2 myclass" required data-parsley-trigger="keyup" style="width: 100%;">
                                                <option value="">Select Class</option>
                                                <?php
                                                //fetch all teachers information
                                                $sql = "SELECT * FROM classes";
                                                $conn->query($sql);
                                                $rowcount = $conn->rowCount();

                                                if($rowcount > 0){
                                                    $result = $conn->fetchMultiple();
                                                    foreach ($result as $class) {
                                                        ?>  <option value="<?php echo $class->id; ?>"><?php echo $class->name; ?></option><?php
                                                    }

                                                }

                                                ?>

                                            </select>
                                        </div>

                                        <div class="col-md-3">
                                            <label for="class"> Exam <span class="text-danger">*</span></label>
                                            <select name="exam" id="exam" class="form-control select2" required data-parsley-trigger="keyup" style="width: 100%;">
                                                <option value="">Select Exam</option>
                                                <?php
                                                //fetch the active term from general settings
                                                $sql = "SELECT active_term FROM general_settings";
                                                $conn->query($sql);
                                                $rowcount = $conn->rowCount();

                                                if($rowcount > 0){
                                                    $active_term = $conn->fetchColumn();
                                                    ?>  <option value="<?php echo $active_term; ?>"><?php echo $active_term; ?></option><?php
                                                }else{
                                                    ?>  <option value="">No active term found</option><?php
                                                }

                                                ?>

                                            </select>
                                        </div>

                                        <div class="col-md-3">
                                            <label for="section"> Section <span class="text-danger">*</span></label>
                                            <select name="section" id="section" class="form-control select2" required data-parsley-trigger="keyup" style="width: 100%;">
                                                <option value="">Select Section</option>


                                            </select>
                                        </div>

                                        <div class="col-md-3">
                                            <label for="subject"> Subject <span class="text-danger">*</span></label>
                                            <select name="subject" id="subject" class="form-control select2" required data-parsley-trigger="keyup" style="width: 100%;">
                                                <option value="">Select Subject</option>


                                            </select>
                                        </div>
                                        <input type="hidden" name="exam_year" value="<?php echo date('Y'); ?>">
                                        <input type="hidden" name="teacher_name" value="<?php echo $teacher_name; ?>">

                                        <div class="col-md-3" style="margin-top: 20px;">
                                            <input type="submit" value="Mark" class="btn btn-success" id="mark">
                                        </div>

                                    </div>


                                </div>
                                <div id="success-msg">
                                </div>
                                <!-- /.card-body -->

                                <!-- /.card-footer -->
                            </form>
                        </div>
                        <!-- /.card -->
                    </div>

                    <div class="col-md-12">
                        <!--                        display mark details-->
                        <div class="card card-info" id="display-details">

                        </div>


                    </div>


                    <!-- /.row (main row) -->
                </div><!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "../admin/includes/footer.php";?>

    <script>
        $(document).ready(function () {
            $('#classID').on('change', function () {
                var classID = $(this).val();
                if(classID){
                    $.ajax({
                        type: 'POST',
                        url: 'fetch_section.php',
                        data: 'classesID=' +classID,//append the classID
                        success: function (html) {
                            $('#section').html(html);
                        }

                    });
                }else{
                    $('#section').html('<option value="">select class  first</option>');
                }
            })
        })
    </script>

    <script>
        $(document).ready(function () {
            $('#classID').on('change', function () {
                var classID = $(this).val();
                if(classID){
                    $.ajax({
                        type: 'POST',
                        url: 'fetch_subject.php',
                        data: 'classesID=' +classID,//append the classID
                        success: function (html) {
                            $('#subject').html(html);
                        }

                    });
                }else{
                    $('#subject').html('<option value="">select class  first</option>');
                }
            })
        })
    </script>

    <script>
        $('#mark-add').parsley();
        $('#mark-add').on('submit', function (event) {
            event.preventDefault();
            if($('#mark-add').parsley().isValid()){
                $.ajax({
                    url: 'fetch-marks-details.php',
                    method: 'POST',
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function () {
                        $('#mark').attr('disabled', 'disabled');
                        $('#mark').val('fetching details, pls wait.....');
                    },
                    success: function (data) {
                        $('#mark-add').parsley().reset();
                        $('#mark').attr('disabled', false);
                        $('#mark').val('Mark');
                        $('#display-details').html(data);
                    }
                });
            }
        });
    </script>

    <script>
        $(document).ready(function(){
            $('.select2').select2();
        })
    </script>
    <script>
        $(document).ready(function(){
            $('#class').select2();

        })

    </script>
    <script>
        $(function () {
            $("#teacher").DataTable({
                "responsive": true, "lengthChange": false, "autoWidth": false,
                "buttons": ["copy", "csv", "pdf", "print", "colvis"]
            }).buttons().container().appendTo('#teacher_wrapper .col-md-6:eq(0)');
            $('#example2').DataTable({
                "paging": true,
                "lengthChange": false,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true
            });
        });
    </script>

    <?php
    if(isset($_POST['submit_result'])){
        $student_class = $_POST['class'];
        $student_exam_score = $_POST['exam_score'];
        $student_first_ca_score = $_POST['first_ca_score'];
        $student_second_ca_score = $_POST['second_ca_score'];
        $student_third_ca_score = $_POST['third_ca_score'];
        $section = $_POST['section'];
        $subject = $_POST['subject'];
        $student_name = $_POST['student_name'];
        $reg_no = $_POST['reg_no'];
        $current_exam = $_POST['exam'];
        $exam_year = $_POST['exam_year'];
        $score_id = $_POST['score_id'];
        $total_scores_obtained = $_POST['total_score'];
        $current_school_section = $_POST['current_school_section'];
        $zero = 0;

        $success_msg1 = '';
        $success_msg2 = '';
        $success_msg3 = '';
        $success_msg4 = '';

        foreach ($student_class as $index=>$result_details){

            //check if details already exist in result table

            $sql = "SELECT * FROM results WHERE name_of_student =:name AND exam =:exam AND class =:class AND subject =:subject AND school_year =:school_year";
            $conn->query($sql);
            $conn->bind(":name", $student_name[$index]);
            $conn->bind(":exam", $current_exam[$index]);
            $conn->bind(":class", $student_class[$index]);
            $conn->bind(":subject", $subject[$index]);
            $conn->bind(":school_year", $exam_year[$index]);

            $rowcount = $conn->rowCount();

            //check if query succeeds

            if($rowcount > 0){
                $db_result = $conn->fetchSingle();
                //update records

                $sql = "UPDATE results SET name_of_student =:name, class =:class, exam =:exam, 
                        section =:section, subject =:subject, first_ca =:first_ca,
                        second_ca=:second_ca, third_ca=:third_ca, school_year =:exam_year, 
                        exam_score =:exam_score, current_school_session =:current_school_session WHERE id =:id";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":subject", $subject[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":first_ca", $student_first_ca_score[$index]);
                $conn->bind(":second_ca", $student_second_ca_score[$index]);
                $conn->bind(":third_ca", $student_third_ca_score[$index]);
                $conn->bind(":exam_year", $exam_year[$index]);
                $conn->bind(":exam_score", $student_exam_score[$index]);
                $conn->bind(":id", $score_id[$index]);
                $conn->bind(":current_school_session", $current_school_section[$index]);

                try{
                    $conn->execute();
                    $success_msg1 = "<script>
                         toastr['success']('Exam details updated successfully.');
                         </script>";
                }catch (PDOException $err){
                    $error = $err->getMessage();
                    $success_msg1 = "<script>
                         toastr['error']('$error');
                         </script>";
                }

            }else{
                //no records found, insert records afresh to db
                $sql = "INSERT INTO results(name_of_student, class, exam, section, subject, first_ca, second_ca, third_ca, school_year, exam_score, current_school_session)
                        VALUES(:name, :class, :exam, :section, :subject, :first_ca, :second_ca, :third_ca, :school_year, :exam_score, :current_school_session)";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":subject", $subject[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":first_ca", $student_first_ca_score[$index]);
                $conn->bind(":second_ca", $student_second_ca_score[$index]);
                $conn->bind(":third_ca", $student_third_ca_score[$index]);
                $conn->bind(":school_year", $exam_year[$index]);
                $conn->bind(":exam_score", $student_exam_score[$index]);
                $conn->bind(":current_school_session", $current_school_section[$index]);

                try{
                    $conn->execute();
                    $success_msg1 = "<script>
                         toastr['success']('Exam details added successfully.');
                         </script>";
                }catch (PDOException $err){
                    $error = $err->getMessage();
                    $success_msg1 =  "<script>
                         toastr['error']('$error');
                         </script>";
                }


            }

            //try the second query for student position
            //check if details already exists in student_class_positions table in DB

            $sql = "SELECT * FROM student_class_positions WHERE name =:name AND class=:class 
                           AND section =:section AND exam =:exam AND exam_year =:year AND reg_no =:reg_no";
            $conn->query($sql);
            $conn->bind(":name", $student_name[$index]);
            $conn->bind(":exam", $current_exam[$index]);
            $conn->bind(":class", $student_class[$index]);
            $conn->bind(":section", $section[$index]);
            $conn->bind(":year", $exam_year[$index]);
            $conn->bind(":reg_no", $reg_no[$index]);

            $rowcount2 = $conn->rowCount();

            if($rowcount2 > 0){//start check for position updating
                //something inserted, go ahead and update data

                //fetch first_ca, second_ca, third ca and exam totals
                $sql = "SELECT SUM(first_ca + second_ca + third_ca + exam_score) FROM results WHERE name_of_student = :name  
                        AND second_ca != :zero 
                        AND third_ca != :zero 
                        AND first_ca != :zero 
                       AND exam_score != :zero 
                      AND class=:class AND section =:section 
                     AND school_year =:school_year AND exam =:exam";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":school_year", $exam_year[$index]);
                $conn->bind(":zero", $zero);
                $total_marks_obtained  = $conn->fetchColumn();



                $sql = "UPDATE student_class_positions SET  marks_obtained =:marks_obtained 
                       WHERE name =:name AND class =:class AND exam =:exam
                        AND section =:section AND reg_no =:reg_no AND 
                          exam_year =:exam_year";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":reg_no", $reg_no[$index]);
                $conn->bind(":exam_year", $exam_year[$index]);
                $conn->bind(":marks_obtained", $total_marks_obtained);
                //$conn->bind(":id", $score_id[$index]);

                try{
                    $conn->execute();

                    //try updating student position details
                    $sql = "SELECT * FROM student_class_positions WHERE  class=:class 
                            AND section =:section AND exam =:exam AND exam_year =:year
                            ORDER BY name";
                    $conn->query($sql);
                    $conn->bind(":exam", $current_exam[$index]);
                    $conn->bind(":class", $student_class[$index]);
                    $conn->bind(":section", $section[$index]);
                    $conn->bind(":year", $exam_year[$index]);

                    $scores = $conn->fetchMultiple();
                    $all_scores = [];
                    $row_count = $conn->rowCount();
                    $i = 1;
                    $position = '';
                    foreach ($scores as $details){
                        //$all_scores = $details->marks_obtained;
                        $all_scores[] = $details->marks_obtained;
                    }
                    rsort($all_scores);
                    $rank=1;
                    $prev=$all_scores[0];
                    foreach($all_scores as $number){
                        if($prev!=$number){
                            $prev=$number;
                            $rank++;
                        }
                        $ones = $rank % 10;
                        $tens = floor($rank / 10) % 10;
                        if ($tens == 1) {
                            $suff = "th";
                        } else {
                            switch ($ones) {
                                case 1 : $suff = "st"; break;
                                case 2 : $suff = "nd"; break;
                                case 3 : $suff = "rd"; break;
                                default : $suff = "th";
                            }
                        }
                        $sql = "UPDATE student_class_positions SET  position =:position 
                       WHERE class =:class AND exam =:exam
                        AND section =:section AND 
                          exam_year =:exam_year AND marks_obtained =:marks_obtained";
                        $conn->query($sql);
                        $conn->bind(":exam", $current_exam[$index]);
                        $conn->bind(":class", $student_class[$index]);
                        $conn->bind(":section", $section[$index]);
                        $conn->bind(":exam_year", $exam_year[$index]);
                        $conn->bind(":marks_obtained", $number);
                        $conn->bind(":position", $rank.$suff);
                        $execute = $conn->execute();

                    }

                    $success_msg2 ="<script>
                         toastr['success']('Student\'s scores were updated successfully too.');
                         </script>";
                }catch (PDOException $err){
                    $error = $err->getMessage();
                    $success_msg2 = "<script>
                         toastr['error']('Alert1: $error');
                         </script>";
                }

                //try checking for subject positions updating




            }else{
                //nothing inserted, add afresh
                //fetch first_ca, second_ca, third ca and exam totals
                $sql = "SELECT SUM(first_ca + second_ca + third_ca + exam_score) FROM results WHERE name_of_student = :name  
                        AND second_ca != :zero 
                        AND third_ca != :zero 
                        AND first_ca != :zero 
                       AND exam_score != :zero 
                      AND class=:class AND section =:section 
                     AND school_year =:school_year AND exam =:exam";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":school_year", $exam_year[$index]);
                $conn->bind(":zero", $zero);
                $total_marks_obtained  = $conn->fetchColumn();

                $sql = "INSERT INTO student_class_positions(name, class, exam, section, exam_year, marks_obtained, reg_no)
                        VALUES(:name, :class, :exam, :section, :exam_year, :marks_obtained, :reg_no)";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":reg_no", $reg_no[$index]);
                $conn->bind(":exam_year", $exam_year[$index]);
                $conn->bind(":marks_obtained", $total_marks_obtained);

                try{
                    $conn->execute();
                    //compute students class positions insertion start
                    //try updating student position details
                    $sql = "SELECT * FROM student_class_positions WHERE  class=:class 
                            AND section =:section AND exam =:exam AND exam_year =:year
                            ORDER BY name";
                    $conn->query($sql);
                    $conn->bind(":exam", $current_exam[$index]);
                    $conn->bind(":class", $student_class[$index]);
                    $conn->bind(":section", $section[$index]);
                    $conn->bind(":year", $exam_year[$index]);

                    $scores = $conn->fetchMultiple();
                    $all_scores = [];
                    $row_count = $conn->rowCount();
                    $i = 1;
                    $position = '';
                    foreach ($scores as $details){
                        //$all_scores = $details->marks_obtained;
                        $all_scores[] = $details->marks_obtained;
                    }
                    rsort($all_scores);
                    $rank=1;
                    $prev=$all_scores[0];
                    foreach($all_scores as $number){
                        if($prev!=$number){
                            $prev=$number;
                            $rank++;
                        }
                        $ones = $rank % 10;
                        $tens = floor($rank / 10) % 10;
                        if ($tens == 1) {
                            $suff = "th";
                        } else {
                            switch ($ones) {
                                case 1 : $suff = "st"; break;
                                case 2 : $suff = "nd"; break;
                                case 3 : $suff = "rd"; break;
                                default : $suff = "th";
                            }
                        }
                        $sql = "UPDATE student_class_positions SET  position =:position 
                       WHERE class =:class AND exam =:exam
                        AND section =:section AND 
                          exam_year =:exam_year AND marks_obtained =:marks_obtained";
                        $conn->query($sql);
                        $conn->bind(":exam", $current_exam[$index]);
                        $conn->bind(":class", $student_class[$index]);
                        $conn->bind(":section", $section[$index]);
                        $conn->bind(":exam_year", $exam_year[$index]);
                        $conn->bind(":marks_obtained", $number);
                        $conn->bind(":position", $rank.$suff);
                        $execute = $conn->execute();

                    }

                    $success_msg2 ="<script>
                         toastr['success']('Student\'s scores were updated successfully too.');
                         </script>";
                }catch (PDOException $err){
                    $error = $err->getMessage();
                    $success_msg2 = "<script>
                         toastr['error']('Alert1: $error');
                         </script>";
                }

                //compute students class positions insertion end
            }//end second query for positions updating




            /*
            Start Students Subject Position
            */

            //try the third query for student subject position
            //check if student position already exists in positions table in database
            $sql = "SELECT * FROM subject_positions WHERE subject =:subject AND name =:name AND class =:class AND section =:section AND exam =:exam AND exam_year =:year AND reg_no =:reg_no";
            $conn->query($sql);
            $conn->bind(":name", $student_name[$index]);
            $conn->bind(":exam", $current_exam[$index]);
            $conn->bind(":class", $student_class[$index]);
            $conn->bind(":section", $section[$index]);
            $conn->bind(":subject", $subject[$index]);
            $conn->bind(":year", $exam_year[$index]);
            $conn->bind(":reg_no", $reg_no[$index]);
            $rowCount2 = $conn->rowCount();


            if($rowCount2 > 0){
                //fetch first ca, second ca and exam total

                //fetch first_ca, second_ca and total exam score

                $sql = "SELECT SUM(second_ca + first_ca + third_ca + exam_score) FROM results WHERE name_of_student = :name  
                        AND second_ca != :zero 
                        AND first_ca != :zero 
                        AND third_ca != :zero 
                       AND exam_score != :zero 
                      AND class=:class AND section =:section 
                     AND school_year =:school_year AND exam =:exam AND subject =:subject";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":school_year", $exam_year[$index]);
                $conn->bind(":zero", $zero);
                $conn->bind(":subject", $subject[$index]);
                $total_marks_obtained = $conn->fetchColumn();

                //Update Marks Records
                $sql = "UPDATE subject_positions SET marks_obtained =:marks_obtained 
                         WHERE subject =:subject AND name =:name AND class =:class 
                         AND section =:section AND exam =:exam AND exam_year =:exam_year 
                         AND reg_no =:reg_no";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":subject", $subject[$index]);
                $conn->bind(":reg_no", $reg_no[$index]);
                $conn->bind(":exam_year", $exam_year[$index]);
                $conn->bind(":marks_obtained", $total_marks_obtained);


                try {
                    $conn->execute();

                    //try updating the students subject positions details
                    $sql = "SELECT * FROM subject_positions WHERE subject =:subject 
                            AND class =:class AND section =:section AND exam =:exam 
                            AND exam_year =:year ORDER BY name";
                    $conn->query($sql);
                    $conn->bind(":exam", $current_exam[$index]);
                    $conn->bind(":class", $student_class[$index]);
                    $conn->bind(":section", $section[$index]);
                    $conn->bind(":subject", $subject[$index]);
                    $conn->bind(":year", $exam_year[$index]);

                    $scores = $conn->fetchMultiple();
                    $all_scores = [];
                    $row_count = $conn->rowCount();
                    $i = 1;
                    $position = '';
                    foreach($scores as $details){
                        $all_scores[] = $details->marks_obtained;
                    }
                    rsort($all_scores);
                    $rank=1;
                    $prev=$all_scores[0];
                    foreach($all_scores as $number){
                        if($prev!=$number){
                            $prev=$number;
                            $rank++;
                        }
                        $ones = $rank % 10;
                        $tens = floor($rank / 10) % 10;
                        if ($tens == 1) {
                            $suff = "th";
                        } else {
                            switch ($ones) {
                                case 1 : $suff = "st"; break;
                                case 2 : $suff = "nd"; break;
                                case 3 : $suff = "rd"; break;
                                default: $suff = "th";
                            }
                        }

                        $sql = "UPDATE subject_positions SET position =:position WHERE subject =:subject 
                                AND class =:class AND section =:section AND exam =:exam 
                                AND exam_year =:exam_year AND marks_obtained =:marks_obtained";
                        $conn->query($sql);
                        $conn->bind(":exam", $current_exam[$index]);
                        $conn->bind(":class", $student_class[$index]);
                        $conn->bind(":section", $section[$index]);
                        $conn->bind(":exam_year", $exam_year[$index]);
                        $conn->bind(":subject", $subject[$index]);
                        $conn->bind(":marks_obtained", $number);
                        $conn->bind(":position", $rank.$suff);
                        $execute = $conn->execute();

                    }

                    $success_msg3 = "<script>
    $(function () { //ready
              toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
              toastr.success('Student\'s Subject Positions Updated Successfully');
          });</script>";
                }catch (PDOException $err) {
                    $error = $err->getMessage();
                    $success_msg3 = "<script>
    $(function () { //ready
              toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
              toastr.error('$error');
          });</script>";
                }

            }else{
                //nothing inserted, add subject positions afresh
                //fetch first ca

                //fetch first_ca, second_ca and total exam score

                $sql = "SELECT SUM(second_ca + first_ca + third_ca + exam_score) FROM results WHERE name_of_student = :name  
                        AND second_ca != :zero 
                        AND first_ca != :zero 
                       AND exam_score != :zero 
                       AND third_ca != :zero 
                      AND class=:class AND section =:section 
                     AND school_year =:school_year AND exam =:exam AND subject =:subject";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":school_year", $exam_year[$index]);
                $conn->bind(":zero", $zero);
                $conn->bind(":subject", $subject[$index]);
                $total_marks_obtained = $conn->fetchColumn();

                $sql = "INSERT INTO subject_positions(name, class, exam, section, exam_year, subject, marks_obtained, reg_no)
                        VALUES(:name, :class, :exam, :section, :exam_year, :subject, :marks_obtained, :reg_no)";
                $conn->query($sql);
                $conn->bind(":name", $student_name[$index]);
                $conn->bind(":exam", $current_exam[$index]);
                $conn->bind(":class", $student_class[$index]);
                $conn->bind(":section", $section[$index]);
                $conn->bind(":reg_no", $reg_no[$index]);
                $conn->bind(":subject", $subject[$index]);
                $conn->bind(":exam_year", $exam_year[$index]);
                $conn->bind(":marks_obtained", $total_marks_obtained);

                try{
                    $conn->execute();
                    //try updating the students subject positions details
                    $sql = "SELECT * FROM subject_positions WHERE subject =:subject 
                            AND class =:class AND section =:section AND exam =:exam 
                            AND exam_year =:year ORDER BY name";
                    $conn->query($sql);
                    $conn->bind(":exam", $current_exam[$index]);
                    $conn->bind(":class", $student_class[$index]);
                    $conn->bind(":section", $section[$index]);
                    $conn->bind(":subject", $subject[$index]);
                    $conn->bind(":year", $exam_year[$index]);

                    $scores = $conn->fetchMultiple();
                    $all_scores = [];
                    $row_count = $conn->rowCount();
                    $i = 1;
                    $position = '';
                    foreach($scores as $details){
                        $all_scores[] = $details->marks_obtained;
                    }
                    rsort($all_scores);
                    $rank=1;
                    $prev=$all_scores[0];
                    foreach($all_scores as $number){
                        if($prev!=$number){
                            $prev=$number;
                            $rank++;
                        }
                        $ones = $rank % 10;
                        $tens = floor($rank / 10) % 10;
                        if ($tens == 1) {
                            $suff = "th";
                        } else {
                            switch ($ones) {
                                case 1 : $suff = "st"; break;
                                case 2 : $suff = "nd"; break;
                                case 3 : $suff = "rd"; break;
                                default: $suff = "th";
                            }
                        }

                        $sql = "UPDATE subject_positions SET position =:position WHERE subject =:subject 
                                AND class =:class AND section =:section AND exam =:exam 
                                AND exam_year =:exam_year AND marks_obtained =:marks_obtained";
                        $conn->query($sql);
                        $conn->bind(":exam", $current_exam[$index]);
                        $conn->bind(":class", $student_class[$index]);
                        $conn->bind(":section", $section[$index]);
                        $conn->bind(":exam_year", $exam_year[$index]);
                        $conn->bind(":subject", $subject[$index]);
                        $conn->bind(":marks_obtained", $number);
                        $conn->bind(":position", $rank.$suff);
                        $execute = $conn->execute();

                    }

                    $success_msg4 = "<script>
    $(function () { //ready
              toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
              toastr.success('Student\'s Subject Positions Updated Successfully');
          });</script>";
                }catch (PDOException $err) {
                    $error = $err->getMessage();
                    $success_msg4 = "<script>
    $(function () { //ready
              toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
              toastr.error('$error');
          });</script>";
                }

            }

            /*
            End  Students Subject Position
           */

        }

        echo $success_msg1;
        echo $success_msg2;
        echo $success_msg3;
        echo $success_msg4;
    }

    ?>

    <script>
        if ( window.history.replaceState ) {
            window.history.replaceState( null, null, window.location.href );
        }
    </script>

    <?php
    }else{
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">
        <?php include '../admin/includes/styles.php'; ?>
        <title> Login to continue |  <?php echo $school_name; ?> </title>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6> You need to login to continue </h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $teacher_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>
