<?php  
  session_start();
    header('Content-Type: text/html; charset=utf-8');
    $instance_id = $_SESSION['client_id'];

        //require "log.php";
        //include "../settings.php";
		include "writedblog.php";
		require_once("ClassLibs/ClassMessageAndLogs.php");
		
		$ObjLogsTOiR = new MessageAndLogs();
		
		
		$dbset = json_decode($_SESSION['settingsApp'],true);
		$db = new mysqli ($dbset['DB']['DB_HOST'],$dbset['DB']['DB_USER'],$dbset['DB']['DB_PASS'],$dbset['DB']['DB_NAME']);
        //$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
        $db->query("SET CHARSET SET utf8");
        $db->query("SET NAMES 'utf8'");
        if (mysqli_connect_errno()) {
            echo "Error connecting to DB";
            exit;
        }
        //-----------------------------------------------------------------add-------------------------------------------------------------    
            
    if ($_GET['func']=='add')
        {  
          foreach ($_POST as $key => $value)
          {
            $data[$key] = $value;
          }
           $query = "INSERT INTO client (client,name_TT,region,city,address,contact_number,contact_name,id_code_PSD,contract_number,
           		note,type_TT,sales_contact_number, instance_id, external_id)  
           		VALUES ('".$data[client]."','".$data[name_TT]."','".$data[region]."','".$data[city]."','".$data[address]."',
           				'".$data[contact_number]."','".$data[contact_name]."','".$data[id_code_PSD]."','".$data[contract_number]."',
           						'".$data[note]."','".$data[type_TT]."','".$data[sales_contact_number]."', $instance_id, '$data[external_id]')";

		   
			if ($stmt = $db->prepare($query)){
			if ($stmt->execute()){      
				$stmt->close();
				echo (json_encode(array("success" => true, "message" => "")));
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
           
            
           
		   $ObjLogsTOiR->WriteLogAttendance(date('Y-m-d H:i:s')."  - instance=".$instance_id."  - query=".$query,'Toir_log','../logs');
		   
           $db->close();
		   exit;
           //echo json_encode(array('success'=>true,'content'=>$_POST));      
        }
        
        
        //-----------------------------------------------------------------update-------------------------------------------------------------    
                   
    if ($_GET['func']=='update')
        {  
          foreach ($_POST as $key => $value)
          {
            $data[$key] = $value;
          }
           $data['id_client'] += 0;
           $query = "UPDATE client SET client='".$data['client']."',name_TT='".$data['name_TT']."',region='".$data['region']."',
           		city='".$data['city']."',address='".$data['address']."',contact_number='".$data['contact_number']."',
           		contact_name='".$data['contact_name']."',id_code_PSD='".$data['id_code_PSD']."',
           		contract_number='".$data['contract_number']."',note='".$data['note']."',
           		type_TT='".$data['type_TT']."',sales_contact_number='".$data['sales_contact_number']."', external_id='$data[external_id]' 
           		WHERE id_client=".$data['id_client']."";
           
			if ($stmt = $db->prepare($query)){
			if ($stmt->execute()){      
				$stmt->close();
				echo (json_encode(array("success" => true, "message" => "")));
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
		   
		   $ObjLogsTOiR->WriteLogAttendance(date('Y-m-d H:i:s')."  - instance=".$instance_id."  - query=".$query,'Toir_log','../logs');
		   $db->close();
		   exit;
           //echo json_encode(array('success'=>true,'content'=>$_POST));
        }
        //-----------------------------------------------------------------show-------------------------------------------------------------    
                               
    if ($_GET['func']=='show')
        {
          $query = "SELECT MAX(id_code_PSD) FROM client";
          $result = $db->query($query);
          $id_code_PSD_query_max = $result->fetch_array(MYSQLI_NUM);
          $query = "SELECT MIN(id_code_PSD) FROM client";
          $result = $db->query($query);
          $id_code_PSD_query_min = $result->fetch_array(MYSQLI_NUM);
          
          if ($_GET['filter'])
          {
            $arrayFilter = $_GET['filter'];
            foreach ($arrayFilter as $key=>$val)
            {
              if ($arrayFilter[$key][field]=='client'){$client_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='name_TT'){$name_TT_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='region'){$region_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='city'){$city_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='address'){$address_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='contact_name'){$contact_name_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='id_code_PSD') // подготовка для цифрового фильтра
              {
                if ($arrayFilter[$key][data][comparison]=='lt'){$id_code_PSD_query_max[0] = $arrayFilter[$key][data][value]+0;}
                if ($arrayFilter[$key][data][comparison]=='gt'){$id_code_PSD_query_min[0] = $arrayFilter[$key][data][value]+0;}
              }
              if ($arrayFilter[$key][field]=='contract_number'){$contract_number_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='note'){$note_query = $arrayFilter[$key][data][value];}
              if ($arrayFilter[$key][field]=='type_TT'){$type_TT_query = $arrayFilter[$key][data][value];}
            }
          }
          $i=0;
          $startLimit = $_GET['start'];
          $limitLimit = $_GET['limit'];
          $query = "SELECT id_client,client,name_TT,region,city,address,contact_number,contact_name,id_code_PSD,contract_number,note,type_TT,
          sales_contact_number, external_id FROM client WHERE instance_id = $instance_id AND client LIKE '%".$client_query."%' AND name_TT LIKE '%".$name_TT_query."%' AND region LIKE '%".$region_query."%' AND city LIKE '%".$city_query."%' AND address LIKE '%".$address_query."%' AND contact_name LIKE '%".$contact_name_query."%' AND id_code_PSD BETWEEN '".$id_code_PSD_query_min[0]."' AND '".$id_code_PSD_query_max[0]."' AND contract_number LIKE '%".$contract_number_query."%' AND note LIKE '%".$note_query."%' AND type_TT LIKE '%".$type_TT_query."%' LIMIT ".$startLimit.", ".$limitLimit."";
      if ($stmt = $db->prepare($query)){
              $stmt->execute();
              $stmt->bind_result($id_client, $client, $name_TT, $region, $city, $address, $contact_number, $contact_name, $id_code_PSD, 
              		$contract_number, $note, $type_TT, $sales_contact_number, $external_id);
              while ($stmt->fetch()) 
              {
                $Model [$i]= 
                  array('id_client'=>$id_client,
                        'client'=>$client,
                        'name_TT'=>$name_TT,
                        'region'=>$region,
                        'city'=>$city,
                        'address'=>$address,
                        'contact_number'=>$contact_number,
                        'contact_name'=>$contact_name,
                        'id_code_PSD'=>$id_code_PSD,
                        'contract_number'=>$contract_number,
                        'note'=>$note,
                        'type_TT'=>$type_TT,
                        'sales_contact_number'=>$sales_contact_number,
                  		'external_id' => $external_id
                        );            
                  $i++;
              }
              $query = mysqli_query($db, "SELECT id_client FROM client WHERE instance_id = $instance_id");
              //echo "SELECT id_client FROM client WHERE instance_id = $instance_id"; exit;
              $resultRows = mysqli_affected_rows($db);      // получаем количество строк в таблице 
              $stmt->close();
              $db->close();
          }        
     echo'{success: true,results: '.$resultRows.',rows:'.json_encode($Model).'}';   
          }
        
//-----------------------------------------------------------------delete-------------------------------------------------------------    
                
    if ($_GET['func']=='del')
        { 
           $id_client = $_GET['id_client'];
           $query = "DELETE FROM client WHERE id_client=".$id_client." LIMIT 1";
			if ($stmt = $db->prepare($query)){
			if ($stmt->execute()){      
				$stmt->close();
				echo (json_encode(array("success" => true, "message" => "")));
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
			}else{ echo (json_encode(array("success" => false, "message" => $db->errno.' '.$db->error))); }
           
            $ObjLogsTOiR->WriteLogAttendance(date('Y-m-d H:i:s')."  - instance=".$instance_id."  - query=".$query,'Toir_log','../logs');
           
			$db->close();
			exit;
        }
        
        
//-----------------------------------------------------------------showCombo-------------------------------------------------------------    
    
    if ($_GET['func']=='showCombo')
        {
        $i=0;
        $query = "SELECT client,name_TT FROM client WHERE instance_id=$instance_id LIMIT 100";
    if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($client,$name_TT);
            while ($stmt->fetch()) 
            {
              $Model [$i]= 
                array('client'=>$client,
                      'name_TT'=>$name_TT,
                      /*'region'=>$region,
                      'city'=>$city,
                      'address'=>$address,
                      'contact_number'=>$contact_number,
                      'contact_name'=>$contact_name,
                      'id_code_PSD'=>$id_code_PSD,
                      'contract_number'=>$contract_number,
                      'note'=>$note,
                      'type_TT'=>$type_TT,
                      'sales_contact_number'=>$sales_contact_number*/
                      );            
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
   echo'{rows:'.json_encode($Model).'}';   
        }
        
//-----------------------------------------------------------------getDataClient---------------------------------------  
    
    if ($_GET['func']=='getDataClient')
        {
        $client = $_GET['client'];
        $i=0;
        $query = "SELECT name_TT,region,city,address,contact_number,contact_name,id_code_PSD,contract_number,note,type_TT,sales_contact_number,external_id FROM client 
        		WHERE instance_id = $instance_id AND client='".$client."'";
    if ($stmt = $db->prepare($query)){
            $stmt->execute();
            $stmt->bind_result($name_TT,$region,$city,$address,$contact_number,$contact_name,$id_code_PSD,$contract_number,$note,$type_TT,$sales_contact_number, $external_id);
            while ($stmt->fetch()) 
            {
              $Model [$i]= 
                array('name_TT'=>$name_TT,
                      'region'=>$region,
                      'city'=>$city,
                      'address'=>$address,
                      'contact_number'=>$contact_number,
                      'contact_name'=>$contact_name,
                      'id_code_PSD'=>$id_code_PSD,
                      'contract_number'=>$contract_number,
                      'note'=>$note,
                      'type_TT'=>$type_TT,
                      'sales_contact_number'=>$sales_contact_number,
                	  'external_id' => $external_id	
                      );            
                $i++;
            } 
            $stmt->close();
            $db->close();
        }
   echo'{rows:'.json_encode($Model).'}';   
        }
            

?>    
  