2025-05-28 14:26:49 +09:00

360 lines
12 KiB
PHP

<?php
namespace App\Controllers;
use App\Models\UserModel;
use App\Models\WordDetailsModel;
use App\Models\DailyLearningLogModel;
use App\Models\WordTestModel;
class Test extends BaseController
{
public function index()
{
try {
$this->checkLogin(); // 로그인 상태 체크
$userId = $this->session->get('useremail');
$model = new UserModel();
$data['user'] = $model->getUserByEmail($userId);
$testData = $this->question_store();
if(!$testData){
throw new \Exception('데이터 생성에 문제가 발생 했습니다. 재로그인 후 시도하세요.');
}
$question_data = json_decode($testData['question_data'], true);
$this->session->set('question_data', $question_data);
return $this->view('test', $data);
} catch (\Exception $e) {
// 예외 처리
return redirect()->to('/')->with('error', $e->getMessage());
}
}
public function starttest($questionNum=null){
try {
$this->checkLogin(); // 로그인 상태 체크
$question_data = $this->session->get('question_data');
if(empty($questionNum)){
$questionNum=1;
}
$question = $question_data[$questionNum];
$question['totcnt'] = count($question_data);
$question['examples'] =[
'example1' => $question['example1'],
'example2' => $question['example2'],
'example3' => $question['example3'],
'example4' => $question['example4'],
'example5' => $question['example5'],
];
return $this->view('starttest', $question);
} catch (\Exception $e) {
// 예외 처리
return redirect()->to('/test')->with('error', $e->getMessage());
}
}
public function question_store()
{
$this->checkLogin(); // 로그인 상태 체크
$model = new WordTestModel();
$learningLogModel = new DailyLearningLogModel();
$ewWordDetailsModel = new WordDetailsModel();
// Assume user_id and date are provided through the request
$userId = $this->session->get('num');
$date = $this->session->get('todate');
$testMode = $this->session->get('test_mode');
// Fetch word_tests log for the user
$wordtests_log = $model->where('date', $date)
->where('user_id', $userId)
->first();
if (!$wordtests_log) {
// Fetch daily learning log for the user
$log = $learningLogModel->where('user_id', $userId)
->where('todate', $date)
->first();
if (!$log) {
return redirect()->back()->with('error', 'No learning log found for the specified date.');
}
$interruptedKeys = json_decode($log['interrupted_key'], true);
$totalKeys = count($interruptedKeys);
$testKeys = array_slice($interruptedKeys, 0, ceil($totalKeys / 2));
$questions = [];
$questionCount = 0;
foreach ($testKeys as $key) {
$details = $ewWordDetailsModel->where('ew_word_pid', $key)
->where('is_first_row', 1)
->where('mean_num', 1)
->first();
if (!$details) {
$details = $ewWordDetailsModel->where('ew_word_pid', $key)
->where('is_first_row', 1)
->orderBy('id', 'asc')
->limit(1)
->first();
}
if($details) {
if ($testMode == "한영") {
$type = 'kor';
} elseif ($testMode == "영한") {
$type = 'eng';
} else {
$type = $questionCount % 2 == 0 ? 'kor' : 'eng';
}
$question = [
'num' => $questionCount + 1,
'type' => $type,
'key' => $key,
'question' => $type == 'kor' ? $details['mean'] : $details['origin'],
'example1' => $type == 'kor' ? $details['origin'] : $details['mean']
];
$randomExamples = $ewWordDetailsModel->getQuery_rand($key);
$exampleIndex = 2;
foreach ($randomExamples as $example) {
$question['example' . $exampleIndex] = $type == 'kor' ? $example['origin'] : $example['mean'];
$exampleIndex++;
}
// Shuffle the examples
$order = ['example1', 'example2', 'example3', 'example4', 'example5'];
shuffle($order);
$question['order'] = [];
$answer='';
foreach ($order as $index => $example) {
$question['order'][$index + 1] = $example;
if($example == 'example1'){
$answer = $index+1;
}
}
$question['result'] = $answer;
$question['check'] = '';
$questions[$questionCount + 1] = $question;
$questionCount++;
}
$data = [
'date' => $date,
'user_id' => $userId,
'user_email' => $log['user_email'],
'question_data' => json_encode($questions),
'result' => '',
'attempt_count' => 0,
];
}
$model->save($data);
$insertedId = $model->insertID();
$this->session->set('wordtests_no', $insertedId);
return $model->find($insertedId);
}else{
return $wordtests_log;
}
}
public function testanswer(){
$this->checkLogin_ajax(); // 로그인 상태 체크
$answer = $this->request->getVar('answer', FILTER_SANITIZE_STRING);
$thisNum = $this->request->getVar('thisNum', FILTER_SANITIZE_STRING);
if(empty($answer) ||empty($thisNum)){
return 'false';
}
$question_data = $this->session->get('question_data');
$order = $question_data[$thisNum]['order'];
$totalcnt = count($question_data);
$ans = '';
foreach ($order as $key => $val) {
if ($val == 'example1') {
$ans = $key;
}
}
if($ans == $answer){
$result = "true";
}else{
$result = "false";
}
$question_data[$thisNum]['result'] = $result;
$question_data[$thisNum]['check'] = $answer;
// 업데이트된 question_data 배열을 세션에 다시 저장
$this->session->set('question_data', $question_data);
if($totalcnt == $thisNum){
$last = 'true';
}else{
$last = 'false';
}
return json_encode([
'status' => $result,
'answer' => $ans,
'nextnum' => $thisNum+1,
'last' => $last,
'totalcnt'=>$totalcnt,
'thisNum'=>$thisNum,
]);
}
public function quizresult (){
try {
// 세션에서 question_data 배열 가져오기
$this->checkLogin(); // 로그인 상태 체크
$questionData = $this->session->get('question_data');
if(!$questionData || empty($this->session->get('wordtests_no'))){
throw new \Exception('잘못된 접근입니다.');
}
// 정답과 오답 개수 계산
$totalQuestions = count($questionData);
$correctCount = 0;
$wronganswerlist = [];
$i=0;
foreach ($questionData as $question) {
if ($question['result'] == "true") {
$correctCount++;
} else {
$wronganswerlist['num'][$i] = $question['num'];
$wronganswerlist['key'][$i] = $question['key'];
$wronganswerlist['question'][$i] = $question['question'];
$wronganswerlist['example1'][$i] = $question['example1'];
$i++;
}
}
$percentage = ($correctCount / $totalQuestions) * 100;
$datas = [
'totalcnt' => $totalQuestions,
'answercnt' => $correctCount,
'percentage' => $percentage,
'wronganswerlist' => json_encode($wronganswerlist)
];
//var_Dump($questionData);
$WordTestModel = new WordTestModel();
$res = $WordTestModel->update($this->session->get('wordtests_no'), $datas);
if(!$res){
throw new \Exception('채점 중 문재가 발생 했습니다. 재로그인 후 시도하세요.');
}
return redirect()->to('/testresult/check')->with('success', '채점을 완료하였습니다. 결과를 확인하세요.');
} catch (\Exception $e) {
// 예외 처리
return redirect()->to('/')->with('error', $e->getMessage());
}
}
public function testresult ($ckd=null){
try {
$this->checkLogin(); // 로그인 상태 체크
$userId = $this->session->get('useremail');
if($ckd != 'check'){
$this->session->remove('question_date');
}
$data=[];
return $this->view('testresult_list', $data);
} catch (\Exception $e) {
// 예외 처리
return redirect()->to('/')->with('error', $e->getMessage());
}
}
public function testdataajax()
{
$firstDayString = $this->request->getVar('start_date', FILTER_SANITIZE_STRING);
$lastDayString = $this->request->getVar('end_date', FILTER_SANITIZE_STRING);
$userId = $this->session->get('useremail');
$model = new WordTestModel();
// 쿼리 빌더를 사용하여 데이터 검색
$query = $model->select('id,date,totalcnt,answercnt,percentage,updated_at')
->where('user_email', $userId)
->where('date>=',$firstDayString)
->where('date<=',$lastDayString)
->orderby('date', 'asc')
->get();
// JSON 형식으로 결과 반환
$result = $query->getResultArray();
echo json_encode($result);
}
public function testdatajson()
{
$model = new WordTestModel();
// 날짜 형식을 YYYY-MM로 설정
$email = $this->session->get('useremail');
// 데이터베이스에서 데이터 검색
$data = $model->where('user_email',$email)
->select('id, date, percentage,answercnt,totalcnt')
->findAll();
// 이벤트 배열 생성
$events = [];
foreach ($data as $item) {
$events[] = [
"id" => $item['id'],
"start" => $item['date'],
"editable" => false,
"display" => "background",
"color" => ($item['percentage']==0)?"red":"blue",
"type" => ($item['percentage']==0)?"false":"true",
"description" => ($item['percentage']==0) ? "No test records" : $item['answercnt']."/".$item['totalcnt']." = ".$item['percentage']."",
];
}
// Response 객체를 이용하여 JSON으로 변환하여 반환
return $this->response->setJSON($events);
}
public function retestsession($id){
$this->checkLogin(); // 로그인 상태 체크
$model = new WordTestModel();
$this->session->set('wordtests_no', $id);
$retestData = $model->find($id);
if(!$retestData){
echo "false";
}else{
$question_data = json_decode($retestData['question_data'], true);
$question_date = $retestData['date'];
$this->session->set('question_data', $question_data);
$this->session->set('question_date', $question_date);
echo "ok";
}
exit; //헤더 노출때문에
}
}