<?php
class ControllerToolCheckBooking extends Controller {

    private $error = [];

    public function index() {
        $this->load->model('tool/sinc');
        $this->load->model('account/customer');
        $this->load->model('checkout/order');

        $result = $this->model_tool_sinc->getNewImport();

        file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).serialize('Запуск программы'),FILE_APPEND | LOCK_EX);
        file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).serialize('Найдено '.count($result).' Записей'),FILE_APPEND | LOCK_EX);
        file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).serialize($result),FILE_APPEND | LOCK_EX);

        foreach ($result as $item) {
            $order_id = 0;
            file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).serialize('Проверка данных...'),FILE_APPEND | LOCK_EX);
            if (!isset($item['product_id']) OR empty($item['product_id'])) {
                $this->error[] = "Некорректный Id номер продукта.";
            }
            if (!isset($item['customer']) OR empty($item['customer'])) {
                $this->error[] = "Некорректное ФИО заказчика.";
            }
            if (!isset($item['date_in']) OR empty($item['date_in'])) {
                $this->error[] = "Некорректная дата вьезда.";
            }
            if (!isset($item['date_out']) OR empty($item['date_out'])) {
                $this->error[] = "Некорректная дата выезда.";
            }
            if (!isset($item['rooms']) OR empty($item['rooms'])) {
                $this->error[] = "Некорректное количество дней проживания.";
            }
            if (!isset($item['status']) OR empty($item['status'])) {
                $this->error[] = "Некорректный статус.";
            }
            if (!isset($item['price']) OR empty($item['price'])) {
                $this->error[] = "Некорректная цена.";
            }
            if (!isset($item['referens_id']) OR empty($item['referens_id'])) {
                $this->error[] = "Некорректный referens_id.";
            }


            $this->cart->clear();

            if ($item['status'] == 'New') {

                $data = array (
                    'firstname' => (isset($item['customer']) and !empty($item['customer']))?$item['customer']:"Некорректное ФИО заказчика",
                    'lastname'  => '',
                    'email'     => $this->generatorMail(),
                    'telephone' => '11111111',
                    'password'  => "v08flXsm2eA2S12ssf"
                );
                file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Создю пользвателя: '.serialize($data),FILE_APPEND | LOCK_EX);
                $id = $this->model_account_customer->addCustomer($data);
                file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).serialize('ID пользвателя='.$id),FILE_APPEND | LOCK_EX);

                $customer_info = $this->model_account_customer->getCustomer($id);
                $this->customer->login($customer_info['email'],'',true);
                $date_begin = $item['date_in'];
                $date_end = $item['date_out'];

                $date = $date_begin;
                while ($date < $date_end) {

                    file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Добавляю товар в корзину: '.serialize([
                            $item['product_id'],
                            $item['rooms'],
                            [],
                            0,
                            $date
                        ]),FILE_APPEND | LOCK_EX);
                    $this->cart->add($item['product_id'],$item['rooms'],[],0,$date);

                    $date = date('Y-m-d',strtotime($date.' + 1 days'));

                }

                $order_data = array ();

                $this->load->language('checkout/checkout');

                $order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
                $order_data['store_id'] = $this->config->get('config_store_id');
                $order_data['store_name'] = $this->config->get('config_name');

                if ($order_data['store_id']) {
                    $order_data['store_url'] = $this->config->get('config_url');
                } else {
                    if ($this->request->server['HTTPS']) {
                        $order_data['store_url'] = HTTPS_SERVER;
                    } else {
                        $order_data['store_url'] = HTTP_SERVER;
                    }
                }

                if ($this->customer->isLogged()) {
                    $this->load->model('account/customer');

                    $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());

                    $order_data['customer_id'] = $this->customer->getId();
                    $order_data['customer_group_id'] = $customer_info['customer_group_id'];
                    $order_data['firstname'] = $customer_info['firstname'];
                    $order_data['lastname'] = $customer_info['lastname'];
                    $order_data['email'] = $customer_info['email'];
                    $order_data['telephone'] = $customer_info['telephone'];
                    $order_data['fax'] = $customer_info['fax'];
                    $order_data['custom_field'] = json_decode($customer_info['custom_field'],true);
                } elseif (isset($this->session->data['guest'])) {
                    $order_data['customer_id'] = 0;
                    $order_data['customer_group_id'] = //$this->session->data['guest']['customer_group_id'];
                    $order_data['firstname'] = $this->session->data['guest']['firstname'];
                    $order_data['lastname'] = $this->session->data['guest']['lastname'];
                    $order_data['email'] = $this->session->data['guest']['email'];
                    $order_data['telephone'] = $this->session->data['guest']['telephone'];
                    $order_data['fax'] = $this->session->data['guest']['fax'];
                    $order_data['custom_field'] = $this->session->data['guest']['custom_field'];
                }

                $order_data['payment_firstname'] = '';//$this->session->data['payment_address']['firstname'];
                $order_data['payment_lastname'] = '';//$this->session->data['payment_address']['lastname'];
                $order_data['payment_company'] = '';//$this->session->data['payment_address']['company'];
                $order_data['payment_address_1'] = '';//$this->session->data['payment_address']['address_1'];
                $order_data['payment_address_2'] = '';//$this->session->data['payment_address']['address_2'];
                $order_data['payment_city'] = '';//$this->session->data['payment_address']['city'];
                $order_data['payment_postcode'] = '';//$this->session->data['payment_address']['postcode'];
                $order_data['payment_zone'] = '';//$this->session->data['payment_address']['zone'];
                $order_data['payment_zone_id'] = '';//$this->session->data['payment_address']['zone_id'];
                $order_data['payment_country'] = '';//$this->session->data['payment_address']['country'];
                $order_data['payment_country_id'] = '';//$this->session->data['payment_address']['country_id'];
                $order_data['payment_address_format'] = '';//$this->session->data['payment_address']['address_format'];
                $order_data['payment_custom_field'] = '';//(isset($this->session->data['payment_address']['custom_field']) ? $this->session->data['payment_address']['custom_field'] : array());

                if (isset($this->session->data['payment_method']['title'])) {
                    $order_data['payment_method'] = $this->session->data['payment_method']['title'];
                } else {
                    $order_data['payment_method'] = '';
                }

                $order_data['payment_code'] = 'cod';

                if ($this->cart->hasShipping()) {
                    $order_data['shipping_firstname'] = '';//$this->session->data['shipping_address']['firstname'];
                    $order_data['shipping_lastname'] = '';//'';// $this->session->data['shipping_address']['lastname'];
                    $order_data['shipping_company'] = '';//$this->session->data['shipping_address']['company'];
                    $order_data['shipping_address_1'] = '';// $this->session->data['shipping_address']['address_1'];
                    $order_data['shipping_address_2'] = '';// $this->session->data['shipping_address']['address_2'];
                    $order_data['shipping_city'] = '';//$this->session->data['shipping_address']['city'];
                    $order_data['shipping_postcode'] = '';// $this->session->data['shipping_address']['postcode'];
                    $order_data['shipping_zone'] = '';// $this->session->data['shipping_address']['zone'];
                    $order_data['shipping_zone_id'] = '';//$this->session->data['shipping_address']['zone_id'];
                    $order_data['shipping_country'] = '';//$this->session->data['shipping_address']['country'];
                    $order_data['shipping_country_id'] = '';//$this->session->data['shipping_address']['country_id'];
                    $order_data['shipping_address_format'] = '';//$this->session->data['shipping_address']['address_format'];
                    $order_data['shipping_custom_field'] = '';//(isset($this->session->data['shipping_address']['custom_field']) ? $this->session->data['shipping_address']['custom_field'] : array());


                    $order_data['shipping_method'] = '';

                    $order_data['shipping_code'] = '';

                } else {
                    $order_data['shipping_firstname'] = '';
                    $order_data['shipping_lastname'] = '';
                    $order_data['shipping_company'] = '';
                    $order_data['shipping_address_1'] = '';
                    $order_data['shipping_address_2'] = '';
                    $order_data['shipping_city'] = '';
                    $order_data['shipping_postcode'] = '';
                    $order_data['shipping_zone'] = '';
                    $order_data['shipping_zone_id'] = '';
                    $order_data['shipping_country'] = '';
                    $order_data['shipping_country_id'] = '';
                    $order_data['shipping_address_format'] = '';
                    $order_data['shipping_custom_field'] = array ();
                    $order_data['shipping_method'] = '';
                    $order_data['shipping_code'] = '';
                }

                $order_data['products'] = array ();

                $products = $this->cart->getProducts();

                foreach ($products as $product) {

                    $option_data = array ();

                    foreach ($product['option'] as $option) {
                        $option_data[] = array (
                            'product_option_id'       => $option['product_option_id'],
                            'product_option_value_id' => $option['product_option_value_id'],
                            'option_id'               => $option['option_id'],
                            'option_value_id'         => $option['option_value_id'],
                            'name'                    => $option['name'],
                            'value'                   => $option['value'],
                            'type'                    => $option['type']
                        );
                    }

                    $order_data['products'][] = array (
                        'product_id'   => $product['product_id'],
                        'name'         => $product['name'],
                        'model'        => $product['model'],
                        'booking_day'  => $product['booking_day'],
                        'booking_date' => $product['booking_day'],
                        'option'       => $option_data,
                        'download'     => $product['download'],
                        'status'       => $product['status'],
                        'quantity'     => $product['quantity'],
                        'subtract'     => $product['subtract'],
                        'price'        => $product['price'],
                        'total'        => $product['total'],
                        'total_raw'    => $product['total'],
                        'tax'          => $this->tax->getTax($product['price'],$product['tax_class_id']),
                        'reward'       => $product['reward']
                    );
                }

                $totals = array ();
                $taxes = $this->cart->getTaxes();
                $total = 0;

                // Because __call can not keep var references so we put them into an array.
                $total_data = array (
                    'totals' => &$totals,
                    'taxes'  => &$taxes,
                    'total'  => &$total
                );

                $this->load->model('extension/extension');

                $sort_order = array ();

                $results = $this->model_extension_extension->getExtensions('total');

                foreach ($results as $key => $value) {
                    $sort_order[$key] = $this->config->get($value['code'].'_sort_order');
                }

                array_multisort($sort_order,SORT_ASC,$results);

                foreach ($results as $result) {
                    if ($this->config->get($result['code'].'_status')) {
                        $this->load->model('extension/total/'.$result['code']);

                        // We have to put the totals in an array so that they pass by reference.
                        $this->{'model_extension_total_'.$result['code']}->getTotal($total_data,$order_data['products']);
                    }
                }

                $sort_order = array ();

                foreach ($totals as $key => $value) {
                    $sort_order[$key] = $value['sort_order'];
                }

                array_multisort($sort_order,SORT_ASC,$totals);

                $order_data['totals'] = $totals;


                $order_data['vouchers'] = array ();


                $order_data['comment'] = '';
                //}
                $order_data['total'] = $total_data['total'];

                if (isset($this->request->cookie['tracking'])) {
                    $order_data['tracking'] = $this->request->cookie['tracking'];

                    $subtotal = $this->cart->getSubTotal();

                    // Affiliate
                    $this->load->model('affiliate/affiliate');

                    $affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);

                    if ($affiliate_info) {
                        $order_data['affiliate_id'] = $affiliate_info['affiliate_id'];
                        $order_data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
                    } else {
                        $order_data['affiliate_id'] = 0;
                        $order_data['commission'] = 0;
                    }

                    // Marketing
                    $this->load->model('checkout/marketing');

                    $marketing_info = $this->model_checkout_marketing->getMarketingByCode($this->request->cookie['tracking']);

                    if ($marketing_info) {
                        $order_data['marketing_id'] = $marketing_info['marketing_id'];
                    } else {
                        $order_data['marketing_id'] = 0;
                    }
                } else {
                    $order_data['affiliate_id'] = 0;
                    $order_data['commission'] = 0;
                    $order_data['marketing_id'] = 0;
                    $order_data['tracking'] = '';
                }

                $order_data['language_id'] = $this->config->get('config_language_id');
                $order_data['currency_id'] = $this->currency->getId($this->session->data['currency']);
                $order_data['currency_code'] = $this->session->data['currency'];
                $order_data['currency_value'] = $this->currency->getValue($this->session->data['currency']);
                $order_data['ip'] = $this->request->server['REMOTE_ADDR'];

                if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
                    $order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
                } elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
                    $order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
                } else {
                    $order_data['forwarded_ip'] = '';
                }

                if (isset($this->request->server['HTTP_USER_AGENT'])) {
                    $order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
                } else {
                    $order_data['user_agent'] = '';
                }

                if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
                    $order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
                } else {
                    $order_data['accept_language'] = '';
                }

                $this->load->model('checkout/order');


                file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Оформаляю заказ='.serialize($order_data),FILE_APPEND | LOCK_EX);

                $order_id = $this->model_checkout_order->addOrder($order_data);

                file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Ид заказа = '.serialize($order_id),FILE_APPEND | LOCK_EX);

                $this->model_tool_sinc->setOrderId($order_id,$item['customer'],$item['referens_id']);
                $this->model_tool_sinc->processed($item['referens_id']);
                $status=1;
                if($item['source']=='booking'){
                    $status=27;
                }elseif ($item['source']=='hotels24'){
                    $status=28;
                }
                $this->model_checkout_order->addOrderHistory($order_id,$status,$this->language->get('text_ordered'),true);

            } else {
                $date_begin = $item['date_in'];
                $date_end = $item['date_out'];
                $order_id = $this->model_tool_sinc->checkOrderId($item['referens_id']);
                $date = $date_begin;

                 file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Ид заказа = '.serialize($order_id),FILE_APPEND | LOCK_EX);
                if ($item['status'] == 'Modified') {
                    $status = 1;
                    if($item['rooms'] > 0) {
                        while ($date < $date_end) {
                            $this->model_tool_sinc->addProduct($order_id,$item['product_id'],$item['rooms'],$date);
                            file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Добавлены товары к ордеру'.serialize($order_id.' '.$item['product_id'].' '.$item['rooms'].' '.$date),FILE_APPEND | LOCK_EX);

                            $date = date('Y-m-d',strtotime($date.' + 1 days'));
                        }
                        if($item['source']=='booking'){
                            $status=29;
                        }elseif ($item['source']=='hotels24'){
                            $status=30;
                        }
                    $this->model_checkout_order->addOrderHistory($order_id,$status,$this->language->get('text_ordered'),true);

                    }else{
                        file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Количество товара меньше или равно нулю, немогу добавить товар',FILE_APPEND | LOCK_EX);

                    }

                } elseif ($item['status'] == 'Cancelled') {
                    $this->model_checkout_order->deleteOrder($order_id);
                    file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Отмена заказа №'.serialize($order_id),FILE_APPEND | LOCK_EX);

                } else {
                    $status = 1;
                    $this->model_checkout_order->addOrderHistory($item['product_id'],$status,$this->language->get('text_ordered'),true);


                }

                $this->model_tool_sinc->processed($item['referens_id']);


            }
            if (count($this->error)>0 AND $item['status']!='Cancelled') {
                file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Найдены некорректные данные: '.serialize($this->error),FILE_APPEND | LOCK_EX);


                if (isset($item['source']) AND $item['source'] == "booking") {
                    $system = $item['source'];
                    $email = "dalk556@gmail.com";
                } elseif (isset($item['source']) AND $item['source'] == "hotels24") {
                    $system = $item['source'];
                    $email = "dalk556@gmail.com";
                } else {
                    $system = "Неопределено";
                    $email = "dalk556@gmail.com";
                }
                file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Система: '.$system,FILE_APPEND | LOCK_EX);

                $referens_id = (isset($item['referens_id']) AND !empty($item['referens_id']))?$item['referens_id']:false;
                $data_add = (isset($item['date_add']) and !empty($item['date_add']))?$item['date_add']:false;
                file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Отправка почты с описанием ошибки на: '.$email,FILE_APPEND | LOCK_EX);

                $this->sendEmail($this->config->get('config_email'),$referens_id,$data_add,$system,$order_id,true);
                $this->sendEmail($email,$referens_id,$data_add,$system,$order_id,true);

            }

        }
        file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Программа отработала',FILE_APPEND | LOCK_EX);

    }

    public function generatorMail() {

        $this->load->model('account/customer');
        $email = rand(1,1000)."No-".date('Y_m_d_h_i_s')."email";

        return $email;
    }

    public function sendEmail($email,$referens_id = false,$date = false,$system = false,$order_id = false,$I = false) {

        $mail = new Mail();
        $mail->protocol = $this->config->get('config_mail_protocol');
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
        $mail->smtp_username = $this->config->get('config_mail_smtp_username');
        $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'),ENT_QUOTES,'UTF-8');
        $mail->smtp_port = $this->config->get('config_mail_smtp_port');
        $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

        $store_email = $this->config->get('config_email');

        if (!$date) {
            $this->error[] = "Некорректная дата добавления заказа.";
        }

        $store_name = "Error ecko-brech";
        $text = "";

        if ($referens_id) {
            $text = "№".$referens_id;
        }

        if ($I) {
            $text .= "<br>Из внешней системы <b>".$system."</b> поступил заказ, но во время его внесения были выявлены ошибки.
            Необходимо проконтролировать правильность созданного заказа №<b>".$order_id."</b> и при необходимости его изменить.";

        }

        $text .= "<br>Список ошибок: <ul type=\"disc\">";

        foreach ($this->error as $error) {
            $text .= "<li>".html_entity_decode($error,ENT_QUOTES,'UTF-8')."</li>";
        }
        $text .= "</ul>";

        $message = '<html dir="ltr" lang="en">'."\n";
        $message .= '  <head>'."\n";
        $message .= '    <title>'.$store_name.'</title>'."\n";
        $message .= '    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">'."\n";
        $message .= '  </head>'."\n";
        $message .= '  <body>'.$text.'</body>'."\n";
        $message .= '</html>'."\n";
        file_put_contents(DIR_LOGS.'product_import.log',chr(13).chr(10).date('Y-m-d H:i:s').chr(9).'Текст почты:'.$message,FILE_APPEND | LOCK_EX);

        $mail->setTo($email);
        $mail->setFrom($store_email);
        $mail->setSender(html_entity_decode($store_name,ENT_QUOTES,'UTF-8'));
        $mail->setSubject(html_entity_decode("sad",ENT_QUOTES,'UTF-8'));
        $mail->setHtml($message);
        $mail->send();

    }
}