<?php
session_start();
if(isset($_SESSION['teacher']))
{
    
    $teacher_id=$_SESSION['teacher']['id'];
    include '../classes/attendance_class.php';
    include '../classes/classroom_class.php';
    include '../classes/subjects_class.php';
    include '../classes/class_subjects_class.php';
    include '../classes/teachers.php';
    include "../manage/function.php";


    $classroom=new ClassRoom("../manage/connection.php");
    $subject=new Subject("../manage/connection.php");
    $classSubject=new ClassSubject("../manage/connection.php");
    $teachers=new Teachers("../manage/connection.php");
    $attendance=new Attendance("../manage/connection.php");
    $class_id=htmlentities($_POST['class_id']);

    $session=currentSession($conn="../manage/connection.php");
    $sessionId=$session['id'];
    $date=date('Y-m-d');
    if(isset($_POST['attendance_date']))
    {
        $date=$_POST['attendance_date'];
    }
    $record_count=0;
    foreach($classroom->getAllClassStudents($class_id) as $cStudent)
    {
        $reason="";
        if(isset($_POST[$cStudent['id'].'_attendance']))
        {
            $selected_student=$cStudent['id'];
            $attendance_status=$_POST[$cStudent['id'].'_attendance'];
            if(isset($_POST['reason_'.$cStudent['id']]))
            {
                $reason=$_POST['reason_'.$cStudent['id']]; 
            }

            if(!$attendance->findAttendance($cStudent['id'], $date))
            {
                // Add new Attendance
                if($attendance->addAttendance($cStudent['id'], 'teacher', $teacher_id, $sessionId, $attendance_status, $reason, $date, time()))
                {
                    $record_count++;
                }
            }
            else
            {
                // Update Attendance
                if($attendance->updateAttendance($cStudent['id'], $attendance_status, $reason, $date))
                {
                    $record_count++;   
                }
            }
        }
        
    }
    
    echo "$record_count Recorded";
}
else
{
    echo 'Login as a teacher';
}
?>