<?php

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

use app\libraries\DateHelper;
use app\libraries\ICSParser;

/**
 * Event_index_calendar trait aiding reuse the methods of :
 * 1. backend/Event/index::calendar()
 * 2. api/Event_calendar/reload::calendar()
 * 
 * api/
 * - require_once __DIR__ . '/../backend/Event_index_calendar.php';
 * - use Event_index_calendar;
 * 
 * backend/
 * - require_once 'Event_index_calendar.php';
 * - use Event_index_calendar;
 */
trait Event_index_calendar
{
    protected function calendar()
    {
        $this->load->model('Teacher_model');
        $this->load->model('Room_model');
        $this->load->model('Event_model');
        $this->load->model('Event_enrollment_item_model');
        $this->load->model('Invoicing_model');

        $icsParser = new ICSParser(FCPATH . 'uploads/public_holiday/1576452468-tc.ics');
        $resources = [];
        // Resource
        $resource = $this->input->get('resource') ?? 'pic';
        $mode = $this->input->get('mode') ?? 'w';
        $date = $this->input->get('date') ?? date('Y-m-d');
        $_pics = $this->Teacher_model->listing_selection();
        $pics = [];
        if (!empty($_pics)) {
            foreach ($_pics as $_pic) {
                $pics[$_pic['id']] = $_pic['chi_name'] ?? $_pic['eng_firstname'] . ' ' . $_pic['eng_lastname'];
            }
        }
        $_rooms = $this->Room_model->all();
        $rooms = [];
        foreach ($_rooms as $_room) {
            $rooms[$_room['id']] = $_room['status'] == 0 ? "<span class='notinuse'>" . $_room['name'] . "</span>" : $_room['name'];
        }
        switch ($resource) {
            case 'pic':
                $resources = $pics;
                break;
            case 'room':
                $resources = $rooms;
                break;
        }

        $events = $this->Event_model->listing_in_event_calendar((new DateTime($date))->getTimestamp());
        $_enrollmentItems = $this->Event_enrollment_item_model->listing_in_event_calendar();
        $enrollmentItems = [];
        foreach ($_enrollmentItems as $_enrollmentItem) {
            $key = sprintf('%s-%s', $_enrollmentItem['event_id'], $_enrollmentItem['event_timeslot_id']);
            //			log_message('debug','key:'.$key);
            /*
			 * DEBUG - 2021-02-01 11:58:26 --> key:1-1
DEBUG - 2021-02-01 11:58:26 --> key:1-2
DEBUG - 2021-02-01 11:58:26 --> key:1-3
DEBUG - 2021-02-01 11:58:26 --> key:1-4
			 */
            if (empty($enrollmentItems[$key])) $enrollmentItems[$key] = [];
            array_push($enrollmentItems[$key], $_enrollmentItem);
        }
        //        log_message('debug','item count:'.count($enrollmentItems));//4
        $paidStatuses = $this->Invoicing_model->listing_paid_statuses();

        $hk = new DateTimeZone('Asia/Hong_Kong');
        foreach ($events as $event) {
            $eventId = $event['id'];
            $timeslotId = $event['timeslot_id'];
            $key = sprintf('%s-%s', $eventId, $timeslotId);
            $startDatetime = sprintf('%s %s', date('Y-m-d', $event['timeslot_startdate']), $event['timeslot_starttime']);
            $endDatetime = sprintf('%s %s', date('Y-m-d', $event['timeslot_startdate']), $event['timeslot_endtime']);
            $teacherName = $pics[$event['pic_1']] ?? '';

            switch ($resource) {
                case 'pic':
                    $resourceName = $teacherName;
                    break;
                case 'room':
                    $resourceName = $rooms[$event['room_id']];
                    break;
            }

            //            log_message('debug','key:'.$key);
            //			log_message('debug','empty item?'.empty($enrollmentItems[$key]));
            $icsParser->addEvent(
                $eventId,
                date('Y-m-d', $event['timeslot_startdate']),
                $event['course_duration'],
                $resourceName,
                DateTime::createFromFormat('Y-m-d H:i', $startDatetime, $hk)->getTimestamp(),
                DateTime::createFromFormat('Y-m-d H:i', $endDatetime, $hk)->getTimestamp(),
                false,
                'event',
                $this->load->view('/backend/event/partials/calendarbox', [
                    'eventId' => $eventId,
                    'display_name' => $event['display_name'],
                    'timeslotId' => $timeslotId,
                    'timeslot_starttime' => $event['timeslot_starttime'],
                    'timeslot_endtime' => $event['timeslot_endtime'],
                    'bgcolor' => $event['category_bgcolor'] ?? $event['course_bgcolor'],
                    'teacherId' => $event['pic_1'],
                    'teacherName' => $teacherName,
                    'courseId' => $event['course_id'],
                    'courseName' => $event['course_name'],
                    'courseMode' => $event['course_mode'],
                    'timeslotSelectedMonth' => date('Y-m', $event['timeslot_startdate']),
                    'tcWeekday' => DateHelper::getDefaultWeekdays($event['timeslot_startdate']),
                    'courseCode' => $event['course_code'],
                    'roomId' => $event['room_id'],
                    'roomName' => $rooms[$event['room_id']],
                    'enrollmentItems' => $enrollmentItems[$key] ?? [],
                    'paidStatuses' => !empty($enrollmentItems[$key]) ? $paidStatuses : [],
                    'remark' => $event['remark']
                ], true)
            );
        }

        return [
            'events' => $icsParser->json(),
            'resources' => json_encode(array_values($resources)),
        ];
    }
}
