<?php


class MainClass {

    private $headers = Array("Authorization: fi9tzpIHgp84E1Pf45rMzR/hy8lA2zE5", 'Content-Type: "application/json"');


    public function __construct($db)
    {
        $this->conn = $db;
    }


          function  WrFile($param){
            //запись в файл. Не понятно зачем, но пока оставил


                          $path='/var/www/tmp';
                          $file_name=$param['date_query'].'.json';
                          if(!file_exists($path)){
                              mkdir($path);
                              chmod ( $path, 0777 );
                          }
                          $path=$path.'/beru';

                          if(!file_exists($path)){
                              mkdir($path);
                              chmod ( $path, 0777 );
                          }

                          if(file_exists($path.'/'.$file_name)){
                              unlink($path.'/'.$file_name);
                          }
                          file_put_contents($path.'/'.$file_name, $param['data_json']);



          }
    function getSSLPage($url,$post_data,$headers) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if(strlen(trim($post_data))>0){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }
        curl_setopt ( $ch , CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt ( $ch , CURLOPT_SSL_VERIFYHOST, 0 );
//$http_code=curl_getinfo($ch,CURLINFO_RESPONSE_CODE);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }


    function wrDatabase($param){

                  /*
                  $param=[
                        `'date_query' => $date_query,
                        'data_json' => $data_json,
                        'db'=> $db,
                        'user'= $user
                     ];`
                  */


             $opers=json_decode($param['data_json'],true);
             $user=$param['user'];
             $date_query=$param['date_query'];
             $firma=$param['kag']['firma'];
             try{


                 for($i=0;$i<count($opers);$i++){

                     $item=$opers[$i];
                     $vars=[
                         'idoper'=>$item['id'],
                         'data_json' => json_encode($item),
                         'user'=>$user,
                         'date_d'=>date('Y-m-d H:i:s'),
                         'date_query'=>$date_query,
                         'firma'=>$firma,

                     ];

                     $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                     $this->conn->beginTransaction();

                     //удалить предыдущие загрузки по дате загрузки и номеру акта

                     $sth = $this->conn->prepare("delete from oper where idoper=:id and firma=:firma and date_query=:date_query");
                     $sth->execute([
                         'id'=>$item['id'],
                         'firma'=>$firma,
                         'date_query'=>$date_query,
                          ]);

                     $query="insert into oper
                    (idoper,firma, data_json,date_d,user,date_query)
                     values
                    (:idoper,:firma, :data_json,:date_d,:user,:date_query)";
                     $stmt = $this->conn->prepare($query);

                     $stmt->execute($vars);

                     $error=$stmt->errorCode();
                     $ids=$this->conn->lastInsertId();
                     $this->conn->commit();

                     //idoper == >
                     $ids_arr[$item['id']]=$ids;





                 }

                 $result= ['result'=>1,'result'=>$ids_arr];





             }catch (Exception $e) {

                 $this->conn->rollBack();
                 $error = "Ошибка: " . $e->getMessage();
                 $result = ['result'=>0,'error'=>$error];
             }

            return $result;





    }



         function DataCollect($param){
         //результаты сканирования актов



                 $query = "select 
                id, 
                barcode,
                date_up
                from oper_collect
                where idoper=:id and firma=:firma ORDER BY date_up";
                 $stmt = $this->conn->prepare($query);
                 $vars['id'] = $param['idoper'];
                 $vars['firma'] = $param['kag']['firma'];
                 $stmt->execute($vars);
                 $error = $stmt->errorCode();

                 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                     $result[] = $row;
                 }


                 return ['idoper'=>$param['idoper'] ,'collect'=>$result,'v'=>$vars];
         }


         function History($param){

           $limit=$param['limit'];
             $kag=$param['kag'];

             $vars=[
                 'firma'=>$param['kag']['firma'],

             ];

             $query = "select
                id,
                idoper, 
                date_query,
                DATE_FORMAT(date_query,'%d.%m.%Y') as date_q,
                data_json
                from oper
                where firma=:firma
                ORDER BY date_query DESC, id DESC    
                limit 10
                ";
             $stmt = $this->conn->prepare($query);
             $stmt->execute($vars);
             $error = $stmt->errorCode();

             while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                 $row['data_json']=json_decode($row['data_json'],true);
                 $row['data_collect']=$this->DataCollect(['idoper'=>$row['idoper'],'kag'=>$param['kag']]);
                 $row['param']=$param;
                 $result[] = $row;
             }


            return ['data'=>$result];



         }


        function pushCollect($data){
        //записать данные по сборке

            try{




                //--Повтор------------>
                $query = "select 
                id
                from oper_collect
                where idoper=:id and firma=:firma and (barcode=:barcode OR barcode_json like '%".$data['barcode']."%')  ORDER BY date_up";
                $stmt = $this->conn->prepare($query);
                $vars['id'] = $data['idoper'];
                $vars['firma'] = $data['kag']['firma'];
                $vars['barcode'] = $data['barcode'];

                $stmt->execute($vars);
                $error = $stmt->errorCode();

                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                    $result_b[] = $row;
                }
                if(count($result_b)){
                    $error = "Повтор ".$data['barcode'];
                    $result = ['result'=>0,'error'=>$error];
                    return $result;
                }

                //<--Повтор------------

                   $vars=[
                        'idoper'=>$data['idoper'],
                        'date_query'=>$data['date_query'],
                        'barcode' => $data['barcode'],
                        'barcode_json'=> json_encode($data['barcode_json']),
                        'date_up'=>date('Y-m-d H:i:s'),
                        'user'=>$data['user'],
                        'firma'=>$data['kag']['firma'],

                    ];

                    $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $this->conn->beginTransaction();


                    $query="insert into oper_collect
                    (idoper,firma , date_query, barcode,barcode_json,date_up,user)
                     values
                    (:idoper, :firma, :date_query,:barcode,:barcode_json,:date_up,:user)";
                    $stmt = $this->conn->prepare($query);

                    $stmt->execute($vars);

                    $error=$stmt->errorCode();
                    $id_new=$this->conn->lastInsertId();
                    $this->conn->commit();


                $result= ['result'=>1];

            }catch (Exception $e) {

                $this->conn->rollBack();
                $error = "Ошибка: " . $e->getMessage();
                $result = ['result'=>0,'error'=>$error,'data'=>$data];
            }

            return $result;




        }

            function PostingStatus($params)
            {

                        //$kag=$params['kag'];
                        //$posting_number=$params['posting_number'];

                        $url='https://marketplace.book-online.ru/api/posting_status/';
                        $json=json_encode($params);
                        $result=$this->getSSLPage($url,$json,$this->headers);

                        return json_decode($result);

            }

            function DeleteCollect($params)
            {
                $oper=$params['oper'];
                $firma=$params['firma'];

                if(strlen(trim($oper))>0 and strlen($firma)>0){
                    $query="delete from  oper_collect
                        where idoper=:id and firma=:firma";

                    $vars=['id'=>$oper,'firma'=>$firma];
                    $stmt = $this->conn->prepare($query);
                    $stmt->execute($vars);
                    $error=$stmt->errorCode();

                    return ['result'=>1,'error'=>$error,'vars'=>$vars];
                }

                  return ['result'=>0,'error'=>'неправильные входящие переменные!'];


            }





}


