<?php
session_start();
include 'includes/database.php';
include 'includes/functions.php';
$conn= new Functions();

if(!empty($_POST['class']) && !empty($_POST['term'])
    && !empty($_POST['exam'])){
    $class = $_POST['class'];
    $term= $_POST['term'];
    $first_ca= $_POST['1st_ca'];
    $second_ca= $_POST['2nd_ca'];
    $third_ca= $_POST['3rd_ca'];
    $exam= $_POST['exam'];
    $mark_id = $_POST['mark_id'];


    //check if first_ca, second_ca and exam are more than 100 or less than 100

    $marks_total = $first_ca + $second_ca +$third_ca + $exam;

    if($marks_total > 100){
        echo "<script>
                   toastr['error']('1st CA, 2nd CA, 3rd CA and Exam total can\'t exceed 100');
                 </script>";
        return false;
    }elseif($marks_total < 100){
        echo "<script>
               toastr['error']('1st CA, 2nd CA, 3rd CA  and Exam total must add up to 100');
             </script>";
        return false;
    }

    //check if class already exists


    $sql = "SELECT * FROM mark_setting WHERE class=:class AND exam =:exam AND term =:term AND first_ca =:first_ca
            AND second_ca =:second_ca  AND third_ca =:third_ca  AND exam =:exam AND id != :mark_id";
    $conn->query($sql);
    $conn->bind(':class', $class);
    $conn->bind(':exam', $exam);
    $conn->bind(':term', $term);
    $conn->bind(':first_ca', $first_ca);
    $conn->bind(':second_ca', $second_ca);
    $conn->bind(':third_ca', $third_ca);
    $conn->bind(':mark_id', $mark_id);

    if($conn->rowCount() > 0){

        echo "<script>
            toastr['error']('This marks details already exists');
      </script>";
        return false;

    }else{
        //process  updating  of data into database
        $sql = "UPDATE mark_setting SET class=:class, term =:term, exam =:exam, first_ca =:first_ca,
         second_ca =:second_ca, third_ca =:third_ca, exam =:exam WHERE id =:mark_id";
        $conn->query($sql);
        $conn->bind(':class', $class);
        $conn->bind(':exam', $exam);
        $conn->bind(':term', $term);
        $conn->bind(':first_ca', $first_ca);
        $conn->bind(':second_ca', $second_ca);
        $conn->bind(':third_ca', $third_ca);
        $conn->bind(':mark_id', $mark_id);


        $send = $conn->execute();
        if ($send) {
            echo "<script>
                 toastr['success']('Marks Setting updated successfully.');
          </script><meta http-equiv='refresh' content='4; mark-setting'>";

        } else {

            echo "<script>
                 toastr['error']('An error occurred while updating data');
        </script><meta http-equiv='refresh' content='4; mark-setting'>";

        }
    }

}else{

    echo "<script>
                 toastr['error']('Fields marked (*) are required.');
        </script>";
}



