<?php

namespace App\Http\Controllers;

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

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

class ClassRoomActivityController extends Controller
{
  public function createClassRoomActivity(Request $request)
  {
    try {
      $data = $request->all();

      $classRoomActivity = new ClassRoomActivity();
      $result = $classRoomActivity->createClassRoomActivity($data);

      if ($result) {
        // return response()->json(['status' => 'success']);
        $schedules = Schedule::orderBy('id', 'desc')->paginate(10);
        return view('schedules.index', compact('request', 'schedules'));
      } else {
        return response()->json(['status' => 'error']);
      }
    } catch (\Exception $e) {
      dd($e);
      return 'createClassRoomActivity failed';
    }
  }

  public function listAllClassRoom()
  {
    try {
      // $classrooms = ClassRoom::orderBy('id','asc');
      $classRoomsResult = DB::table('class_rooms')->get();
      $classRooms = [];

      foreach ($classRoomsResult as $classRoom) {
        array_push($classRooms, $classRoom);
      }

      return $classRooms;
    } catch (\Exception $e) {
      dd($e);
      return 'list all classroom failed';
    }
  }

  public function listFreeClassRoom(Request $request)
  {
    try {
      $data = $request->all();

      $startTime = $data['startTime'];
      $endTime = $data['endTime'];

      $startEpoch = strtotime($startTime);
      $endEpoch = strtotime($endTime);

      $arr = [];
      $output = [];

      if (is_null($request->query('q'))) {
        // NOTE: return all records

        $all_free_class_room_in_period = DB::table('class_rooms')
          ->whereNotIn('id', function ($query) use ($startEpoch, $endEpoch) {
            $query
              ->select('class_room_id')
              ->from('class_room_activities')
              ->where('date_epoch', '>=', $startEpoch)
              ->orWhere('date_epoch', '<=', $endEpoch);
          })
          ->get()
          ->unique('id');
      } else {
        // NOTE: request with query word
        $q_word = $request->query('q');

        $all_free_class_room_in_period = DB::table('class_rooms')
          ->where('classroomTitle', 'LIKE', '%' . $q_word . '%')
          ->whereNotIn('id', function ($query) use ($startEpoch, $endEpoch) {
            $query
              ->select('class_room_id')
              ->from('class_room_activities')
              ->where('date_epoch', '>=', $startEpoch)
              ->orWhere('date_epoch', '<=', $endEpoch);
          })
          ->get()
          ->unique('id');
      }

      foreach ($all_free_class_room_in_period as $free_class_room) {
        array_push($output, $free_class_room);
      }

      return response()->json($output);
    } catch (\Exception $e) {
      dd($e);
      return 'listFreeClassRoom failed';
    }
  }
}
