<?php
class ModelExtensionModuleBooking extends Model {
    public function post($data) {
        $this->load->model('setting/setting');
        $this->load->model('tool/sinc');
        $login             = $this->config->get('booking_login');
        $pass              = $this->config->get('booking_pass');
        $login_url         = 'https://admin.booking.com/';
        $set_url           = 'https://admin.booking.com/hotel/hoteladmin/extranet_ng/manage/json/calendarsavedates.json?';
        $ref_url           = 'https://admin.booking.com/hotel/hoteladmin/extranet_ng/manage/calendar.html?';
        $login_var_name    = 'loginname';
        $password_var_name = 'password';
        $user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; (R1 1.5))";
        $user_cookie_file  = DIR_CACHE . 'cookie_ext.txt';
        $request = [];
		
        if (!$ch = curl_init())
        {
            echo curl_error($ch);
            exit;
        }


        $post_fields = "$login_var_name=$login&$password_var_name=$pass";

        curl_setopt($ch, CURLOPT_URL, $login_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        curl_setopt($ch, CURLOPT_REFERER, $login_url);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $user_cookie_file);
        curl_setopt($ch, CURLOPT_COOKIEJAR,  $user_cookie_file);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

        $content = curl_exec($ch);

        curl_close($ch);

        $pattern = '/data-ses="(.[0-9a-zA-Z]*)"/is';
        preg_match($pattern, $content, $res);

        if (isset($res[1])){
            echo '<br>start booking ',count($data['apartamets']);
            $log = new Log('sync_to_booking.log');
			
            $message = '---------------BOOKING------------------';
            $log->write($message);

            foreach ($data['apartamets'] as $rooms) {

                if (isset($rooms['send1_ok'])){
                    $params = 'room_id='. $rooms['room_id']['booking'] .'&lang=xu&ses='.$res[1].'&hotel_id='.$login;

                    if (!$ch = curl_init())
                    {
                        echo curl_error($ch);
                        exit;
                    }
                    $post_fields = "dates=" . $rooms['date'] . "&price=" . $rooms['price'] . "&rooms_to_sell=" . $rooms['room_to_sell'] . "";

                    $message = 'room_id='. $rooms['room_id']['booking'] ." dates=" . $rooms['date'] . " price=" . $rooms['price'] . " rooms_to_sell=" . $rooms['room_to_sell'];
                    $log->write($message);

                    curl_setopt($ch, CURLOPT_URL, $set_url.''.$params);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    curl_setopt($ch, CURLOPT_VERBOSE, 1);
                    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
                    curl_setopt($ch, CURLOPT_REFERER, $ref_url.''.$params);
                    curl_setopt($ch, CURLOPT_COOKIEFILE, $user_cookie_file);
                    curl_setopt($ch, CURLOPT_COOKIEJAR,  $user_cookie_file);
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

                    $content = curl_exec($ch);

                    $request[] = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
                    curl_close($ch);


                    echo '.';

                    if(isset($rooms['room_to_sell'])){
                        $post_fields = "form=" . $rooms['date'] ."&until=".$rooms['date'];

                        $url='https://admin.booking.com/hotel/hoteladmin/extranet_ng/manage/json/calendarloaddates.json?room_id='.$rooms['room_id']['booking'].'&hotel_id='.$login.'&lang=xu&ses='.$res[1].'&from='.$rooms['date'].'&until='.$rooms['date'];
                        $refer='https://admin.booking.com/hotel/hoteladmin/extranet_ng/manage/calendar.html?room_id='.$rooms['room_id']['booking'].'&hotel_id='.$login.'&ses='.$res[1].'&lang=xu';
                        if (!$ch = curl_init()){
                            echo curl_error($ch);
                            exit;
                        }

                        curl_setopt($ch, CURLOPT_URL,$url);
                        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                        curl_setopt($ch, CURLOPT_VERBOSE, 1);
                        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
                        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
                        curl_setopt($ch, CURLOPT_REFERER, $refer);
                        curl_setopt($ch, CURLOPT_COOKIEFILE, $user_cookie_file);
                        curl_setopt($ch, CURLOPT_COOKIEJAR,  $user_cookie_file);
                        curl_setopt($ch, CURLOPT_POST, 1);
                        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

                        $content = curl_exec($ch);
						//echo $content;
                        curl_close($ch);

                        $dom = new DOMDocument();
                        libxml_use_internal_errors(true);
                        $dom->loadHTML($content);
                        libxml_use_internal_errors(false);
                        $xdom = new DOMXPath($dom);
                        $arr=[];
						$b_dost=true;
						$b_dost_tex='';
                         $page_links = $xdom->query('//span[contains(@class, "date-rooms-count")]');
						if($page_links->length){
							$el = $page_links->item(0);
							
						
							$b_dost_tex = $el->nodeValue;
							$b_dost = in_array($b_dost_tex,['Closed','Fully booked'])?1:0;
						}
						$page_links = $xdom->query('//span[@class="date-price-formatted"]');
						$b_cost = 0;
						if ($page_links->length) {
							$el = $page_links->item(0);
							$b_cost=preg_replace("/[^0-9]/", '', $el->nodeValue);
						}
					
						
						$mess_sinc="Цена на букинге: ".$b_cost.", Цена в бд:".$rooms['price'].", Статус в букинге:".$b_dost_tex.'='.$b_dost.", Статус у нас:".$rooms['room_to_sell'].", Дата:".$rooms['date'].", product_id:".$rooms['product_id'];
						echo $mess_sinc;
						
						echo '=====<br>';
						echo $rooms['room_to_sell'].'--------'.is_null($b_dost).'<br>';
						echo ($rooms['room_to_sell']<=0 AND $b_dost).'<br>';
						echo ($rooms['room_to_sell']<=0 AND !$b_dost).'<br>';
						echo (!$b_dost or !isset($b_dost)).'<br>';
						$chek=0;
						if($rooms['room_to_sell']<=0 AND $b_dost){
							echo 2;	$chek=2;
							$this->model_tool_sinc->send_ok($rooms['product_id'], $rooms['date'], 1,2);
						}elseif($rooms['room_to_sell']<=0 AND !$b_dost){
							echo 1;$chek=1;
							$this->model_tool_sinc->send_ok($rooms['product_id'], $rooms['date'], 1,1);
						}elseif(!isset($b_dost)){
							echo 3;
							
							$chek=3;
							$this->model_tool_sinc->send_ok($rooms['product_id'], $rooms['date'], 1,3);
						}elseif($rooms['price']!=$b_cost){
							echo 4;$chek=4;				
							$this->model_tool_sinc->send_ok($rooms['product_id'], $rooms['date'], 1,4);
						}else{
							echo 1;$chek=1;
							$this->model_tool_sinc->send_ok($rooms['product_id'], $rooms['date'], 1,1);
						}
						file_put_contents(DIR_LOGS.'status_sync_booking.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).$mess_sinc.' Статус отправки:'.$chek,FILE_APPEND | LOCK_EX);
                    }
                }
            }
        }

        return $request;
    }

    public function login() {
        $this->load->model('setting/setting');
        $login             = $this->config->get('booking_login');
        $pass              = $this->config->get('booking_pass');
        $login_url         = 'https://admin.booking.com/';
        $login_var_name    = 'loginname';
        $password_var_name = 'password';
        $user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; (R1 1.5))";
        $user_cookie_file  = DIR_CACHE . 'cookie_ext.txt';
        $request = [];

        if (!$ch = curl_init())
        {
            echo curl_error($ch);
            exit;
        }
        $post_fields = "$login_var_name=$login&$password_var_name=$pass";

        curl_setopt($ch, CURLOPT_URL, $login_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        curl_setopt($ch, CURLOPT_REFERER, $login_url);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $user_cookie_file);
        curl_setopt($ch, CURLOPT_COOKIEJAR,  $user_cookie_file);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);

        $content = curl_exec($ch);


        curl_close($ch);

        $pattern = '/data-ses="(.[0-9a-zA-Z]*)"/is';
        preg_match($pattern, $content, $res);

        if (isset($res[1])) {
            return $res[1];
        } else {
            return false;
        }
    }

    public function getReferens($ses, $res) {
        $this->load->model('setting/setting');
        $login             = $this->config->get('booking_login');
        $pass              = $this->config->get('booking_pass');
        $login_var_name    = 'loginname';
        $password_var_name = 'password';
        $user_agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; (R1 1.5))";
        $user_cookie_file  = DIR_CACHE . '/cookie_ext.txt';

        $get_url = 'https://admin.booking.com/hotel/hoteladmin/extranet_ng/manage/booking.html?lang=en&ses=' . $ses . '&hotel_id=' . $login . '&res_id='.$res['referens_id'];
        if (!$ch = curl_init())
        {
            echo curl_error($ch);
            exit;
        }

        curl_setopt($ch, CURLOPT_URL, $get_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        curl_setopt($ch, CURLOPT_REFERER, $get_url);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $user_cookie_file);
        curl_setopt($ch, CURLOPT_COOKIEJAR,  $user_cookie_file);



        $content = curl_exec($ch);
    



        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML($content);
        libxml_use_internal_errors(false);
        $xdom = new DOMXPath($dom);
        $arr=[];

        $page_links = $xdom->query('//h2[@class="title_select_phone_number"]/text()');

        if ($page_links->length) {
			
				 file_put_contents('admin/booking_get_sms.html',$content);
				return false;
			
        } else {
            $page_links = $xdom->query('//li[contains(@class, "reservation-info-item")]');

            if ($page_links->length) {
                for ($i = $page_links->length; --$i >= 0;) {
                    $el = $page_links->item($i);
                    if(trim($el->nodeValue)!=""){
                        list($key, $val) = explode(':', $el->nodeValue);
                        if(!empty($key) AND !empty($val) and trim($val)!=''){
                            $arr[trim($key)]=$val;
                        }
                    }
                }
            }

            $page_links = $xdom->query('//strong[contains(@class, "room_row__number")]');
            if ($page_links->length) {
                for ($i = 1; --$i >= 0;) {
                    $el = $page_links->item($i);
                    if(trim($el->nodeValue)!=""){
                        preg_match("`#([\w]*)`", $el->nodeValue, $val);
                        $arr['room_id']=$val[1];

                    }
                    break;
                }
            }

            $page_links = $xdom->query('//li[contains(@class, "reservation-room-info-item pull-left")]/text()');

            if ($page_links->length) {
                for ($i = $page_links->length; --$i >= 0;) {
                    $el = $page_links->item($i);
                    if(trim($el->nodeValue)!=""){

                        if($i==1){
                            $arr['date_in']=$el->nodeValue;

                        }
                        if($i==3){
                            $arr['date_out']=$el->nodeValue;
                        }

                    }

                }
            }



            $ress = array();

            $request[] = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);

            curl_close($ch);
            if (!empty($arr)) {
                $return = [
                    'name' => mb_convert_encoding($arr['Guest name'],"Windows-1252"),
                    'count_guest' => (int)$arr['Total guests'],
                    'count_room' => $arr['Total rooms booked'],
                    'room_id' => $arr['room_id'],
                    'date_in' => strftime('%F',strtotime($arr['date_in'])),
                    'date_out' => strftime('%F',strtotime($arr['date_out'])),
                    'price' => (int)$arr["Total reservation price"]
                ];
            } else {
                $return = false;
            }
            return $return;
        }

    }
}
