<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

use Yajra\DataTables\Facades\DataTables;

use App\Models\ExamResult;
use App\Models\Student;
use App\Models\Teacher;
use App\Models\Exam;

class ExamResultController extends Controller
{
  function returnToLogin()
  {
    return redirect()
      ->route('login')
      ->with('success', 'sorry but the session already timeout');
  }

  function errHandler($th)
  {
    $ERR_CANNOT_GET_EMAIL = 'Attempt to read property "email" on null';

    if ($ERR_CANNOT_GET_EMAIL == $th->getMessage()) {
      return $this->returnToLogin();
    } else {
      throw dd($th);
    }
  }

  /**
   * Display a listing of the resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function index(Request $request)
  {
    Session::forget('status');

    try {
      return view('exam_results.index', compact('request'));
    } catch (\Exception $e) {
      $debug = config('app.debug');
      if ($debug) {
        dd($e);
      } else {
        return 'sorry but list exam failed';
      }
    }
  }

  public function getExamResultsJson()
  {
    try {
      $arr = [];
      $exam_results = ExamResult::orderBy('id', 'asc')->paginate(100);

      foreach ($exam_results as $row) {
        array_push($arr, [
          'exam_id' => $row->exam_id,
          'subject_id' => $row->subject_id,
          'student_email' => $row->student_email,
          'result' => $row->result,
          'remarks' => $row->remarks,
        ]);
      }

      return response()->json($arr);
    } catch (\Exception $e) {
      $debug = config('app.debug');
      if ($debug) {
        dd($e);
      } else {
        return 'sorry but list exam_results failed';
      }
    }
  }

  public function show(ExamResult $exam_result, Request $request)
  {
    try {
      $exam_result = ExamResult::with(['exam', 'student', 'teacher'])->find(
        $exam_result->id
      );

      return view('exam_results.show', compact('exam_result', 'request'));
    } catch (\Exception $e) {
      $debug = config('app.debug');
      if ($debug) {
        dd($e);
      } else {
        return 'sorry but show exam results failed';
      }
    }
  }

  public function edit(ExamResult $exam_result, Request $request)
  {
    try {
      return view('exam_results.edit', compact('exam_result', 'request'));
    } catch (\Exception $e) {
      $debug = config('app.debug');
      if ($debug) {
        dd($e);
      } else {
        return 'sorry but edit exam_result failed';
      }
    }
  }

  public function destroy(ExamResult $exam_result)
  {
    try {
      $exam_result->delete();
      return redirect()
        ->route('exam_results.index')
        ->with('success', 'exam_result has been deleted successfully');
    } catch (\Exception $e) {
      $debug = config('app.debug');
      if ($debug) {
        dd($e);
      } else {
        $ERR_MSG = 'delete classroom failed';
        return $ERR_MSG;
      }
    }
  }

  public function dtGetExamResults()
  {
    try {
      $exam_results = ExamResult::with([
        'student',
        'teacher',
        'exam',
      ])->select();

      return DataTables::eloquent($exam_results)->toJson();
    } catch (\Exception $e) {
      $debug = config('app.debug');

      if ($debug) {
        dd($e);
      } else {
        return 'sorry but list exam result failed';
      }
    }
  }

  public function dtGetExamResultsByStudentEmail(
    Request $request,
    string $student_email
  ) {
    try {
      $exam_results = ExamResult::select()->where(
        'student_email',
        '=',
        $student_email
      );

      return DataTables::eloquent($exam_results)->toJson();
    } catch (\Exception $e) {
      $debug = config('app.debug');

      if ($debug) {
        dd($e);
      } else {
        return 'sorry but list exam result failed';
      }
    }
  }

  public function create(Request $request)
  {
    try {
      return view('exam_results.create', compact('request'));
    } catch (\Exception $e) {
      //throw $th;
      dd($e);
      return 'add new exam failed';
    }
  }

  public function store(Request $request)
  {
    try {
      $validatedData = $request->validate([
        'exam_id' => 'required',
        'student_id' => 'required',
        'teacher_id' => 'required',
        'result' => '',
      ]);

      $exam = Exam::find($validatedData['exam_id']);
      $student = Student::find($validatedData['student_id']);
      $teacher = Teacher::find($validatedData['teacher_id']);

      $exam_result_db = new ExamResult();

      $exam_result_db->result = $validatedData['result'];
      $exam_result_db->remarks = $request['remarks'];
      $exam_result_db->student_id = $student->id;
      $exam_result_db->teacher_id = $teacher->id;
      $exam_result_db->exam_id = $exam->id;

      $exam_result_db->save();

      return redirect()
        ->route('exam_results.index')
        ->with('success', 'ExamResult has been created successfully.');
    } catch (\Exception $e) {
      dd($e);

      return 'add exam result failed';
    }
  }

  public function update(Request $request, ExamResult $exam_result)
  {
    try {
      $validatedData = $request->validate([
        'exam_id' => 'required',
        'student_id' => 'required',
        'teacher_id' => 'required',
        'result' => '',
      ]);

      $exam = Exam::find($validatedData['exam_id']);
      $student = Student::find($validatedData['student_id']);
      $teacher = Teacher::find($validatedData['teacher_id']);

      $exam_result_db = ExamResult::find($exam_result->id);

      $exam_result_db->result = $validatedData['result'];
      $exam_result_db->remarks = $request['remarks'];
      $exam_result_db->student_id = $student->id;
      $exam_result_db->teacher_id = $teacher->id;
      $exam_result_db->exam_id = $exam->id;

      $exam_result_db->save();

      return redirect()
        ->route('exam_results.index')
        ->with('success', 'ExamResult has been updated successfully.');
    } catch (\Exception $e) {
      return $this->errHandler($e);
    }
  }
}
