<?php

use app\libraries\DateHelper;

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

class Event_qrcode extends MY_BackendController
{
    public function __construct()
    {
        parent::__construct();

        $this->load->model('Room_model');
        $this->load->model('Teacher_model');
        $this->load->model('Student_model');
        $this->load->model('Event_timeslot_model');
        $this->load->model('Course_category_model');
        $this->load->model('Course_subcategory_model');
        $this->load->model('Event_enrollment_item_model');
    }

    protected function detail_course($eventId) {
        // Load Course Mode
        $this->load->model('Event_model');
        $this->load->model('Course_model');

        return $this->Event_model->detail_only_course($eventId);
    }

    public function index($eventId, $timeslotId)
    {   $course = $this->detail_course($eventId);
        $event = $this->Event_model->detail($eventId);
        if (!$event) {
            return $this->exception_dataNotFound();
        }

        if ($this->input->method() == 'post') {
            $params = $this->input->post();

            $this->Event_enrollment_item_model->update_in_event_attendance($params);
        }

        $category = $this->Course_category_model->detail($course['course_category_id']);
        $subCategory = $this->Course_subcategory_model->detail($course['course_category_sub_id']);

        // Teacher
        $teacher = $this->Teacher_model->detail_custom($event['pic_1']);

        // Event Time
        $timeslot = $this->Event_timeslot_model->detail($timeslotId);

        // Room
        $room = $this->Room_model->detail($event['room_id']);

        $startdate = $timeslot['startdate'];
        $daterange = sprintf('%s - %s', $timeslot['starttime'], $timeslot['endtime']);
        $date = date('Y-m-d', $startdate);
        $date_tc = sprintf('%s (%s)', $date, DateHelper::getDefaultTcWeekdays()[date('w', $startdate)]);
        $this->view('backend/event/qrcode', [
            '__eventId' => $eventId,
            '__timeslotId' => $timeslotId,
            '__pathname' => 'qrcode',
            'title' => $this->Course_model->fullTitle($course['name'], $event['weekdays']),
            'date' => $date,
            'date_tc' => $date_tc,
            'daterange' => $daterange,
            'course_mode' => $course['mode'],
            'course_category_name' => $category['name'],
            'course_category_sub_name' => $subCategory['name'],
            'course_name' => $course['name'],
            'teacher_name' => trim(sprintf('%s %s %s', $teacher['eng_firstname'], $teacher['eng_lastname'], $teacher['chi_name'])),
            'items' => $this->Event_enrollment_item_model->listing_in_event_attendance($eventId, $timeslotId),
            'room_name' => $room['name']
        ]);
    }
}
