<?php
require_once( __DIR__. '/../lib/nusoap.php');
require_once( __DIR__.'/SiteInfo.php');
require_once( __DIR__.'/AppointmentTypes.php');
require_once( __DIR__.'/ShopInfo.php');
require_once( __DIR__.'/PractitionerInfo.php');
require_once( __DIR__.'/AppointmentSlotDetails.php');
require_once( __DIR__.'/AppointmentDetails.php');
require_once( __DIR__.'/../optician-panel/helpers/SessionManagementService.php');
require_once( __DIR__.'/../optician-panel/helpers/Util.php');

class MyOpticianWsdlService {

    private $soap_client;
    //http://87.127.13.154:899/DiaryWebService.svc
    //http://87.127.13.154:899/DiaryWebService.svc
    private $service_host;
    private $optician_id;
    private $debug_mode;
    private $session_management_service;

    public function __construct($service_host, $optician_id)
    {
        $this->service_host = $service_host;
        $this->soap_client = new nusoap_client($service_host,'wsdl');
	    $this->soap_client ->soap_defencoding = 'UTF-8';
        $this->optician_id = $optician_id;
        $this->soap_client->setDebugLevel(1);
        // $this->debug_mode = $_GET['debug_mode'] == 'true';
        $this->debug_mode = false;
        $this->session_management_service = new SessionManagementService();
    }

    public function getSiteInfo($optician_id, $password){
        if($this->session_management_service->isLoggedIn()){
            $usermodel = $this->session_management_service->getUserModel();
            return $usermodel->getSiteInfo();
        }
        $arg_params = array(
			'site'=>$optician_id,
			'password'=>$password
		);
		$result = $this->soap_client->call('GetSiteInfo',$arg_params);
        // print_r($this->soap_client->getDebug()); die;
        $siteInfo = new SiteInfo();
        $siteInfo->setAllFromStr($result['GetSiteInfoResult']);
        return $siteInfo;
    }

    public function getSiteInfoByLogin($username, $password){
        $arg_params = array(
			'login'=>$username,
			'password'=>$password
		);
		$result = $this->soap_client->call('GetSiteInfoByLogin',$arg_params);
        // echo $result['GetSiteInfoByLoginResult'];die;
        // print_r($this->soap_client->getDebug()); die;
        $siteInfo = new SiteInfo();
        $siteInfo->setAllFromStr($result['GetSiteInfoByLoginResult']);
        return $siteInfo;
    }

    public function getAppointmentTypes($site_id, $password, $siteInfo = null){
        $arg_params = array(
			'site'=>$site_id,
			'password'=>$password
		);
        $local_soap_client = $this->getLocalSoapClient($siteInfo);
		$result = $local_soap_client->call('GetAppointmentTypes',$arg_params);
        $typeInfo = explode('|',$result['GetAppointmentTypesResult']);
        $types = [];
        foreach ($typeInfo AS $type_name){
            if(empty($type_name))
                continue;
            $types[] = new AppointmentTypes($type_name);
        }
        // if(empty($types)){
        //     global $server_error, $server_error_more_details;
        //     $server_error="could not fetch appointment types";
        //     if($this->debug_mode){
        //         $server_error_more_details = $this->debug_mode ? print_r($siteInfo, true) : '';
        //         $server_error_more_details.= "<br>".$local_soap_client->getDebug();
        //     }
        //     include_once('server-error.php');
        //     die;
        // }
        return $types;
    }

    public function getShops($site_id, $password, $siteInfo = null){
        $arg_params = array(
			'site'=>$site_id,
			'password'=>$password
		);
        $local_soap_client = $this->getLocalSoapClient($siteInfo);
		$result = $local_soap_client->call('GetShops',$arg_params);
        $shopInfo = explode('|',$result['GetShopsResult']);
        $shops = [];
        foreach ($shopInfo AS $shop_details){
            if(empty($shop_details))
                continue;
            [$shop_name, $shop_address, $shop_phone] = explode(",", $shop_details);
            
            $shops[] = new ShopInfo($shop_name, $shop_address, $shop_phone);
        }
        if(empty($shops)){
            global $server_error, $server_error_more_details;
            $server_error="could not fetch shops";
            if($this->debug_mode){
                $server_error_more_details = $this->debug_mode ? print_r($siteInfo, true) : '';
                $server_error_more_details.= "Result of Shops:" . $result['GetShopsResult'];
                $server_error_more_details.= "<br>".$local_soap_client->getDebug();
            }            
            include_once('server-error.php');
            die;
        }
        return $shops;
    }

    public function getPractitioners($site_id, $password, $shop_name, $siteInfo = null){
        $arg_params = array(
			'site'=>$site_id,
			'password'=>$password,
            'shop' => $shop_name
		);
        $local_soap_client = $this->getLocalSoapClient($siteInfo);
		$result = $local_soap_client->call('GetPeople',$arg_params);

        $peopleResult = $result['GetPeopleResult'];
        if(Util::isBase64($peopleResult)) {
            $peopleResult = base64_decode($peopleResult);
        }

        $practitionerInfo = explode('|',$peopleResult);
        $practitioners = [];
        foreach ($practitionerInfo AS $name){
            if(empty($name))
                continue;
            $practitioners[] = new PractitionerInfo($name);
        }
        // if(empty($practitioners)){
        //     global $server_error, $server_error_more_details;
        //     $server_error="could not fetch practitioners";
        //     if($this->debug_mode){
        //         $server_error_more_details = $this->debug_mode ? print_r($siteInfo, true) : '';
        //         $server_error_more_details.= "<br>".$local_soap_client->getDebug();
        //     }
        //     include_once('server-error.php');
        //     die;
        // }
        return $practitioners;

    }

    public function getAppointments($site_id, $password, $shop_name, $practitioner_name, $siteInfo = null){
        $arg_params = array(
			'site'=>$site_id,
			'password'=>$password,
            'shop' => $shop_name,
            'practitioner' => $practitioner_name
		);
        $local_soap_client = $this->getLocalSoapClient($siteInfo);
		$result = $local_soap_client->call('GetAppointments',$arg_params);
        $appointmentsSlotInfo = explode('|',$result['GetAppointmentsResult']);
        // print_r("Appointment Slots: ". print_r($result, true));
        $appointmentSlots = [];
        foreach ($appointmentsSlotInfo AS $info){
            if(empty($info))
                continue;
            $appointmentSlot = new AppointmentSlotDetails();
            $appointmentSlot->setAllFromStr($info);
            $appointmentSlots[] = $appointmentSlot;
        }
        // if(empty($appointmentSlots)){
        //     global $server_error, $server_error_more_details;
        //     $server_error="could not fetch appointment slots";
        //     if($this->debug_mode){
        //         $server_error_more_details = $this->debug_mode ? print_r($siteInfo, true) : '';
        //         $server_error_more_details.= "<br>".$local_soap_client->getDebug();
        //     }
        //     include_once('server-error.php');
        //     die;
        // }
        return $appointmentSlots;
    }

    public function postNewAppointment($site_id, $appointment_slot, AppointmentDetails $appointment, $shop_name, $siteInfo = null){
        $arg_params = array(
			'site'=>$site_id,
			'appointment'=>$appointment_slot,
            'data' => $appointment->toString(),
            'shop' => $shop_name
        );

        $local_soap_client = $this->getLocalSoapClient($siteInfo);
		$result = $local_soap_client->call('PostAppointment',$arg_params);
        error_log("Response of the Appointment booking: ". print_r($result, true));
        if(strtolower($result['PostAppointmentResult'])=='success')
            return true;
        else 
            return false;
    }

    public function getDiary($site_id, $calendar_date, $shop_name, $practitioner_name, $siteInfo = null){
        $arg_params = array(
			'site'=>$site_id,
			'calendarDate'=>$calendar_date,
            'shop' => $shop_name,
            'practitioner' => $practitioner_name
		);
        // print_r($arg_params);
        $local_soap_client = $this->getLocalSoapClient($siteInfo);
		$result = $local_soap_client->call('GetDiary',$arg_params);
        $appointmentsSlotInfo = explode('|',$result['GetDiaryResult']);
        // print_r("Appointment Slots: ". print_r($result, true));
        $appointmentSlots = [];
        foreach ($appointmentsSlotInfo AS $info){
            if(empty($info))
                continue;
            $appointmentSlot = new AppointmentSlotDetails();
            $appointmentSlot->setAllFromStr($info);
            $appointmentSlots[] = $appointmentSlot;
        }
        return $appointmentSlots;
    }

    private function getLocalSoapClient($siteInfo){
        $local_soap_client = null;
        if($siteInfo == null){
            $local_soap_client = $this->soap_client;
        } else {
            $local_soap_client = new nusoap_client($siteInfo->getWebserviceAddress(),'wsdl');
            $local_soap_client ->soap_defencoding = 'UTF-8';
            $local_soap_client->setDebugLevel(1);
        }
        return $local_soap_client;
    }


}
?>