<?php

use app\libraries\DateHelper;
use app\libraries\Json;

defined('BASEPATH') or exit('No direct script access allowed');

/**
 * @property Event_course_model $Event_course_model
 */
class Event_makeup_next_timeslot extends MY_BackendController
{
    use Json;

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $eventId = $this->input->get('event_id');
        $timeslotId = $this->input->get('timeslot_id');
        $studentIds = $this->input->get('student_ids');
        $enrollmentItemIds = $this->input->get('enrollment_item_ids');
        $courseLock = $this->input->get('course_unlock') != "true";
        $date = $this->input->get('date');

        try {
            $res = [];

            $this->load->model('Event_course_model');
            $ec = $this->Event_course_model->getOne($this->Event_course_model->database, $this->Event_course_model->tbl, ['course_id'], $eventId, 'event_id');

            $this->load->model('Event_enrollment_item_model');
            $items = $this->Event_enrollment_item_model->makeup_next_timeslot($eventId, $timeslotId, $studentIds, $enrollmentItemIds, $date, $courseLock);


            if (!empty($items)) {
                // Get next event ids 
                $nextEventIds = [];
                foreach ($items as $item) {
                    array_push($nextEventIds, $item['event_id']);
                }

                $_ecs = $this->Event_course_model->getAllIn($this->Event_course_model->database, $this->Event_course_model->tbl, ['event_id', 'course_id'], 'event_id', $nextEventIds);
                $ecs = [];
                foreach ($_ecs as $_ec) {
                    $ecs[$_ec['event_id']] = $_ec['course_id'] == $ec['course_id'];
                }


                foreach ($items as $item) {
                    $date = date('Y-m-d', $item['startdate']);

                    $res[$item['id']] = [
                        'same_course' => $ecs[$item['event_id']],
                        'timeslot' => sprintf(
                            '%s  %s  (%s)  %s - %s',
                            $item['name'],
                            $date,
                            DateHelper::getDefaultTcWeekdays($item['startdate']),
                            $item['starttime'],
                            $item['endtime']
                        )
                    ];
                }
            }

            return $this->json_response([
                'error' => false,
                'success' => true,
                'data' => [
                    'next_timeslots' => $res
                ]
            ]);
        } catch (Exception $ex) {
            return $this->json_response([
                'error' => true,
                'success' => false,
                'data' => 'Error performing your request.'
            ]);
        }
    }
}
