<?php

/*
 * Copyright CADMAI Software GmbH.
 * All rights reserved.
 *
 * The redistributor / user does not have the right to change, translate,
 * back-develop, decompile or disassemble the software.
 *
 * Redistributions must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 *
 * Neither the name of CADMAI Software GmbH nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

include_once ( 'funcs.php' );

$func = $_GET['func'];

$data = json_decode ( $_POST['data'] );

$output = [
  "mMm" => $func,
  "erC" => 0,
  "erT" => '',
  "srvInfo" => '',
  "dt" => []
];

switch ( $func ) {
  case 'LoadCatalog':
    $output['erC'] = LoadCatalog ( $data, $output['dt'], $output['erT'] );
    break;

  case 'ExportCatalog':
    $output['erC'] = ExportCatalog ( $data, $output['dt'], $output['erT'], $output['srvInfo'] );
    break;

  case 'LoadCatalogIndex':
    $output['erC'] = LoadCatalogIndex ( $data, $output['dt'], $output['erT'], $output['srvInfo'] );
    break;

  default:
    $output['erC'] = 1;
    $output['erT'] = 'function not implemented';
    break;
}
echo json_encode ( $output );

function LoadCatalog ($data, &$ret, &$errorText)
{
  $ret = (object) [];
  $errorText = "";

  if ( empty ( $data->cDir ) ) {
    $errorText = "cDir not set";
    return 1;
  }

  //internal catalogs only when logged in
  $checkName = strtolower($data->cDir);
  if(strpos($checkName, './poi3dcatalog') !== false) {
    if ( iLoadUserBaseData( $data, $user, $errorText ) ) {
      return 2;
    }
  }

  $catEntriesFname = $data->cDir . '/catalog.json';

  $cEntries = [];
  $cEntries = iGetJsonFromFile($catEntriesFname,true)->data;

  $ret->baseDir = $data->cDir;
  $ret->cEntries = $cEntries;

  return 0;
}

function LoadCatalogIndex ($data, &$ret, &$errorText, &$srvInfo)
{
  $ret = (object) [];
  $errorText = "";

  if ( empty ( $data->indexDir ) ) {
    $errorText = "indexDir not set";
    return 1;
  }

  $catalogs = [];
  $indexFileName = $data->indexDir . "/catalogIndex.json";
  $content = iGetJsonFromFile($indexFileName,true);
  $catalogs = $content->data;

  $ret->ctlgs = $catalogs;
  return 0;
}

function ExportCatalog ($data, &$ret, &$errorText, &$srvInfo)
{
  $ret = (object) [];
  $errorText = "";

  if ( iLoadUserBaseData( $data, $user, $errorText ) ) {
    return 1;
  }

  if ( empty ( $data->dirInfo ) ) {
    $errorText = "dirInfo not set";
    return 2;
  }

  $entryList = $data->dirInfo;
  if ( !is_array ( $entryList ) ) {
    $errorText = "invalid data structure";
    return 3;
  }

  $tgtDir = "./FileOutput/CatalogExport";
  $zipFile = "./FileOutput/CatalogExport.zip";
  $ctlgIndexFile = $tgtDir . "/catalog.json";
  $ctlgIndexEntry = (object) [];
  $ctlgIndex = [];
  $encTok = "";

  if ( iDecrypt( $data->slt, $encTok, $errorText ) ) {
    $errorText = 'decryption error: ' . $errorText;
    return 4;
  }

  mkdir ( $tgtDir );
  copy ( "./Poi3d/Ressources/HtaccessCtlg.txt", $tgtDir . "/.htaccess" );

  foreach ( $entryList as $e ) {
    $ctlgIndexEntry = new stdClass();
    $ctlgIndexEntry->grId = $e->grId;
    $ctlgIndexEntry->grNm = $e->grNm;
    $ctlgIndexEntry->owner = $e->owner;
    $ctlgIndexEntry->ownerName = $e->ownerName;
    $ctlgIndex[] = $ctlgIndexEntry;

    $wgDir = "./FileOutput/CatalogExport/" . $e->grId;

    mkdir ( $wgDir );
    ixCopy($e->grDir,$wgDir);
    if (file_exists($wgDir . "/users.json")) unlink($wgDir . "/users.json");

    foreach ( $e->docs as $d ) {

      $docDir = $wgDir . "/" . $d->dId;

      mkdir ( $docDir );
      ixCopy($d->dDir,$docDir);

      if (file_exists($docDir . "/workGroups.json")) unlink($docDir . "/workGroups.json");
      if (file_exists($docDir . "/fileAccess.json")) unlink($docDir . "/fileAccess.json");
      if (file_exists($docDir . "/docChat.json")) unlink($docDir . "/docChat.json");

      if (file_exists($docDir . "/annotations.json_lock")) unlink($docDir . "/annotations.json_lock");
      if (file_exists($docDir . "/locations.json_lock")) unlink($docDir . "/locations.json_lock");
      if (file_exists($docDir . "/instructions.json_lock")) unlink($docDir . "/instructions.json_lock");
      if (file_exists($docDir . "/materialSets.json_lock")) unlink($docDir . "/materialSets.json_lock");
      if (file_exists($docDir . "/fileAttachments.json_lock")) unlink($docDir . "/fileAttachments.json_lock");
      if (file_exists($docDir . "/boms.json_lock")) unlink($docDir . "/boms.json_lock");
      if (file_exists($docDir . "/sensors.json_lock")) unlink($docDir . "/sensors.json_lock");
      if (file_exists($docDir . "/docAttributes.json_lock")) unlink($docDir . "/docAttributes.json_lock");

      iDecodeAttachment($docDir . "/annotations.json", $encTok->pwd);
      iDecodeAttachment($docDir . "/locations.json", $encTok->pwd);
      iDecodeAttachment($docDir . "/instructions.json", $encTok->pwd);
      iDecodeAttachment($docDir . "/materialSets.json", $encTok->pwd);
      iDecodeAttachment($docDir . "/fileAttachments.json", $encTok->pwd);
      iDecodeAttachment($docDir . "/boms.json", $encTok->pwd);
      iDecodeAttachment($docDir . "/sensors.json", $encTok->pwd);
      iDecodeAttachment($docDir . "/docAttributes.json", $encTok->pwd);
    }
  }

  $json = json_encode ( $ctlgIndex );
  if ( !iWriteFile( $ctlgIndexFile, $json ) ) {
    $errorText = "could not create catalog index";
    iRmDir($tgtDir);
    return 5;
  }

  if ( !iZipDirectory($tgtDir,$zipFile)) {
    $errorText = "could not create zip file";
    iRmDir($tgtDir);
    return 6;
  }

  iRmDir($tgtDir);

  return 0;
}


function AskAiBot ($data, &$ret, &$errorText, &$srvInfo)
{
  $ret = (object) [];
  $errorText = "";

  if ( iLoadUserBaseData( $data, $user, $errorText ) ) {
    return 1;
  }

  if ( empty ( $data->aiId ) ) {
    $errorText = "no ai interface defined";
    return 2;
  }

  if ( empty ( $data->fileName ) ) {
    $errorText = "chat target not set";
    return 3;
  }

  if ( empty ( $data->msgData ) ) {
    $errorText = "chat message template not set";
    return 4;
  }

  if ( empty ( $data->question ) ) {
    $errorText = "no question given";
    return 5;
  }

  $encTok = "";
  if (! empty ( $data->slt ) ) {
    if ( iDecrypt( $data->slt, $encTok, $errorText ) ) {
    $errorText = 'decryption error: ' . $errorText;
    return 6;
    }
  }

  $msgContent = json_decode ( $data->msgData );

  // read portal configuration for chat bot
  $cfgFileName = 'portalConfig.json';
  $f = iReadFile ( $cfgFileName );

  if ( !$f ) {
    $errorText = "couldn't open " . $cfgFileName;
    return 7;
  }

  $aiBot = null;
  $fContent = json_decode ( $f );
  if(!empty ( $fContent->aiBots )) {
    foreach ( $fContent->aiBots as $ab ) {
      if($ab->aiId == $data->aiId) {
        $aiBot = $ab;
        break;
      }
    }
  }

  if ( $aiBot == null ) {
    $errorText = "no bot found";
    return 8;
  }

  //Test ----------------
  /*
  $date = new DateTime();
  $msgContent->cDt = $date->setTimezone(new \DateTimeZone('UTC'))->format(DateTime::ATOM);
  $msgContent->tXt = "Hello from chatbot " . $msgContent->aL;

  $data->data = json_encode ($msgContent);

  return AppendToJsonFile($data, $ret, $errorText, $srvInfo);
  */

  //OpenRouter implementation -----------------

  $apiKey = $aiBot->key;

  // API-Endpunkt für OpenRouter
  $url = 'https://openrouter.ai/api/v1/chat/completions';

  // Die Daten, die an OpenRouter gesendet werden (z. B. Nachrichten und Modell)
  $queryData = [
      "model" => $aiBot->llm,
      "messages" => [
          ["role" => "user", "content" => $data->question]
      ]
  ];

  // cURL Initialisierung
  $ch = curl_init($url);

  // cURL Optionen setzen
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Antwort als String zurückgeben
  curl_setopt($ch, CURLOPT_POST, true); // POST Anfrage
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Content-Type: application/json",
      "Authorization: Bearer $apiKey"
  ]);

  // Daten in JSON umwandeln und an OpenRouter senden
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($queryData));

  // Anfrage ausführen und Antwort speichern
  $response = curl_exec($ch);

  // Fehlerbehandlung
  if (curl_errno($ch)) {
    $errorText = curl_error($ch);
    return 9;
  }
  else {
    // Antwort als JSON dekodieren
    $responseData = json_decode($response, true);

    // Prüfen, ob eine Antwort vom Modell zurückkommt
    if (isset($responseData['choices'][0]['message']['content'])) {
      $date = new DateTime();
      $msgContent->cDt = $date->setTimezone(new \DateTimeZone('UTC'))->format(DateTime::ATOM);

      $orgResponse = $responseData['choices'][0]['message']['content'];

      //plain text ---------
      /*
      $msgContent->tXt = $orgResponse;
      $data->data = json_encode ($msgContent);

      AppendToJsonFile($data, $ret, $errorText, $srvInfo);
      */

      //markup in html umwandeln -----------
      $Parsedown = new Parsedown();
      $msgContent->tXt = $Parsedown->text($orgResponse);
      $data->data = json_encode ($msgContent);

      return AppendToJsonFile($data, $ret, $errorText, $srvInfo);
    }
    else {
      $date = new DateTime();
      $msgContent->cDt = $date->setTimezone(new \DateTimeZone('UTC'))->format(DateTime::ATOM);

      $msgContent->tXt = "Query canceled (no answer received)";
      //HTTP 402: {"error":{"message":"Insufficient credits. This account never purchased credits. Make sure your key is on the correct account or org, and if so, purchase more at https://openrouter.ai/settings/credits","code":402}}

      if (isset($responseData['error'])){
        $msgContent->tXt = "ERROR:" . json_encode ($responseData['error']);
      }

      $data->data = json_encode ($msgContent);

      return AppendToJsonFile($data, $ret, $errorText, $srvInfo);
    }
  }

  // cURL Session schließen
  curl_close($ch);
}
?>