<?php

namespace App\Http\Controllers;

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

use App\Models\Subject;

use Yajra\DataTables\Facades\DataTables;

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

    try {
      return view('subjects.index', compact('request'));
    } catch (\Exception $e) {
      // dd($e);
      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return 'list subject failed';
    }
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create(Request $request)
  {
    try {
      return view('subjects.create', compact('request'));
    } catch (\Exception $e) {
      // dd($e);
      return 'create subject failed';
    }
  }

  /**
   * Store a newly created resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @return \Illuminate\Http\Response
   */
  public function store(Request $request)
  {
    try {
      $validatedData = $request->validate([
        'subjectTitle' => 'required',
        'syllabusDetails' => '',
      ]);

      $subject = new Subject();
      $subject->subjectTitle = $validatedData['subjectTitle'];
      $subject->syllabusDetails = $validatedData['syllabusDetails'];
      $subject->save();

      Session::forget('status');

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

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return view('subjects.create', compact('request'));
    }
  }

  /**
   * Display the specified resource.
   *
   * @param  \App\Subject  $Subject
   * @return \Illuminate\Http\Response
   */
  public function show(Subject $subject, Request $request)
  {
    try {
      return view('subjects.show', compact('subject', 'request'));
    } catch (\Exception $e) {
      // dd($e);
      return 'show subject failed';
    }
  }

  /**
   * Show the form for editing the specified resource.
   *
   * @param  \App\Subject  $Subject
   * @return \Illuminate\Http\Response
   */
  public function edit(Subject $subject, Request $request)
  {
    try {
      return view('subjects.edit', compact('request', 'subject'));
    } catch (\Exception $e) {
      dd($e);
      return 'edit subject failed';
    }
  }

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \App\Subject  $Subject
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, Subject $subject)
  {
    try {
      $validatedData = $request->validate([
        'subjectTitle' => 'required',
        'syllabusDetails' => 'required',
      ]);

      Subject::where('id', $subject->id)->update([
        'subjectTitle' => $validatedData['subjectTitle'],
        'syllabusDetails' => $validatedData['syllabusDetails'],
      ]);

      return redirect()
        ->route('subjects.index')
        ->with('success', 'Subject Has Been updated successfully');
    } catch (\Exception $e) {
      DB::rollback();

      $message = $e->getMessage();
      $request->session()->put('status', $message);

      return view('subjects.edit', compact('subject', 'request'));
    }
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  \App\Subject  $Subject
   * @return \Illuminate\Http\Response
   */
  public function destroy(Subject $subject)
  {
    try {
      $subject->delete();

      return redirect()
        ->route('subjects.index')
        ->with('success', 'Subject has been deleted successfully');
    } catch (\Exception $e) {
      dd($e);
      return 'delete subject failed';
    }
  }

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

      if (is_null($request->query('q'))) {
        // NOTE: return all records
        $subjects = subject::orderBy('id', 'asc')->get();

        foreach ($subjects as $row) {
          array_push($arr, [
            'id' => $row->id,
            'subjectTitle' => $row->subjectTitle,
            'syllabusDetails' => $row->syllabusDetails,
          ]);
        }
      } else {
        // NOTE: request with query word
        $q_word = $request->query('q');
        $subjects = subject::where(
          'subjectTitle',
          'LIKE',
          '%' . $q_word . '%'
        )->get();

        foreach ($subjects as $row) {
          array_push($arr, [
            'id' => $row->id,
            'subjectTitle' => $row->subjectTitle,
            'syllabusDetails' => $row->syllabusDetails,
          ]);
        }
      }

      return response()->json($arr);
    } catch (\Exception $e) {
      // dd($e);
      return 'getSubjectsJson failed';
    }
  }

  public function dtGetSubjects()
  {
    $subjects = Subject::select(['id', 'subjectTitle'])->where(
      'deleted',
      '=',
      'false'
    );

    return DataTables::eloquent($subjects)->toJson();
  }

  public function SoftDelete(Request $request, string $id)
  {
    // to prevent the delete alter the schedules assigned

    try {
      Subject::where('id', $id)->update([
        'deleted' => 'true',
      ]);

      return redirect()
        ->route('subjects.index')
        ->with('success', 'subject Has Been updated successfully');
    } catch (\Exception $e) {
      return redirect()
        ->route('subjects.index')
        ->with('failed', 'failed during delete subjects');
    }
  }
}
