<?php

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

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

require_once 'Event_index_calendar.php';
class Event extends MY_BackendController
{
    use Event_index_calendar;

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

    protected function detail_course($eventId)
    {
        // Load Course Mode
        return $this->Event_model->detail_only_course($eventId);
    }

    public function index()
    {
        $res = $this->calendar();
        //        log_message('debug','empty res?'.empty($res));//false
        //        return false;
        //        log_message('debug','empty events count:'.empty($res['events']));//false
        //        return false;
        $this->view('backend/event/index', [
            '_events' => $res['events'],
            '_resources' => $res['resources'],
            '_action_' => ''
        ]);
    }
    /**
     * Some features are in api.
     * api/Event.php
     * 
     * course_subcategory()
     * course()
     * select()
     * course_detail()
     * enroll_mode()
     * course_detail_pay()
     * listing_month_dates()
     * listing_lesson_dates()
     */
    public function add()
    {
        // $this->load->model('Event_model');
        $this->load->model('Teacher_model');
        $this->load->model('Room_model');
        $this->load->model('Teacher_model');
        $this->load->model('Course_model');
        $this->load->model('Course_category_model');
        // Date
        $date = $this->input->get('date') ?? date('Y-m-d');
        // Resource
        $resource = $this->input->get('resource') ?? null;
        // ResourceName
        $resourceName = $this->input->get('resourceName') ?? null;
        // Resource + ResourceName => Default Resourcec Selection
        $roomId = null;
        $picId = null;
        if (empty($resource) || empty($resourceName)) {
        } else {
            switch ($resource) {
                case 'pic':
                    $teacher = $this->Teacher_model->detail_chiName($resourceName);
                    if ($teacher) {
                        $picId = $teacher['id'];
                    }
                    break;
                case 'room':
                    $room = $this->Room_model->detail_name($resourceName);
                    if ($room) {
                        $roomId = $room['id'];
                    }
                    break;
            }
        }
        $this->view('backend/event/add', [
            'title' => '新增時段',
            'name' => null,
            'date' => $date,
            'room_id' => $roomId,
            'rooms' => $this->Room_model->listing_selection(),
            'pic_1' => $picId,
            'pic_2' => null,
            'teachers' => $this->Teacher_model->listing_selection(),
            'course_id' => null,
            'courses' => $this->Course_model->listing_in_event_selection(),
            'course_category_id' => null,
            'courseCategories' => $this->Course_category_model->listing_selection()
        ]);
    }

    public function edit($eventId, $timeslotId)
    {
        $this->load->model('Event_model');
        $this->load->model('Course_model');
        $this->load->model('Event_enrollment_model');
        $this->load->model('Event_course_model');
        $this->load->model('Event_timeslot_model');
        $this->load->model('Teacher_model');
        $this->load->model('Room_model');
        $this->load->model('Teacher_model');
        $this->load->model('Course_category_model');
        $this->load->model('Course_subcategory_model');

        $course = $this->detail_course($eventId);
        $item = $this->Event_model->detail($eventId);
        if (!$course || !$item) {
            return $this->exception_dataNotFound();
        }
        $cannotEdit = $this->Event_enrollment_model->listing_by_event_id($eventId);
        $cannotEdit2 = $this->Event_enrollment_item_model->listing_in_event_id($eventId);
        if (count($cannotEdit) > 0) {
            $this->_data['__alert_failure_message'] = '系統發現此時段或相關的時段內已有學生報名，因此不會儲存編輯的資料。';
        }
        if (count($cannotEdit2) > 0) {
            $this->_data['__alert_failure_message'] = '系統發現此時段或相關的時段內已有學生報名，因此不會儲存編輯的資料。';
        }
        if ($this->input->method() == 'post' && !array_key_exists('__alert_failure_message', $this->_data)) {
            $this->Event_model->delete($eventId);
            $this->Event_course_model->delete_by_event_id($eventId);
            $this->Event_timeslot_model->delete_by_event_id($eventId);
            return $this->save();
        }
        $timeslot = $this->Event_timeslot_model->detail($timeslotId);
        $date = date('Y-m-d', $timeslot['startdate']);
        $mode = $course['mode'];
        // Resource + ResourceName => Default Resourcec Selection
        $roomId = $item['room_id'];
        $pic1 = $item['pic_1'];
        $pic2 = $item['pic_2'];
        $remark = $item['remark'];
        switch ($mode) {
            case 'month':
                if ($item) {
                    $weekdayArr = json_decode($item['weekday_json'], true);
                    $weekdays = [];
                    if (!empty($weekdayArr)) {
                        $dateTimestamp = (new DateTime($weekdayArr[0]['timeslot']))->getTimestamp();
                        while (true) {
                            $item2 = array_pop($weekdayArr);
                            if (!array_key_exists($item2['weekday'], $weekdays)) {
                                $weekdays[intval($item2['weekday'])] = date('H:i', (new DateTime($item2['timeslot']))->getTimestamp());
                            } else {
                                break;
                            }
                        }
                        ksort($weekdays);
                    }
                }
                $detail = $this->load->view('backend/event/partials/edit_mode_' . $mode, [
                    'duration' => $course['duration'],
                    'date' => date('Y-m-d', $timeslot['startdate']),
                    'date_from' => $item['date_from'],
                    'date_to' => $item['date_to'],
                    'dateTimestamp' => $timeslot['startdate'],
                    'default_weekdays' => DateHelper::getDefaultWeektimes(),
                    'weekdays' => $weekdays,
                    'dateTimestamp' => empty($dateTimestamp) ? '' : $dateTimestamp,
                    'hk' => new DateTimeZone('Asia/Hong_Kong'),
                ], true);
                break;
            case 'lesson':
                $weekdays = [];
                if ($item) {
                    $weekdayArr = json_decode($item['weekday_json'], true);
                    while (true) {
                        $item2 = array_pop($weekdayArr);
                        if (!array_key_exists($item2['weekday'], $weekdays)) {
                            $weekdays[intval($item2['weekday'])] = date('H:i', (new DateTime($item2['timeslot']))->getTimestamp());
                        }
                        if (count($weekdayArr) == 0) {
                            break;
                        }
                    }
                    ksort($weekdays);
                }
                $detail = $this->load->view('backend/event/partials/edit_mode_' . $mode, [
                    'duration' => $course['duration'],
                    'date' => date('Y-m-d', $timeslot['startdate']),
                    'date_from' => $item['date_from'],
                    'dateTimestamp' => $timeslot['startdate'],
                    'timeslots' => $this->Event_timeslot_model->listing_by_event_id($eventId),
                    'default_weekdays' => DateHelper::getDefaultWeektimes(),
                    'weekdays' => $weekdays,
                    'tc_weekdays' => DateHelper::getDefaultTcWeekdays(),
                    'total_lessons' => $item['total_lessons'],
                ], true);
                break;
            case 'period':
                $detail = $this->load->view('backend/event/partials/edit_mode_' . $mode, [
                    'duration' => $course['duration'],
                    '__nonRegularTimeslots' => $this->Event_timeslot_model->listing_by_event_id($eventId),
                ], true);
                break;
        }
        $this->view('backend/event/edit', [
            '__eventId' => $eventId,
            '__timeslotId' => $timeslotId,
            '__pathname' => 'edit',
            'title' => $this->Course_model->fullTitle($course['name'], $item['weekdays']),
            'display_name' => $item['display_name'],
            'date' => $date,
            'room_id' => $roomId,
            'rooms' => $this->Room_model->listing_selection(),
            'pic_1' => $pic1,
            'pic_2' => $pic2,
            'teachers' => $this->Teacher_model->listing_selection(),
            'course_mode' => $course['mode'],
            'course_id' => $course['id'],
            'courses' => $this->Course_model->listing_selection(),
            'course_category_id' => $course['course_category_id'],
            'courseCategories' => $this->Course_category_model->listing_selection(),
            'course_category_sub_id' => $course['course_category_sub_id'],
            'courseSubCategories' => $this->Course_subcategory_model->listing_selection(),
            'remark' => $remark,
            'detail' => $detail
        ]);
    }
    // Insert / Update
    public function save()
    {
        $this->load->model('Event_model');
        $this->load->model('Event_timeslot_model');
        $data = $this->input->post();
        $mode = $data['mode'];
        unset($data['mode']);
        $params = [];
        $params = $data;
        if ($mode === 'c') {
            $this->Event_model->create($params);
        } else {
            $this->Event_model->update($params, $data['id']);
        }
        redirect('/event?date=' . $this->Event_timeslot_model->courseDate);
    }
}
