<?php header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: *");  

  //header('Content-Type: application/json');

  include '../db/connectMe.php';   
  include '../function/function.php';  

  // (C) GENERATE JWT TOKEN
  require "../vendor/autoload.php";
  use Firebase\JWT\JWT;

  use ElephantIO\Client;
  use ElephantIO\Engine\SocketIO\Version2X;

  
  if( AuthorizeMe(@substr(getallheaders()["Authorization"], 7)) ){

    $jwt = substr(getallheaders()["Authorization"], 7);

    //Decoding data
    $decodeToken = (json_decode(base64_decode(str_replace('_', '/', str_replace('-','+',explode('.', $jwt)[1]))))->data);

    if(!isset($decodeToken)){

      exit(json_encode(array("error" => "unauthorised") ));

    }


    // (A) NO data
    if (!isset($_POST["msg"])  || !isset($_POST["receiverId"])  ) { 

      $error = array("error"=> "no");
      exit( json_encode($error) ); 

    }


    $port = 3001;
    $senderId = mysql_prep($decodeToken->ID);
  



    if(isset($_POST['msg']) && isset($_POST['receiverId']) ){


    	$msg = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', "", $_POST['msg']);
    	$receiverId = $_POST['receiverId'];

        @$token = mysql_prep(uniqid());
        @$date = date("Y-m-d");

        $time =  date("h:i:sa");
        $msgKey = uniqid();


        $uploadDir = "../../CELLFIX-V72/chats/uploads/"; // Folder to store images
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0777, true); // Create directory if it doesn't exist
        }

        $response = "";
        $ext = "";

        $fileName = "";
        $status = 1;

        $fileUrl = '';

        //exit( $_FILES["file"]["name"] );


        //if (isset($_FILES["file"]) && $_FILES["file"]["error"] === UPLOAD_ERR_OK) {
        if (isset($_FILES["file"]) ) {

          $fileTmpPath = $_FILES["file"]["tmp_name"];
          $fileName = basename($_FILES["file"]["name"]);

          $img = $_FILES['file']['name'];
          $fileDestination = $uploadDir .$msgKey.$fileName;

          $fileUrl = $msgKey.$fileName;

          //exit($fileUrl);



          $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));

          // Move the uploaded file to the destination folder
          if (move_uploaded_file($fileTmpPath, $fileDestination)) {

            $response = $fileDestination;

          } else {
            
          }
        
        } else {
          
        }


        // save message
        $stmt = $connectMe->prepare("INSERT INTO  tbl_chat_msg ( tbl_userId, tbl_receiverId, tbl_chat_msgContent, tbl_chat_msgFile, tbl_chat_msgDate, tbl_chat_msgTime, tbl_chat_msgToken, tbl_chat_msgStatus)  VALUES (?,?,?, ?,?,?, ?,?) ");  
       
        $stmt->bindParam(1, $senderId);
        $stmt->bindParam(2, $receiverId);

        $stmt->bindParam(3, $msg);
        $stmt->bindParam(4, $fileUrl);

        $stmt->bindParam(5, $date);
        $stmt->bindParam(6, $time);

        $stmt->bindParam(7, $token);
        $stmt->bindParam(8, $status);

        if($stmt->execute()){


          /////////////////////////////send message

          try {

              $version = new Version2X("http://192.168.0.100:".$port);
              //$version = new Version2X("https://realtime.worldsoftsms.com");

              $client = new Client($version);
              $client->initialize();

              $client->emit("new_order", 
                [
                    "tbl_chat_msgContent" => $msg, 
                    "tbl_receiverId" => $receiverId, 
                    
                    "tbl_chat_msgFile" => $fileUrl,
                    "tbl_chat_msgToken" => $token,

                    "ext" =>  $ext,
                    "tbl_userId" => $senderId
                ]
              );

              $client->close();

              //exit($response);

              exit(json_encode(array("message" => 'Message sent') ));
    
            } catch (Exception $e) {

              exit("Failed to connect to the server");
    
            }

        }else{

           exit("Message send failed"); 
        }


    }


  }else{

    exit(json_encode(array("error" => "unauthorised") ));


  }