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

    $jsondata = $_POST['json'];

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

    $decode = json_decode($jsondata, true);

    $uid = $decode['uid'];
    $pid = $decode['paper_id'];
    $time_taken = $decode['time_taken'];
    $speed = $decode['speed'];
    $site_name = $decode['site_name'];
    $allanswer = $decode['allanswers'];


    $rowCount = $db->getRows("SELECT * FROM assignment_attempt_paper WHERE pid = '$pid' AND uid = '$uid'");
    if (count($rowCount) > 0){
        $array['status'] = $status;
        $array['msg'] = 'Paper is already submitted';

        echo json_encode($array);
        return;
    }


    $paperArray = array(
        "pid" => "$pid",
        "uid" => "$uid",
        "time_taken" => "$time_taken",
        "speed" => "$speed",
        "paper_mode" => "mobile",
        "site_name" => "$site_name"
        );

    if($pid != "" && $uid !=""){
        $flgIn=$db->insertAry("assignment_attempt_paper",$paperArray);
    }

    if($flgIn > 0){
        foreach($allanswer as $answer){

            $ansArray = array(
                "pid" => "$pid",
                "uid" => "$uid",
                "qid" => "$answer[qid]",
                "att_paper_id" => "$flgIn",
                "answer" => "$answer[answer]",
                "qtype" => "$answer[qtype]",
                "paper_mode" => "mobile",
                "site_name" => "$site_name"
                );
                
                $ansIn =$db->insertAry("assignment_attempt_question",$ansArray);
                
                
                $ans_img = $answer['ans_img'];
                
                foreach($ans_img as $img){
                    
                    $imgAry = array(
                            "uid" => "$uid",
                            "pid" => "$pid",
                            "qid" => "$answer[qid]",
                            "att_paper_id" => "$flgIn",
                            "att_que_id" => "$ansIn",
                            "name" => "$img",
                            "qtype" => "$answer[qtype]"
                        );

                   $imgIn =$db->insertAry("assignment_attempt_subj_files", $imgAry);

                }

        }

        $status = 1;
        $msg = 'Paper successfully submitted.';
    }
    else {
        $msg = "Paper not submitted. Something went wrong.";
    }

    $array['status'] = $status;
    $array['msg'] = $msg;

echo json_encode($array);

?>