<?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 Bookinglist extends CI_Controller {

	/**
	 * 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
	 */

        // Hardcoded Calendar Schedule Event Settings
          private $fromTime = '06:00';
          private $toTime = '20:00';

          // Storage
          private $data = [];
          private $dates = [];    

         var $menu;
         var $contactus;
        public function __construct()
        {
            parent::__construct();
            $this->load->library(array('session'));
            // $this->load->model('Section', 'section_model');
            // $this->menu = $this->section_model->buildTopMenuItem();
            // $this->breadcrumbs = [];
            // $this->load->model('ContactDetails', 'contactdetails_model');
            // $this->contactus = $this->contactdetails_model->getContactus();

            $this->load->model('FrontendUser', 'frontenduser_model');

            $this->load->model('Folder', 'folder_model');
           
            $this->load->model('FrontRightModel', 'frontright_model');
            $this->load->model('EmployeeGroupModel', 'employeegroup_model');
            $this->load->model('ShopModel', 'shop_model');
            $this->load->model('EmployeeModel', 'employee_model');
            $this->load->model('CustomerModel', 'customer_model');
             $this->load->model('LivingareaModel', 'livingarea_model');
             $this->load->model('ServicesModel', 'services_model');

             $this->load->model('RoomModel', 'room_model');
             $this->load->model('BookingModel', 'booking_model');
            if (!$this->session->userdata('logged_in'))
            { 
                redirect('/at-cms/login');
            }
    
            
            $this->load->helper('form');
            
        }

        public function index()
	{

        $userid = $this->session->userdata('userid');
        // $user_data = $this->session->userdata('USER_ID');

        if(empty($userid)){
            // $this->load->view('test1');
            redirect('/at-cms/login', 'refresh');
        }
        $this->load->helper('url');
        //testing
        // $currentURL = current_url(); //for simple URL
        // $params = $_SERVER['QUERY_STRING']; //for parameters
        // $fullURL = $currentURL . '?' . $params; //full URL with parameter
        //end testing


        //for pagination    
         // or you can autoload it in config

// print base_url($this->uri->uri_string());
        // $config["base_url"] = base_url() . "adminmain/index/";
        $config["base_url"] =  base_url() ."adminmain/index";
        // $config["total_rows"] = $this->Countries->record_count();
        
        // $config["total_rows"] = $this->frontenduser_model->record_count();
        
        $config["uri_segment"] = 3;
        $config["per_page"] = 10;
        $config["page"] = 0;

        // $page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;

        $this->load->helper('url');
        if(!empty($this->uri->segment(3))){
            $page = $this->uri->segment(3);  
        }
        else{
            $page = $config["page"];
        }
        // get 11
        if(!empty($this->uri->segment(4))){
            $perpage = $this->uri->segment(4);  
        }
        else{
            $perpage = $config["per_page"];
        }
        // $perpage = $this->uri->segment(4);

        // $choice = $config["total_rows"] / $perpage;
        // $config["num_links"] = round($choice);
        // $config["num_links"] = ceil($choice);
        
        //end for pagination

        // $this->load->view('welcome_message');
        $data = array(
                'title' => 'My Title',
                'heading' => 'My Heading',
                'message' => 'My Message'
            );        
        // $data['total_rows']=$config["total_rows"];
        $data['page']=$page;
        $data['perpage']=$perpage;
        // $data['num_links'] = $config["num_links"];
        // $data['record']=$this->frontenduser_model->getAdmindata($perpage, $page);
        $data['base_url'] =$config["base_url"];
        $data['fullName'] = $this->session->userdata('fullName');  

        
        //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['rooms']= $this->customer_model->getAllCustomer($this->session->userdata('currentshop'));
         $data['customers']= $this->customer_model->getAllCustomer();

         //get booking list
         $content = './uploads/1576452468-tc.ics';

         $calendar = $this->parseICS($content);   
         $bookings=$this->booking_model->getAllBooking();

         $bookingdata=array();

         date_default_timezone_set('Asia/Hong_Kong'); 


         $count=0;
         foreach ($bookings as $bookingrow) {
           $bookinglist=array();
           $bookinglist['id']=$bookingrow->id;
           $bookinglist['starttime']= DateTime::createFromFormat('Y-m-d H:i', $bookingrow->startdate." ".$bookingrow->starttime);
           $starttimestamp =$bookinglist['starttime']->getTimestamp();
           $weekday = date( "w", $starttimestamp);
           $weeklist = array('日', '一', '二', '三', '四', '五', '六'); 
           $bookinglist['weekdata']=$weeklist[$weekday];

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


           //get booking items 
            $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) {

            $bookinglist['bookingitemsname']=$bookingitemsname;
            $bookinglist['bookingitemscode']=$bookingitemscode;

           //end get booking items


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



           $bookinglist['roomname']=$this->room_model->getRoomName($bookingrow->room_id);
           $bookinglist['customersrow']=$this->customer_model->getCustomerData($bookingrow->user_id);
           $bookinglist['create_time']=$bookingrow->create_time;
           $bookinglist['in_time']=$this->booking_model->getIntime($bookingrow->id);
           $bookinglist['out_time']=$this->booking_model->getOuttime($bookingrow->id);
           array_push($bookingdata,$bookinglist);
         }//foreach ($bookings as $bookingrow) {
         //end get booking list


             $data['bookingdata']=$bookingdata;


        $this->load->view('/admin/bookinglistview',$data);
        // $contactusdata = $this->contactdetails_model->getContactus();
        //     $this->breadcrumbs[] = array (
        //         'label' => '聯絡我們',
        //         'link' => ''
        //     );
        //     $this->twig->display('main', array(
        //         'path' => array(
        //             'vendor' => $this->config->item('vendor_path'),
        //             'script' => $this->config->item('script_path'),
        //             'css' => $this->config->item('css_path'),
        //             'image' => $this->config->item('image_path')
        //         ),
        //         'breadcrumbs' => $this->breadcrumbs,
        //         'menus' => $this->menu,
        //         'contactusdata'=>$contactusdata,
        //         'session' => 'contact',
        //         'contactus' => $this->contactus,
        //         'page' => 'index'
        //     ));
        }
        public function add(){
            $userid = $this->session->userdata('userid');
            // $user_data = $this->session->userdata('USER_ID');

            if(empty($userid)){
                // $this->load->view('test1');
                redirect('/at-cms/login', 'refresh');
            }
            $this->load->helper('url');
            $config["base_url"] =  base_url() ."adminmain/index";
        // $config["total_rows"] = $this->Countries->record_count();
        
        // $config["total_rows"] = $this->frontenduser_model->record_count();
        
        $config["uri_segment"] = 3;
        $config["per_page"] = 10;
        $config["page"] = 0;

        // $page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;

        $this->load->helper('url');
        if(!empty($this->uri->segment(3))){
            $page = $this->uri->segment(3);  
        }
        else{
            $page = $config["page"];
        }
        // get 11
        if(!empty($this->uri->segment(4))){
            $perpage = $this->uri->segment(4);  
        }
        else{
            $perpage = $config["per_page"];
        }
        // $perpage = $this->uri->segment(4);

        // $choice = $config["total_rows"] / $perpage;
        // $config["num_links"] = round($choice);
        // $config["num_links"] = ceil($choice);
        
        //end for pagination

        // $this->load->view('welcome_message');
        $data = array(
                'title' => 'My Title',
                'heading' => 'My Heading',
                'message' => 'My Message'
            );        
        // $data['total_rows']=$config["total_rows"];
        $data['page']=$page;
        $data['perpage']=$perpage;
        // $data['num_links'] = $config["num_links"];
        // $data['record']=$this->frontenduser_model->getAdmindata($perpage, $page);
        $data['base_url'] =$config["base_url"];
        $data['fullName'] = $this->session->userdata('fullName'); 

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

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

        //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['pagemethod']='add';
        $data['currentshop']= $this->session->userdata('currentshop');
        $data['customercode']=$this->shop_model->getShopcode($this->session->userdata('currentshop'));
        $data['shopimprove']=$this->shop_model->getSkinImprove();

        $data['firstzone']=$this->livingarea_model->getFirstZone();

        //end 



        
            $this->load->view('/admin/customeraddview',$data);
        }
        public function edit(){
          
            $userid = $this->session->userdata('userid');
            // $user_data = $this->session->userdata('USER_ID');

            if(empty($userid)){
                // $this->load->view('test1');
                redirect('/at-cms/login', 'refresh');
            }
            $this->load->helper('url');
            $config["base_url"] =  base_url() ."adminmain/index";
        // $config["total_rows"] = $this->Countries->record_count();
        
        // $config["total_rows"] = $this->frontenduser_model->record_count();
        
        $config["uri_segment"] = 3;
        $config["per_page"] = 10;
        $config["page"] = 0;

        // $page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;

        $this->load->helper('url');
        if(!empty($this->uri->segment(3))){
            $page = $this->uri->segment(3);  
        }
        else{
            $page = $config["page"];
        }
        // get 11
        if(!empty($this->uri->segment(4))){
            $perpage = $this->uri->segment(4);  
        }
        else{
            $perpage = $config["per_page"];
        }
        // $perpage = $this->uri->segment(4);

        // $choice = $config["total_rows"] / $perpage;
        // $config["num_links"] = round($choice);
        // $config["num_links"] = ceil($choice);
        
        //end for pagination

        // $this->load->view('welcome_message');
        $data = array(
                'title' => 'My Title',
                'heading' => 'My Heading',
                'message' => 'My Message'
            );        
        // $data['total_rows']=$config["total_rows"];
        $data['page']=$page;
        $data['perpage']=$perpage;
        // $data['num_links'] = $config["num_links"];
        // $data['record']=$this->frontenduser_model->getAdmindata($perpage, $page);
        $data['base_url'] =$config["base_url"];
        $data['fullName'] = $this->session->userdata('fullName'); 

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

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

        //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['pagemethod']='add';
        $data['currentshop']= $this->session->userdata('currentshop');
        $data['customercode']=$this->shop_model->getShopcode($this->session->userdata('currentshop'));
        $data['shopimprove']=$this->shop_model->getSkinImprove();

        $data['firstzone']=$this->livingarea_model->getFirstZone();

        //end 

        //get customer data
            $data['pagemethod']='edit';
            $id = $this->uri->segment(4);
            $data['customerdetails']=$this->customer_model->getCustomer($id);
            $data['customerdetailslivingarea']=$this->customer_model->getCustomerLivingArea($id);
            $data['customerdetailsPromotionCode']=$this->customer_model->getCustomerPromotionCode($id);
            $data['customerdetailsSkinImprove']=$this->customer_model->getCustomerSkinImprove($id);

            $userid = $this->session->userdata('userid');

        //end get customer data
        
        
        
            $this->load->view('/admin/customeraddview',$data);
        
        }
        public function dispay(){
            echo "1";
            $this->load->helper('url');
        $page = $this->uri->segment(3);  // get 11
        $perpage = $this->uri->segment(4);
        echo "page";
        echo $page;
        echo "perpage";
        echo $perpage;
        }

        public function changeshop(){
             $this->load->library('session');

            $shopid=$this->input->post('shopid');
            // echo $searchingword;

            //clearing $searchingword
            $shopid=trim($shopid);
            //end clearing $searchingword

            $this->session->set_userdata('currentshop', $shopid);    
            $this->index();    
        }
        public function detail(){

                $userid = $this->session->userdata('userid');
        // $user_data = $this->session->userdata('USER_ID');

        if(empty($userid)){
            // $this->load->view('test1');
            redirect('/at-cms/login', 'refresh');
        }
        $this->load->helper('url');
        //testing
        // $currentURL = current_url(); //for simple URL
        // $params = $_SERVER['QUERY_STRING']; //for parameters
        // $fullURL = $currentURL . '?' . $params; //full URL with parameter
        //end testing


        //for pagination    
         // or you can autoload it in config

// print base_url($this->uri->uri_string());
        // $config["base_url"] = base_url() . "adminmain/index/";
        $config["base_url"] =  base_url() ."adminmain/index";
        // $config["total_rows"] = $this->Countries->record_count();
        
        // $config["total_rows"] = $this->frontenduser_model->record_count();
        
        $config["uri_segment"] = 3;
        $config["per_page"] = 10;
        $config["page"] = 0;

        // $page = ($this->uri->segment(3))? $this->uri->segment(3) : 0;

        $this->load->helper('url');
        if(!empty($this->uri->segment(3))){
            $page = $this->uri->segment(3);  
        }
        else{
            $page = $config["page"];
        }
        // get 11
        if(!empty($this->uri->segment(4))){
            $perpage = $this->uri->segment(4);  
        }
        else{
            $perpage = $config["per_page"];
        }
        // $perpage = $this->uri->segment(4);

        // $choice = $config["total_rows"] / $perpage;
        // $config["num_links"] = round($choice);
        // $config["num_links"] = ceil($choice);
        
        //end for pagination

        // $this->load->view('welcome_message');
        $data = array(
                'title' => 'My Title',
                'heading' => 'My Heading',
                'message' => 'My Message'
            );        
        // $data['total_rows']=$config["total_rows"];
        $data['page']=$page;
        $data['perpage']=$perpage;
        // $data['num_links'] = $config["num_links"];
        // $data['record']=$this->frontenduser_model->getAdmindata($perpage, $page);
        $data['base_url'] =$config["base_url"];
        $data['fullName'] = $this->session->userdata('fullName');  

        
        //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['rooms']= $this->room_model->getAllRoom($this->session->userdata('currentshop'));
         $data['customers']= $this->customer_model->getAllCustomer();

         //get booking list
         $content = './uploads/1576452468-tc.ics';

         $calendar = $this->parseICS($content);   
         $bookings=$this->booking_model->getAllBooking();

         $bookingdata=array();

         date_default_timezone_set('Asia/Hong_Kong'); 


         $count=0;
         foreach ($bookings as $bookingrow) {
           $bookinglist=array();
           $bookinglist['id']=$bookingrow->id;
           $bookinglist['starttime']= DateTime::createFromFormat('Y-m-d H:i', $bookingrow->startdate." ".$bookingrow->starttime);
           $starttimestamp =$bookinglist['starttime']->getTimestamp();
           $weekday = date( "w", $starttimestamp);
           $weeklist = array('日', '一', '二', '三', '四', '五', '六'); 
           $bookinglist['weekdata']=$weeklist[$weekday];

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


           //get booking items 
            $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) {

            $bookinglist['bookingitemsname']=$bookingitemsname;
            $bookinglist['bookingitemscode']=$bookingitemscode;

           //end get booking items


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



           $bookinglist['roomname']=$this->room_model->getRoomName($bookingrow->room_id);
           $bookinglist['customersrow']=$this->customer_model->getCustomerData($bookingrow->user_id);
           $bookinglist['create_time']=$bookingrow->create_time;
           $bookinglist['in_time']=$this->booking_model->getIntime($bookingrow->id);
           $bookinglist['out_time']=$this->booking_model->getOuttime($bookingrow->id);
           array_push($bookingdata,$bookinglist);
         }//foreach ($bookings as $bookingrow) {
         //end get booking list

                $data['therapist']=$this->employee_model->gettherapist($this->session->userdata('currentshop'));
              //get services data
               $data['pagemethod']='edit';
               $id = $this->uri->segment(4);
               $data['bookingdetails']=$this->booking_model->getBookingByid($id);
               $userid = $this->session->userdata('userid');  
            //end get services data    



             $data['bookingdata']=$bookingdata;


        $this->load->view('/admin/bookinglistedit',$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;
  }

   /**
   * 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;
  }

}