<?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\Exam;
use App\Models\Student;
use App\Models\Teacher;

class ExamController 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('exams.index', compact('request'));
    } catch (\Exception $e) {
      $debug = config('app.debug');
      if ($debug) {
        dd($e);
      } else {
        return 'sorry but list exam failed';
      }
    }
  }

  public function getExamsJson(Request $request)
  {
    try {
      $arr = [];

      if (is_null($request->query('q'))) {
        // NOTE: return all records
        $exams = Exam::all();
      } else {
        // NOTE: request with query word
        $q_word = $request->query('q');
        $exams = Exam::where('title', 'LIKE', '%' . $q_word . '%')->get();
      }

      foreach ($exams as $row) {
        array_push($arr, [
          'id' => $row->id,
          'date' => $row->date,
          'subject_id' => $row->subject_id,
          'title' => $row->title,
          'remarks' => $row->remarks,
        ]);
      }

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

  public function show(Exam $exam, Request $request)
  {
    try {
      $exam = Exam::with(['subject'])->find($exam->id);

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

  public function edit(Exam $exam, Request $request)
  {
    try {
      $exam = Exam::with(['subject'])->find($exam->id);
      $teacher = $exam->teachers[0];

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

  public function destroy(Exam $exam)
  {
    try {
      $exam_id = $exam->id;
      $exam->teachers()->detach();

      $exam->delete();

      return redirect()
        ->route('exams.index')
        ->with('success', 'exam 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 dtGetExams()
  {
    try {
      $exams = Exam::with(['subject'])->select();

      return DataTables::eloquent($exams)->toJson();
    } catch (\Exception $e) {
      $debug = config('app.debug');
      if ($debug) {
        dd($e);
      } else {
        return 'sorry but list exam failed';
      }
    }
  }

  public function store(Request $request)
  {
    try {
      $validatedData = $request->validate([
        'date' => 'required',
        'subject_id' => 'required',
        'title' => 'required',
        'teacher_id' => 'required',
        'remarks' => '',
      ]);

      $teacher = Teacher::find($validatedData['teacher_id']);

      $exam_db = new Exam();
      $exam_db->date = $validatedData['date'];
      $exam_db->subject_id = $validatedData['subject_id'];
      $exam_db->title = $validatedData['title'];
      $exam_db->remarks = $validatedData['remarks'];

      $exam_db->save();
      $new_exam_id = $exam_db->id;

      $teacher->exams()->attach($new_exam_id);

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

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

  public function update(Request $request, Exam $exam)
  {
    try {
      $validatedData = $request->validate([
        'date' => 'required',
        'subject_id' => 'required',
        'title' => 'required',
        'teacher_id' => 'required',
        'remarks' => '',
      ]);

      DB::beginTransaction();

      $teacher = Teacher::find($validatedData['teacher_id']);
      $exam_db = Exam::find($exam->id);

      $exam_db->date = $validatedData['date'];
      $exam_db->subject_id = $validatedData['subject_id'];
      $exam_db->title = $validatedData['title'];
      $exam_db->remarks = $validatedData['remarks'];

      $exam_db->save();

      $exam_db->teachers()->detach();
      $exam_db->teachers()->attach($teacher);

      DB::commit();

      return redirect()
        ->route('exams.index')
        ->with('success', 'Exam has been created successfully.');
    } catch (\Exception $e) {
      DB::rollback();
      return $this->errHandler($e);
    }
  }

  public function dtGetSimpleExams(Request $request)
  {
    $exams = Exam::with(['subject'])
      ->orderBy('id', 'desc')
      ->limit(10)
      ->get();

    return response()->json($exams);
  }
}
