<?php

use Carbon\Carbon;
use Louis1021\ICalendar\helpers\SG_iCal_Query;
use Louis1021\ICalendar\SG_iCalReader;

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

class Booking extends CI_Controller
{
  // Hardcoded Calendar Schedule Event Settings
  private $fromTime = '06:00';
  private $toTime = '20:00';

  // Storage
  private $data = [];
  private $dates = [];
  public function __construct()
        {
            parent::__construct();
            $this->load->library(array('session'));

            $this->load->model('CustomerModel', 'customer_model');

            $this->load->model('RoomModel', 'room_model');
            $this->load->model('EmployeeModel', 'employee_model');
            $this->load->model('BookingModel', 'booking_model');
            
  }

  public function index()
  {
    /**
     * Add CSS / JS
     * @see https://www.tutorialspoint.com/codeigniter/codeigniter_adding_js_css.htm
     */
    $this->load->helper('url');

    /**
     * Since read_file is deprecated, use file_get_contents() instead
     * The dot means the current path (root path)
     */
    $content = './uploads/1576452468-tc.ics';

    $calendar = $this->parseICS($content);

    //add booking
      $bookings=$this->booking_model->getAllBooking();
      // addEvent($id, $date, $duration, $resource, $start, $end, $allDay, $category, $content = null)
      
      date_default_timezone_set('Asia/Hong_Kong');  
      
      foreach ($bookings as $bookingrow) {
          // $starttime= DateTime::createFromFormat("Y-m-d G:i", $bookingrow->startdate." ".$bookingrow->starttime);
           $starttime = DateTime::createFromFormat('Y-m-d H:i', $bookingrow->startdate." ".$bookingrow->starttime);

           // DateTime::createFromFormat('Y/m/d H:i:s','2010/08/09 07:47:00')->getTimestamp()
           // $date = DateTime::createFromFormat('Y-m-d', '2009-02-15');
           // var_dump($bookingrow->startdate." ".$bookingrow->starttime);
           // var_dump($starttime);
           $starttimestamp =$starttime->getTimestamp();

          // $endtime= DateTime::createFromFormat("Y-m-d G:i", $bookingrow->startdate." ".$bookingrow->endtime);
          $endtime = DateTime::createFromFormat('Y-m-d H:i',$bookingrow->startdate." ".$bookingrow->endtime);
          $endtimestamp =$endtime->getTimestamp();

           $bookingitemsname="";
           $bookingitemscode="";
           $bookingitems=$this->booking_model->getBookingItem($bookingrow->id);
           
           
           $count=0;
           foreach ($bookingitems as $bookingitemsrow) {

             $bookingitemsname=$bookingitemsname.$bookingitemsrow->name;
             $bookingitemscode=$bookingitemscode.$bookingitemsrow->code;
             if($count!=0){
              $bookingitemscode=$bookingitemscode."<br>";
              $bookingitemsname=$bookingitemsname."<br>";
             } 
             $count=$count+1;
           }//foreach ($bookingitems as $bookingitemsrow) {

          // $weekday  = date('w', strtotime($bookingrow->startdate));
          $weekday = date( "w", $starttimestamp);
          $weeklist = array('日', '一', '二', '三', '四', '五', '六');    

          //get therapist name
          $pic_1name="";
          if(!empty($bookingrow->pic_1)){
            $pic_1name=$this->employee_model->getEmpolyeeName($bookingrow->pic_1);
          }
          $pic_2name="";
          if(!empty($bookingrow->pic_2)){  
              $pic_2name=$this->employee_model->getEmpolyeeName($bookingrow->pic_2);
          }  
          //end get therapist name

          //get room name
          $roomname=$this->room_model->getRoomName($bookingrow->room_id);
          $customersrow=$this->customer_model->getCustomerData($bookingrow->user_id);
          //end get room name

          $displayformat='<div class="course">
                          <div class="course-details" data-id="'.$bookingrow->id.'" data-bgcolor="#dddddd" data-teachers="annie" data-students="Melody cheung 66002661">
                              <div class="title">id:'.$bookingrow->id.'<br>'.$bookingitemsname.'</div><div class="weekdays">('.$weeklist[$weekday].')</div>
                              <div class="code">'.$bookingitemscode.'</div>
                          </div>
                              <div class="main-teachers"><a data-id="31"><span class="chi_name">'.$pic_1name.' '.$pic_2name.'</span></a></div>
                              <div class="room"><a data-id="1"><span class="name">'.$roomname.'</span></a></div>
                              <div class="students"><a data-id="19" W><span class="chi_name" W>'.$customersrow->chi_name.' '.$customersrow->mobile.'</span></a></div>
                              <div class="students-attend-stat"><span p>0</span>+<span a>0</span>+<span w>1</span>/1</div>
                          </div>
                          ';
        $this->addEvent($bookingrow->id,$bookingrow->startdate,60,$roomname,$starttimestamp,$endtimestamp,0,"course",$displayformat);
      }//foreach ($variable as $key => $value) {
      
    //end add booking

    // $this->load->view('/admin/welcome_message2', [
    //   '_events' => $calendar->json(),
    //   // resource is a set of labels, the calendar.js will handle it
    //   '_resources' => json_encode(['Room A', 'Room B', 'Room C', 'Room D', 'Room E', 'Room F']),
    // ]);

       //added shop
        // $data['employeegroup']=$this->employeegroup_model->getAllEmployeeGroup();

        $data['shop']=$this->shop_model->getAllShop();
        // $data['employeeincometype']=$this->employee_model->getEmployeeIncomeType();

        // $data['employee'] =$this->employee_model->getAllEmpolyee();


         //set default current shop id,

         //it may be delete in later
        if(empty($this->session->userdata('currentshop'))){
            $this->session->set_userdata('currentshop', 1); 
        }
        //end 

        $data['currentshop']= $this->session->userdata('currentshop');
        //ended added shop  

        $data['_events']=  $calendar->json();
        // $data['_resources']=  json_encode(['Room A', 'Room B', 'Room C', 'Room D', 'Room E', 'Room F']);
        $data['_resources']=  json_encode(['Room A', 'Room B', 'Room C', 'Room D', 'Room E']);
        $data['fullName']=  $this->session->userdata('fullName');
    //  $this->load->view('/admin/welcome_message2', [
    //   '_events' => $calendar->json(),
    //   // resource is a set of labels, the calendar.js will handle it
    //   '_resources' => json_encode(['Room A', 'Room B', 'Room C', 'Room D', 'Room E', 'Room F']),
    //   'fullName' => $this->session->userdata('fullName'),
    // ]);

      $this->load->view('/admin/welcome_message2', $data);
  }

  protected function parseICS($path, $startdate = null, $enddate = null)
  {
    $ical = new SG_iCalReader($path);
    $query = new SG_iCal_Query();

    $evts = $ical->getEvents();
    //$evts = $query->Between($ical,strtotime('20100901'),strtotime('20101131'));

    $data = array();
    if ($evts) {
      foreach ($evts as $id => $ev) {

        $jsEvt = array(
          "id" => ($id + 1),
          "title" => $ev->getProperty('summary'),
          "start" => $this->getRefinedFromTime($ev->getStart()),
          "end"   => $this->getRefinedToTime($ev->getEnd() - 1),
          "allDay" => $ev->isWholeDay(),
          "category" => "publicholiday"
        );

        if (isset($ev->recurrence)) {
          $count = 0;
          $start = $ev->getStart();
          $freq = $ev->getFrequency();
          if ($freq->firstOccurrence() == $start)
            $this->data[] = $jsEvt;
          $this->dates[] = Carbon::createFromTimestamp($start)->format('Y-m-d');
          while (($next = $freq->nextOccurrence($start)) > 0) {
            if (!$next or $count >= 1000) break;
            $count++;
            $start = $next;
            $jsEvt["start"] = $start;
            $jsEvt["end"] = $start + $ev->getDuration() - 1;

            $evtIsoDate = Carbon::createFromTimestamp($start)->format('Y-m-d');

            if ($startdate && $enddate) {
              if ($startdate >= $evtIsoDate && $evtIsoDate <= $enddate) {
                $this->data[] = $jsEvt;
                $this->dates[] = $evtIsoDate;
              }
            } else {
              $this->data[] = $jsEvt;
              $this->dates[] = $evtIsoDate;
            }
          }
        } else {
          $start = $jsEvt['start'];
          $evtIsoDate = Carbon::createFromTimestamp($start)->format('Y-m-d');

          if ($startdate && $enddate) {
            if ($startdate >= $evtIsoDate && $evtIsoDate <= $enddate) {
              $this->data[] = $jsEvt;
              $this->dates[] = $evtIsoDate;
            }
          } else {
            $this->data[] = $jsEvt;
            $this->dates[] = $evtIsoDate;
          }
        }
      }
    }

    //echo(date('Ymd\n',$data[0][start]));
    //echo(date('Ymd\n',$data[1][start]));
    //dump_t($data);

    return $this;
  }

  protected function addEvent($id, $date, $duration, $resource, $start, $end, $allDay, $category, $content = null)
  {
    $this->data[] = compact('id', 'date', 'duration', 'resource', 'start', 'end', 'allDay', 'category', 'content');
    return $this;
  }

  protected function json()
  {
    $events = json_encode($this->data);

    return $events;
  }

  protected function holidayJson()
  {
    return json_encode($this->dates);
  }

  /**
   * TODO: 
   * fromTime from database
   * 單數 hour 時減一
   *
   * @param int $unixDateTime
   * @return int
   */
  protected function getRefinedFromTime($unixDateTime)
  {
    list($hour, $minute) = explode(':', $this->fromTime);
    return Carbon::createFromTimestamp($unixDateTime)->setTime($hour, $minute)->timestamp;
  }

  /**
   * TODO: 
   * toTime from database
   * 單數 hour 時加一
   *
   * @param int $unixDateTime
   * @return int
   */
  public function getRefinedToTime($unixDateTime)
  {
    list($hour, $minute) = explode(':', $this->toTime);
    return Carbon::createFromTimestamp($unixDateTime)->setTime($hour, $minute)->timestamp - 1;
  }

  /**
   * Index Page for this controller.
   *
   * Maps to the following URL
   * 		http://example.com/index.php/welcome
   *	- or -
   * 		http://example.com/index.php/welcome/index
   *	- or -
   * Since this controller is set as the default controller in
   * config/routes.php, it's displayed at http://example.com/
   *
   * So any other public methods not prefixed with an underscore will
   * map to /index.php/welcome/<method_name>
   * @see https://codeigniter.com/user_guide/general/urls.html
   */
  public function indexOriginal()
  {
    $this->load->view('welcome_message');
  }

  //added page
  public function add(){
    $userid = $this->session->userdata('userid');
    $data['fullName'] = $this->session->userdata('fullName');
    $data['rooms']= $this->room_model->getAllRoom($this->session->userdata('currentshop'));
     $data['customers']=$this->customer_model->getAllCustomerOrderByid();
     $data['therapist']=$this->employee_model->gettherapist();
     $this->load->view('/admin/bookingaddview',$data);

  }
  //end added page
}
