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

if(!empty($_POST['name']) && !empty($_POST['class_numeric'])
    && !empty($_POST['teacher_name'])){
    $name = $_POST['name'];
    $class_numeric = $_POST['class_numeric'];
    $teacher_name= $_POST['teacher_name'];
    $class_id = $_POST['class_id'];

    //check if class already exists 

    $sql = "SELECT * FROM classes WHERE name = :name";
    $conn->query($sql);
    $conn->bind(":name", $name);

    if($conn->rowCount() > 0){
      
      echo "<script>
            toastr['error']('The class you are updating already exists');
      </script>";
      return false;

    }else{
              //process  updating  of data into database
    $sql = "UPDATE classes SET name=:name, class_numeric =:class_numeric, teacher_name =:teacher_name WHERE id =:class_id";
    $conn->query($sql);
    $conn->bind(':name', $name);
    $conn->bind(':class_numeric', $class_numeric);
    $conn->bind(':teacher_name', $teacher_name);
     $conn->bind(':class_id', $class_id);

        $send = $conn->execute();
        if ($send) {

               //update results table if the class already exists with results added already 

            $sql = "UPDATE results SET class =:name WHERE class =:name";
            $conn->query($sql);
            $conn->bind(":name", $name);

            if($conn->execute()){
                   echo "<script>
                 toastr['success']('Class name and other relevant details updated successfully.');
          </script><meta http-equiv='refresh' content='4; class'>";

            }else{
                //update only the class nam, no results exists yet for the renamed class 

                   echo "<script>
                 toastr['success']('Class name updated successfully.');
          </script><meta http-equiv='refresh' content='4; class'>";
            }
            
        } else {

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

        }
    }

  
   


}else{

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



