<?php



use app\libraries\DateHelper;

use app\libraries\Json;



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



class Event extends MY_ApiController

{



    use \app\libraries\Json;



    public function __construct()

    {

        parent::__construct();

    }



    public function course_subcategory()

    {

        $this->load->model('Course_subcategory_model');



        $request = $this->input->get();



        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => $this->Course_subcategory_model->listing_by_course_category($request['course_category_id']),

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function course()

    {

        $this->load->model('Course_model');



        $request = $this->input->get();



        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => $this->Course_model->listing_by_course_subcategory($request['course_category_id'], $request['course_subcategory_id']),

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function select()

    {

        $this->load->model('Event_model');



        $request = $this->input->get();



        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => $this->Event_model->listing_by_course($request['course_id']),

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function course_detail()

    {

        $this->load->model('Course_model');



        $request = $this->input->get();



        $item = $this->Course_model->detail($request['id']);

        $mode = $item['mode'];



        // Date

        $date = $this->input->get('date') ? $this->input->get('date') : date('Y-m-d');

        $dateTimestamp = DateTime::createFromFormat('Y-m-d', $date)->getTimestamp();

        $dayOfWeek = intval(date('w', $dateTimestamp));



        // Time

        $time = $this->input->get('time') ? $this->input->get('time') : date('H:00');



        // Date + Time => Weekdays

        $weekdays = [$dayOfWeek => $time];



        $this->load->model('Setting_center_model');

        $settings = $this->Setting_center_model->detail();



        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => [

                    'mode' => $item['mode'],

                    'detail_html' => $this->load->view('backend/event/partials/add_course_detail', [

                        'item' => $item

                    ], true),

                    'mode_html' => $this->load->view('backend/event/partials/add_weekday_mode_' . $mode, [

                        'default_weekdays' => DateHelper::getDefaultWeektimes(),

                        'weekdays' => $weekdays,

                        'date' => $date,

                        'time' => $time,

                        'end_date' => $settings['default_event_end_date'],

                        'hk' => new DateTimeZone('Asia/Hong_Kong'),

                        'total_lessons' => 0

                    ], true),

                ],

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function enroll_mode()

    {

        $this->load->model('Event_model');

        $params = $this->input->get();



        $eventId = $params['event_id'];

        $event = $this->Event_model->detail($eventId);

        $course = $this->Event_model->detail_only_course($eventId);



        $this->load->model('Event_enrollment_invoicing_model');

        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => $this->Event_enrollment_invoicing_model->enroll_mode($event, $course),

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function course_detail_pay()

    {

        $this->load->model('Course_model');



        $request = $this->input->get();



        $item = $this->Course_model->detail($request['id']);

        $mode = $item['mode'];



        // Date

        $date = $this->input->get('date') ? $this->input->get('date') : date('Y-m-d');

        $dateTimestamp = DateTime::createFromFormat('Y-m-d', $date)->getTimestamp();

        $dayOfWeek = intval(date('w', $dateTimestamp));



        // Time

        $time = $this->input->get('time') ? $this->input->get('time') : date('H:00');



        // Date + Time => Weekdays

        $weekdays = [$dayOfWeek => $time];



        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => [

                    'mode' => $item['mode'],

                    'detail_html' => $this->load->view('backend/event/partials/add_course_detail', [

                        'item' => $item

                    ], true),

                    'mode_html' => $this->load->view('backend/event/partials/add_weekday_mode_' . $mode, [

                        'default_weekdays' => DateHelper::getDefaultWeektimes(),

                        'weekdays' => $weekdays,

                        'date' => $date,

                        'hk' => new DateTimeZone('Asia/Hong_Kong'),

                        'total_lessons' => 0

                    ], true),

                ],

            ],

        ], JSON_UNESCAPED_UNICODE);

    }

    public function listing_month_dates()

    {

        $this->load->model('Course_model');

        $this->load->model('Event_timeslot_model');



        $request = $this->input->post();
        $request['weekday-sun-time'] = $request['time'][0];
        $request['weekday-mon-time'] = $request['time'][1];
        $request['weekday-tue-time'] = $request['time'][2];
        $request['weekday-wed-time'] = $request['time'][3];
        $request['weekday-thu-time'] = $request['time'][4];
        $request['weekday-fri-time'] = $request['time'][5];
        $request['weekday-sat-time'] = $request['time'][6];
        
       
       
        $course = $this->Course_model->detail($request['course_name']);



        if (!empty($request['enrollOrPay'])) {

            if ($request['enrollOrPay'] == 'enroll') {

                // From Date information

                $fromDate = $request['start_date'];

                $toDate = $request['end_date'];

            } else if ($request['enrollOrPay'] == 'pay') {

                //if ($course['mode'] == 'month') {

                    $fromDate = sprintf('%s-01', $request['start_date']);

                    $timestamp = (new DateTime($fromDate, new DateTimeZone('Asia/Hong_Kong')))->getTimestamp();

                    $toDate = date('Y-m-d', strtotime('-1 day', strtotime('+1 month', $timestamp)));

                //}

            }

        } else {

            $fromDate = $request['start_date'];

            $toDate = $request['end_date'];

        }

        $event_timeslot_information = $this->Event_timeslot_model->listing_month_dates($course, $fromDate, $toDate, $request, '');
        foreach($event_timeslot_information as $index => $element){
            $event_timeslot_information[$index]["startdate"] = date("d-m-Y",$element['startdate']);
        }

        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

              //  'result' => $this->load->view('backend/event/partials/add_listing_month_dates', [

                    'items' =>  $event_timeslot_information

              //  ], true),

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function enroll_mode_month_listing()

    {

        $this->load->model('Course_model');

        $this->load->model('Event_timeslot_model');



        $params = $this->input->post();

        $eventId = $params['event_id'];



        $dayOfWeeks = [];

        if (!empty($params['weekday-sun']))

            array_push($dayOfWeeks, 1);

        if (!empty($params['weekday-mon']))

            array_push($dayOfWeeks, 2);

        if (!empty($params['weekday-tue']))

            array_push($dayOfWeeks, 3);

        if (!empty($params['weekday-wed']))

            array_push($dayOfWeeks, 4);

        if (!empty($params['weekday-thu']))

            array_push($dayOfWeeks, 5);

        if (!empty($params['weekday-fri']))

            array_push($dayOfWeeks, 6);

        if (!empty($params['weekday-sat']))

            array_push($dayOfWeeks, 7);



        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => $this->load->view('backend/event/partials/enroll_mode_month_listing', [

                    'items' => $this->Event_timeslot_model->listing_selected_months_day_of_weeks($eventId, $params['selected_month'], $dayOfWeeks),

                    'checked' => [

                        'weekday-mon' => $params['weekday-mon'] ?? null,

                        'weekday-tue' => $params['weekday-tue'] ?? null,

                        'weekday-wed' => $params['weekday-wed'] ?? null,

                        'weekday-thu' => $params['weekday-thu'] ?? null,

                        'weekday-fri' => $params['weekday-fri'] ?? null,

                        'weekday-sat' => $params['weekday-sat'] ?? null,

                        'weekday-sun' => $params['weekday-sun'] ?? null,

                    ]

                ], true),

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function listing_lesson_dates()

    {

        $this->load->model('Course_model');

        $this->load->model('Event_timeslot_model');



        $request = $this->input->post();

        $course = $this->Course_model->detail($request['course_id']);

        $fromDate = $request['date_from'];

        $totalLessons = $request['total_lessons'];

        //$event_timeslot_information = $this->Event_timeslot_model->listing_lesson_dates($course, $fromDate, $totalLessons, $request, '')

        echo json_encode([

            'success' => true,

            'data' => [

                'error' => 0,

                'result' => $this->load->view('backend/event/partials/add_listing_lesson_dates', [

                    'items' => $this->Event_timeslot_model->listing_lesson_dates($course, $fromDate, $totalLessons, $request, '')

                ], true),

            ],

        ], JSON_UNESCAPED_UNICODE);

    }



    public function getallids()

    {

        $ids = $this->Course_category_model->getAllIds();

        echo json_encode(['success' => true, 'data' => $ids, JSON_UNESCAPED_UNICODE]);

    }



    public function listing_selected_months()

    {

        $this->is_get();

        $params = $this->input->get();



        $eventId = $params['event_id'];

        $studentId = $params['student_id'];



        $this->load->model('Event_model');

        $item = $this->Event_model->detail($eventId);

        $d1 = $item['date_from'];

        $d2 = $item['date_to'];



        $d = $d1;

        $month = date('Y-m', $d);

        $endingMonth = date('Y-m', $d2);

        $availableSelectedMonths = [];



        while ($month <= $endingMonth) {

            array_push($availableSelectedMonths, $month);

            $d = strtotime('+1 month', $d);

            $month = date('Y-m', $d);

        }



        $this->load->model('Event_enrollment_model');

        $enrollment = $this->Event_enrollment_model->detail_by_student_event_id($eventId, $studentId);

        $hasInvoices = false;



        if (!empty($enrollment)) {

            $this->load->model('Invoicing_model');

            $invoices = $this->Invoicing_model->listing_month_invoice($eventId, $enrollment['id'], $studentId, $availableSelectedMonths);



            if (!empty($invoices)) {

                foreach ($invoices as $invoice) {

                    $pos = array_search($invoice['selected_month'], $availableSelectedMonths);

                    if ($pos !== false) {

                        $hasInvoices = true;

                        unset($availableSelectedMonths[$pos]);

                    }

                }

            }

            $availableSelectedMonths = array_values($availableSelectedMonths);

        }



        echo $this->respond([

            'months' => $availableSelectedMonths,

            'has_invoices' => $hasInvoices

        ]);

    }



    public function delete()

    {

        $this->load->model('Event_enrollment_model');



        $id = $this->input->get('event_id');

        $cannotEdit = $this->Event_enrollment_model->listing_by_event_id($id);

		$cannotEdit2 = $this->Event_enrollment_item_model->listing_in_event_id($id);

        if (count($cannotEdit) > 0 ) {

            $this->json_response('系統發現此時段或相關的時段內已有學生報名，不能刪除。', 400);

        }else{

			if(count($cannotEdit2) >0){

				 $this->json_response('系統發現此時段或相關的時段內已有學生報名，不能刪除。', 400);

			}else{

        $this->Event_model->delete($id);

        $this->Event_course_model->delete_by_event_id($id);

        $this->Event_timeslot_model->delete_by_event_id($id);

        $this->json_response('記錄已刪除。');

				}

		}

	}

}

