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

$status = 0;
$msg = 'Unable to save data. Please try again later..!';

$jsonData  = $_POST['json'];
$arrayData = json_decode($jsonData, true);

$jsonDataAnswer  = $_POST['json_answers'];
$arrayDataAnswer = json_decode($jsonDataAnswer, true);

$class   = $arrayData['class'];
$subject = $arrayData['subject'];
$type    = $arrayData['type'];
$idno    = $arrayData['idno'];
$total   = $arrayData['total'];
$obtain  = $arrayData['obtain'];
$session = $arrayData['session'];
$addedBy = $arrayData['added_by'];

$termMark = $db->getVal("SELECT total FROM examterm WHERE name = '$type' AND subject = '$subject' AND class = '$class' AND session = '$session' ");

if ($termMark == $total){

    $examRecordId = $db->getVal("SELECT id FROM exammarks WHERE subject = '$subject' AND type = '$type' AND idno = '$idno' AND session = '$session' AND is_omr = '1'");

    $dbArray = array("class" => $class, "subject" => $subject, "type" => $type, "idno" => $idno, "total" => $total, "obtain" => $obtain,
                     "session" => $session, "school_id" => 1, "added_by" => $addedBy, "is_omr" => 1);

    if ($examRecordId > 0){
        $recordUpdateFlag = false;
        $flgUp = $db->updateAry("exammarks", $dbArray,"where id = '$examRecordId' ");
        if ($flgUp){
            $recordUpdateFlag = true;
        }

        foreach ($arrayDataAnswer as $rowItem) {
            $isUpdated = $db->updateAry("omr_attempt_question", array("answer_given" => $rowItem['answer']), "where exammarks_id = '$examRecordId' AND omr_question_id = '$rowItem[id]'");
            if ($isUpdated){
                $recordUpdateFlag = true;
            }
        }

        if ($recordUpdateFlag){
            $status = 1;
            $msg = "Record updated successfully";
        }else{
            $msg = "Record not updated due to data is same..! Please make changes in data and try again";
        }
    }else{
        $sqlResponse = $db->insertAry("exammarks", $dbArray);
        if ($sqlResponse > 0) {
            $status = 1;
            $msg = "Record inserted successfully";

            foreach ($arrayDataAnswer as $rowItem) {
                $db->insertAry("omr_attempt_question", array("exammarks_id" => $sqlResponse, "omr_question_id" => $rowItem['id'], "question_no" => $rowItem['question'],
                                                             "answer_given" => $rowItem['answer'], "idno" => $idno, "session" => $session, "added_by" => $addedBy));
            }
        }
    }

}else{
    $msg = 'Exam term mark does not match OMR paper mark..! Please rectify this issue and try again';
}

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