<?php
include("../../db.php");
header('Content-Type: application/json');

$status = 0;
$msg = "Unable to execute operation at this time..! Please retry later";

if (isset($_POST['json'])) {

    $raw_json   = $_POST['json'];
    $post_array = json_decode($raw_json, true);

    $session       = $post_array['session'];
    $added_by      = $post_array['added_by'];
    $selected_date = $post_array['selected_date'];
    $data          = $post_array['student_record'];

    $attendance_table = "attandenc";
    $current_month    = date("F");
    $school_id        = 1;
    $user_type        = 2; // 2 For Student

    /////////////////////////////////////

    foreach ($data as $row) {

        $att_status         = $row['att_status'];
        $updated_att_status = $row['updated_att_status'];

        if ($att_status == 0) {

            $late_flag = "";
            if ($updated_att_status == 2) $late_flag = "LATE";

            $aryData = array("idno" => $row['student_id'], "school_id" => $school_id, "session" => $session, "date" => $selected_date, "month" => $current_month,
                             "status" => 0, "added_by" => $added_by, "type" => $user_type, "late_flag" => $late_flag);

            $existing_row_check = $db->getVal("select id from $attendance_table where idno='$row[student_id]' and date='$selected_date' and type='$user_type' and status='0' ");

            if (empty($existing_row_check)) $db->insertAry($attendance_table, $aryData);

        } elseif ($att_status == 1) {

            if ($updated_att_status == 0) {
                //delete row
                deleteRecordById($db, $attendance_table, $row['att_id']);
            } elseif ($updated_att_status == 2) {
                //update late flag
                updateRecordById($db, $attendance_table, $row['att_id'], "LATE");
            }

        } elseif ($att_status == 2) {
            if ($updated_att_status == 0) {
                //delete row
                deleteRecordById($db, $attendance_table, $row['att_id']);
            } elseif ($updated_att_status == 1) {
                //clear late flag
                updateRecordById($db, $attendance_table, $row['att_id'], '');
            }
        }

    }

    $status = 1;
    $msg = 'Record updated successfully';

}

echo json_encode(array('status' => $status, 'msg' => $msg));

///////////////////

function deleteRecordById($db, $attendance_table, $row_id){
    $db->delete($attendance_table, " where id = '$row_id' ");
}

function updateRecordById($db, $attendance_table, $row_id, $late_flag){
    $db->updateAry($attendance_table, array("late_flag" => $late_flag), "where id = '$row_id' ");
}
