<?php

/*===============================================*\
|| ############################################# ||
|| # JAKWEB.CH / Version 2.1.4                 # ||
|| # ----------------------------------------- # ||
|| # Copyright 2023 JAKWEB All Rights Reserved # ||
|| ############################################# ||
\*===============================================*/

if (!file_exists('../../config.php')) die('ajax/[available.php] config.php not exist');
require_once '../../config.php';

if (!isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !isset($_SESSION['jak_lcp_idhash'])) die("Nothing to see here");

// Import the user or standard language file
if (isset($_SESSION['jak_lcp_lang']) && file_exists(APP_PATH.JAK_OPERATOR_LOC.'/lang/'.$_SESSION['jak_lcp_lang'].'.php')) {
    include_once(APP_PATH.JAK_OPERATOR_LOC.'/lang/'.$_SESSION['jak_lcp_lang'].'.php');
} else {
    include_once(APP_PATH.JAK_OPERATOR_LOC.'/lang/'.JAK_LANG.'.php');
}

$switchtl = $iso_code_clean = "";
if (isset($_POST['wsource']) && !empty($_POST['wsource'])) $switchtl = $_POST['wsource'];

switch($switchtl) {

  case 'answer':

    // Let's filter some inputs
    $tid = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
    $aid = filter_var($_POST['aid'], FILTER_SANITIZE_NUMBER_INT);

    if (!is_numeric($tid)) die(json_encode(array('status' => 0, "txt" => $jkl['g116'])));

    $row = $jakdb->get("support_tickets", ["content", "lang"], ["id" => $tid]);

    if (isset($row) && !empty($row)) {

      if ($aid != 0 && is_numeric($tid) && is_numeric($aid)) {
        $row2 = $jakdb->get("ticket_answers", ["content"], ["AND" => ["id" => $aid, "ticketid" => $tid]]);
        $row3 = $jakdb->get("ticket_ai_translations", ["original_lang", "translated_lang", "lang"], ["AND" => ["opid" => $opcacheid, "ticketid" => $tid, "ticketanswerid" => $aid]]);
      } else {
        $row2["content"] = $row["content"];
        $row3 = $jakdb->get("ticket_ai_translations", ["original_lang", "translated_lang", "lang"], ["AND" => ["opid" => $opcacheid, "ticketid" => $tid, "ticketanswerid" => 0]]);
      }

      // We check if the text is the same and the translation has already been done
      if (isset($row3["lang"]) && $row3["lang"] == $_SESSION['jak_lcp_lang']) {

        // We can assume that the translation has been done, so we do not need to run it again and pay money for it
        $translation = $row3["translated_lang"];

      } else {

        // We have previous messages
          $translation_msg = [];

          // User Subject
          $translation_msg[] = [
              "role" => "user",
              "content" => "Please translate this text into following language with iso code '".$_SESSION['jak_lcp_lang']."': ".$row2["content"]
          ];

        // We have no translation so far, let's call the AI service
          $jsonData = json_encode(array(
              "model" => "gpt-3.5-turbo",
              "temperature" => 0.3,
              "messages" => $translation_msg
          ));

          // cURL initialization
          $ch = curl_init();

          // Set cURL options
          curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
          curl_setopt($ch, CURLOPT_HTTPHEADER, [
              "Content-Type: application/json",
              "Authorization: Bearer ".JAK_OPENAI_APIKEY,
          ]);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);

          // Execute the cURL request
          $response = curl_exec($ch);

          // Close cURL connection
          curl_close($ch);

          //die(print_r($response."<br>". curl_error($ch)));
          // die(json_encode(array('status' => 0, "txt" => print_r($response."<br>". curl_error($ch)))));

          // Handle the response
          if ($response === false) {
              // Error handling
              die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
              // echo 'cURL error: ' . curl_error($ch);
          } else {
              // Process the response
              $translation = "";
              $responseData = json_decode($response, true);
              // Check if we have a valid answer
              if (isset($responseData['choices'][0]['message']['content'])) $translation = html_entity_decode(filter_var($responseData['choices'][0]['message']['content'], FILTER_SANITIZE_FULL_SPECIAL_CHARS));
          }

          // We do have a translation?
          if (!empty($translation)) {

            // Add the values to the database
            $jakdb->insert("ticket_ai_translations", [
            "opid" => $opcacheid,
            "ticketid" => $tid,
            "ticketanswerid" => $aid,
            "operatorid" => $_POST['uid'],
            "original_lang" => $row2["content"],
            "translated_lang" => $translation,
            "lang" => $_SESSION['jak_lcp_lang'],
            "created" => $jakdb->raw("NOW()")]);

            // Now we need to know the original language from the text
            if (empty($row["lang"])) {

              // We have previous messages
              $iso_code_msg = [];

              // User Subject
              $iso_code_msg[] = [
                  "role" => "user",
                  "content" => "Please return the language iso code for following text: ".$row2["content"]
              ];

            // We have no translation so far, let's call the AI service
              $jsonData2 = json_encode(array(
                  "model" => "gpt-3.5-turbo",
                  "temperature" => 0.5,
                  "messages" => $iso_code_msg
              ));

              // cURL initialization
              $ch2 = curl_init();

              // Set cURL options
              curl_setopt($ch2, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
              curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
              curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'POST');
              curl_setopt($ch2, CURLOPT_HTTPHEADER, [
                  "Content-Type: application/json",
                  "Authorization: Bearer ".JAK_OPENAI_APIKEY,
              ]);
              curl_setopt($ch2, CURLOPT_POSTFIELDS, $jsonData2);

              // Execute the cURL request
              $response2 = curl_exec($ch2);

              // Close cURL connection
              curl_close($ch2);

              // die(print_r($response."<br>". curl_error($ch2)));
              // die(json_encode(array('status' => 0, "txt" => print_r($response2."<br>". curl_error($ch2)))));

              // Handle the response
              if ($response2 === false) {
                  // Error handling
                  // die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
                  // echo 'cURL error: ' . curl_error($ch2);
              } else {
                  // Process the response
                  $iso_code = "";
                  $responseData2 = json_decode($response2, true);
                  // Check if we have a valid answer
                  if (isset($responseData2['choices'][0]['message']['content'])) $iso_code = $responseData2['choices'][0]['message']['content'];

                  // Regular expression pattern to find text inside double quotes
              $pattern = '/"([^"]+)"/';

              // Use preg_match_all to find all matches
              if (preg_match($pattern, $iso_code, $matches)) {
                  // $matches[0] contains the full matches including the double quotes
                  // $matches[1] contains the text inside the double quotes
                  $iso_code_clean = $matches[1];

                  // We update the database
                    $jakdb->update("support_tickets", ["lang" => $iso_code_clean], ["id" => $tid]);

              }

                  
              }

            }

          } else {
            die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
          }

      }

      die(json_encode(array('status' => 1, "translation" => $translation, "lang" => $iso_code_clean, "txt" => $jkl['g14'])));

    } else {
      die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
    }

  break;
  case 'grammar':

    if (isset($_POST['tcontent']) && !empty($_POST['tcontent'])) {

      // We will check the grammar from the input
        $grammar_check = [];

        // User Subject
        $grammar_check[] = [
            "role" => "user",
            "content" => "Please correct grammar, and generate a more formal language for the following text, keep the format: ".$_POST['tcontent']
        ];

      // We have no translation so far, let's call the AI service
        $jsonData3 = json_encode(array(
            "model" => "gpt-3.5-turbo",
            "temperature" => 0.3,
            "messages" => $grammar_check
        ));

        // cURL initialization
        $ch3 = curl_init();

        // Set cURL options
        curl_setopt($ch3, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
        curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch3, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch3, CURLOPT_HTTPHEADER, [
            "Content-Type: application/json",
            "Authorization: Bearer ".JAK_OPENAI_APIKEY,
        ]);
        curl_setopt($ch3, CURLOPT_POSTFIELDS, $jsonData3);

        // Execute the cURL request
        $response3 = curl_exec($ch3);

        // Close cURL connection
        curl_close($ch3);

        // die(print_r($response."<br>". curl_error($ch3)));
        // die(json_encode(array('status' => 0, "txt" => print_r($response3."<br>". curl_error($ch3)))));

        // Handle the response
        if ($response3 === false) {
            // Error handling
            die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
            // echo 'cURL error: ' . curl_error($ch);
        } else {
            // Process the response
            $grammar_correct = "";
            $responseData3 = json_decode($response3, true);
            // Check if we have a valid answer
            if (isset($responseData3['choices'][0]['message']['content'])) $grammar_correct = html_entity_decode(filter_var($responseData3['choices'][0]['message']['content'], FILTER_SANITIZE_FULL_SPECIAL_CHARS));
        }

        die(json_encode(array('status' => 2, "grammar_correct" => $grammar_correct, "txt" => $jkl['g14'])));
    } else {
      die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
    }

  break;
  case 'translate':

    if (isset($_POST['tcontent']) && !empty($_POST['tcontent']) && !empty($_POST['lang'])) {

      // We will check the grammar from the input
        $translation_go = [];

        // User Subject
        $translation_go[] = [
            "role" => "user",
            "content" => "Please translate this text into following language with iso code '".$_POST['lang']."': ".$_POST['tcontent']
        ];

      // We have no translation so far, let's call the AI service
        $jsonData4 = json_encode(array(
            "model" => "gpt-3.5-turbo",
            "temperature" => 0.3,
            "messages" => $translation_go
        ));

        // cURL initialization
        $ch4 = curl_init();

        // Set cURL options
        curl_setopt($ch4, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
        curl_setopt($ch4, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch4, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch4, CURLOPT_HTTPHEADER, [
            "Content-Type: application/json",
            "Authorization: Bearer ".JAK_OPENAI_APIKEY,
        ]);
        curl_setopt($ch4, CURLOPT_POSTFIELDS, $jsonData4);

        // Execute the cURL request
        $response4 = curl_exec($ch4);

        // Close cURL connection
        curl_close($ch4);

        // die(print_r($response."<br>". curl_error($ch4)));
        // die(json_encode(array('status' => 0, "txt" => print_r($response4."<br>". curl_error($ch4)))));

        // Handle the response
        if ($response4 === false) {
            // Error handling
            die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
            // echo 'cURL error: ' . curl_error($ch);
        } else {
            // Process the response
            $translate_correct = "";
            $responseData4 = json_decode($response4, true);
            // Check if we have a valid answer
            if (isset($responseData4['choices'][0]['message']['content'])) $translate_correct = html_entity_decode(filter_var($responseData4['choices'][0]['message']['content'], FILTER_SANITIZE_FULL_SPECIAL_CHARS));
        }

        die(json_encode(array('status' => 3, "translate_correct" => $translate_correct, "txt" => $jkl['g14'])));
    } else {
      die(json_encode(array('status' => 0, "txt" => $jkl['i2'])));
    }

  break;
}
?>
