<?php

namespace App\Http\Controllers;

use DateTime;
use DateInterval;
use DatePeriod;

use App\Models\Schedule;
use App\Models\ClassRoom;
use App\Models\User;
use App\Models\ClassRoomActivity;
use App\Models\ScheduleSubjectRel;

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

use Yajra\DataTables\Facades\DataTables;

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

    try {
      $schedules = Schedule::with(['classrooms', 'subjects'])->get();

      return view('schedules.index', compact('request', 'schedules'));
    } catch (\Exception $e) {
      dd($e);
      return 'list schedule failed';
    }
  }

  /**
   * Show the form for creating a new resource.
   *
   * @return \Illuminate\Http\Response
   */
  public function create(Request $request)
  {
    try {
      return view('schedules.create', compact('request'));
    } catch (\Exception $e) {
      dd($e);
      return 'create schedule 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([
        'class_room_id' => 'required',
        'subject_id' => 'required',
        'subject' => 'required', //TODO: rename field, change it to "name"
        'startTime' => 'required',
        'endTime' => 'required',
        'description' => 'required',
      ]);

      // Schedule::create($request->post());
      DB::beginTransaction();

      $schedule = new Schedule();

      // TODO: need review
      $schedule->day = '1';
      // TODO: need review

      $schedule->startTime = $validatedData['startTime'];
      $schedule->endTime = $validatedData['endTime'];
      $schedule->description = $validatedData['description'];
      $schedule->subject = $validatedData['subject']; //TODO: rename field, change it to "name"
      $schedule->save();
      $newScheduleId = $schedule->id;

      $class_room_id = $validatedData['class_room_id'];
      $startTime = $validatedData['startTime'];
      $endTime = $validatedData['endTime'];

      // // get the days in between startTime and endTime
      $begin = new DateTime($startTime);
      $end = new DateTime($endTime);
      $interval = DateInterval::createFromDateString('1 day');
      $period = new DatePeriod($begin, $interval, $end);

      $arr = [];
      foreach ($period as $dt) {
        array_push($arr, $dt->format('Y-m-d'));
      }
      array_push($arr, $end->format('Y-m-d'));

      foreach ($arr as $day) {
        $class_room_activity = new ClassRoomActivity();
        $class_room_activity->class_room_id = $class_room_id;
        $class_room_activity->schedule_id = $newScheduleId;
        $class_room_activity->date_epoch = strtotime($day);
        $class_room_activity->save();
      }

      $schedule_subject_rel = new ScheduleSubjectRel();
      $schedule_subject_rel->subject_id = $validatedData['subject_id'];
      $schedule_subject_rel->schedule_id = $newScheduleId;
      $schedule_subject_rel->save();

      DB::commit();

      Session::forget('status');

      return redirect()
        ->route('schedules.index')
        ->with('success', 'Schedule has been created successfully.');
    } catch (\Exception $e) {
      DB::rollback();
      // dd($e);

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

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

  /**
   * Display the specified resource.
   *
   * @param  \App\Schedule  $schedule
   * @return \Illuminate\Http\Response
   */
  public function show(Schedule $schedule, Request $request)
  {
    try {
      // dd($schedule->subjects[0]->deleted);
      return view('schedules.show', compact('schedule', 'request'));
    } catch (\Exception $e) {
      dd($e);
      return 'show schedule failed';
    }
  }

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

  /**
   * Update the specified resource in storage.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \App\Schedule  $schedule
   * @return \Illuminate\Http\Response
   */
  public function update(Request $request, Schedule $schedule)
  {
    try {
      $validatedData = $request->validate([
        'class_room_id' => 'required',
        'description' => 'required',
        'subject_id' => 'required',
        'subject' => 'required', //TODO: change field name to "name"
        'startTime' => 'required',
        'endTime' => 'required',
      ]);

      DB::beginTransaction();

      // Schedule::where('id', $schedule->id)->update([
      //     'startTime' => $validatedData['startTime'],
      //     'endTime' => $validatedData['endTime'],
      //     'description' => $validatedData['description'],
      // ]);
      $schedule = Schedule::find($schedule->id);
      $schedule->startTime = $validatedData['startTime'];
      $schedule->endTime = $validatedData['endTime'];
      $schedule->description = $validatedData['description'];
      $schedule->subject = $validatedData['subject'];
      $schedule->save();

      $new_subject_id = $validatedData['subject_id'];

      $class_room_id = $validatedData['class_room_id'];
      $startTime = $validatedData['startTime'];
      $endTime = $validatedData['endTime'];
      $begin = new DateTime($startTime);
      $end = new DateTime($endTime);
      $interval = DateInterval::createFromDateString('1 day');
      $period = new DatePeriod($begin, $interval, $end);
      $arr = [];
      foreach ($period as $dt) {
        array_push($arr, $dt->format('Y-m-d'));
      }
      array_push($arr, $end->format('Y-m-d'));

      // TODO: some checking here

      // detach all subjects
      $subjects = $schedule->subjects;
      foreach ($subjects as $subject) {
        $schedule->subjects()->detach($subject->id);
      }

      $schedule->subjects()->attach($new_subject_id);

      // delete existing booking schedule-classroom
      $deleted = ClassRoomActivity::where(
        'schedule_id',
        $schedule->id
      )->delete();

      foreach ($arr as $day) {
        $class_room_activity = new ClassRoomActivity();
        $class_room_activity->class_room_id = $class_room_id;
        $class_room_activity->schedule_id = $schedule->id;
        $class_room_activity->date_epoch = strtotime($day);
        $class_room_activity->save();
      }

      // $schedule->fill($request->post())->save();

      DB::commit();

      Session::forget('status');

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

      dd($e);
      // return 'update schedule failed';

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

      return view('teachers/EditSchedule', compact('request'));
    }
  }

  /**
   * Remove the specified resource from storage.
   *
   * @param  \App\Schedule  $schedule
   * @return \Illuminate\Http\Response
   */
  public function destroy(Schedule $schedule)
  {
    try {
      $schedule->delete();
      return redirect()
        ->route('schedules.index')
        ->with('success', 'Schedule has been deleted successfully');
    } catch (\Exception $e) {
      dd($e);
      return 'delete schedule failed';
    }
  }

  public function dtGetSchedules(Request $request)
  {
    $schedules = Schedule::with(['classrooms', 'subjects']);

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

  public function dtGetSimpleSchedules(Request $request)
  {
    $schedules = Schedule::with(['classrooms', 'subjects'])
      ->orderBy('id', 'desc')
      ->limit(10)
      ->get();

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