<?php
require_once("../../../../general/TaquaLB/Elements/Elements.php");
$configdir = "../../../../../../".urldecode($_POST['SubDir']);
require_once("../../../../general/config.php");
if(!isset($_POST['ExmID']))exit("#Invalid Exam/Test Selected");
//get the exam details
$exmdet = $dbo->SelectFirstRow("cbt_exam_tb","","ExamID=".$_POST['ExmID']);
if(!is_array($exmdet))exit("#Reading Exam/Test Failed");

$deftobjarr = [
    ["Label"=>"Option 1","Body"=>"","IsCorrect"=>true],
    ["Label"=>"Option 1","Body"=>"","IsCorrect"=>false],
    ["Label"=>"Option 1","Body"=>"","IsCorrect"=>false],
    ["Label"=>"Option 1","Body"=>"","IsCorrect"=>false],
    ["Label"=>"Option 1","Body"=>"","IsCorrect"=>false],
    ["Label"=>"Option 1","Body"=>"","IsCorrect"=>false]
];
//check if new loading
if(isset($_POST['IsNew']) && $_POST['IsNew'] == "true"){ //if new question creation
    
  $inst = $dbo->InsertID2("cbt_questions_tb",["Mark"=>1,"ExmID"=>$_POST['ExmID'],"QBody"=>"","QAnswerType"=>"OBJECTIVE","QAnswerBody"=>json_encode($deftobjarr)]);
  if(is_numeric($inst)){
    //$_POST['QNum'] = $_POST['NewQ'];
  }else{
    exit("#Adding Question Failed - ".$inst." ".$_POST['ExmID']);
    //check if new loading
  }
}
$msg = "";
$isdelete = false;
//if to delete question
if(isset($_POST['DeleteQID']) && (int)$_POST['DeleteQID'] > 0){
    $del = $dbo->Delete("cbt_questions_tb","ID=".$_POST['DeleteQID']);
    if(is_array($del)){
        $msg = "Question Deleted Successfully";
        $isdelete = true;
    }else{
        exit("#Delete Operation Failed");   
    }
}
$qusnum = isset($_POST['QNum']) && (int)$_POST['QNum'] > 0?(int)$_POST['QNum']:1;
$limoffset = $qusnum - 1;
//get ExmQuestions
$qusts = $dbo->Query("SELECT SQL_CALC_FOUND_ROWS * FROM cbt_questions_tb WHERE ExmID=".$_POST['ExmID']." LIMIT $limoffset,1");
if(!is_array($qusts) || $qusts[1] < 1){
    if(!$isdelete){
        // exit("#No Question Found, Click New Button to Add Question to Exam/Test");
        $msg = "*No Question in <b>{$exmdet['ExamName']}</b><br/> Click <b>New</b> Button to Add Question";
        //$msg = "";
    }
    exit(json_encode(["ID"=>0,"Mark"=>"","QBody"=>"","QAnswerType"=>"OBJECTIVE","QAnswerBody"=>json_encode($deftobjarr),"Message"=>$msg,"Total"=>0,"Num"=>0,"ExamAbbr"=>$exmdet['ExamAbbr'],"ExamName"=>$exmdet['ExamName'],"ExamID"=>$_POST['ExmID']]));
    
}
$rsttot = $dbo->Query("SELECT FOUND_ROWS()");
$rtot = $rsttot[0]->fetch_array();
$alltot = (int)$rtot[0];
//get the question details
$questDet = $qusts[0]->fetch_assoc();
$questDet['Total'] = $alltot;
$questDet['Num'] = $qusnum;
$questDet['Message'] = $msg;
$questDet['ExamAbbr'] =$exmdet['ExamAbbr'];
$questDet['ExamName'] =$exmdet['ExamName'];
$questDet['ExamID'] =$_POST['ExmID'];
echo json_encode($questDet);
?>