<?php
include("../../db.php");
//header("Access-Control-Allow-Origin: * ");
header('Content-Type: application/json');

$pid = $_GET['paper_id'];
$uid = $_GET['uid'];

$array = array();
$status = 0;

$correct = 0;
$wrong = 0;
$skipped = 0;
$ansArray = array();

$result = $db->getRow("select * from assignment_attempt_paper where pid='$pid' and uid='$uid' ");
if (count($result) > 0) {
    $status = 1;

    $allquestions = $db->getRows("select * from assignment_questions where paper_id='$pid' ");

    foreach ($allquestions as $question) {

        $correctans = json_decode($question['answer']);
        $questatus = "";
        $att_question = $db->getRow("select * from assignment_attempt_question where att_paper_id='$result[id]' and pid='$pid' and uid='$uid' and qid='$question[id]' ");
        if (count($att_question) > 0) {
            $questatus = "attempted";
        } else {
            $questatus = "not attempted";
        }

        $allimages = $db->getRows("SELECT * from assignment_question_files where question_id='$question[id]' ");
        $imageArray = array();

        foreach ($allimages as $image) {
            if ($image[image_type] == "question_image") {
                $imageArray [] = "$_SERVER[HTTP_HOST]/uploads/questionimages/$image[name]";
            }
        }

        $uploadimages = $db->getRows("select * from assignment_attempt_subj_files where uid='$uid' and pid='$pid' and qid='$question[id]' ");
        $imgAry = array();
        foreach ($uploadimages as $img) {
            // $imgAry []= $img['name'];

            $imgAry [] = "https://" . "$_SERVER[HTTP_HOST]/uploads/subjectiveexam/$img[name]";

        }

        if ($att_question[answer] != '') {
            $givenans = $att_question[answer];
        } else {
            $givenans = '';
        }

        $obtMark = $att_question['mark_obtained'];
        if ($obtMark == null) {
            $obtMark = "";
        }

        array_push($ansArray, ["qid" => "$question[id]", "qtype" => $question[qtype],
            "question" => "$question[question]", "q_image" => $imageArray, "solution" => "$question[solution]", "given_ans" => $givenans,
            "upload_images" => $imgAry, "quemark" => $question["quemark"], "obt_mark" => $obtMark, "status" => $questatus]);

    }

}

$total_sum = $db->getVal("SELECT SUM(mark_obtained) FROM assignment_attempt_question WHERE uid = '$uid' AND pid = '$pid'");

$max_mark = $db->getVal("SELECT SUM(quemark) FROM assignment_questions WHERE paper_id = '$pid'");


$array['status'] = $status;
$array['total'] = count($allquestions);
$array['correct'] = $correct;
$array['wrong'] = $wrong;
$array['skipped'] = $skipped;
$array['time_take'] = $result[time_taken];
$array['speed'] = $result[speed];
$array['ans_keys'] = $ansArray;

$array['mark_obt'] = $total_sum;
$array['max_mark'] = $max_mark;

echo json_encode($array);

?>