<?php
session_start();
require("../snippets/autoload.php");
$utils = new Utils();
$abandoned = new Abandoned();
$num = count(glob("../../uploads/tmp/".$utils->ReturnSessionVar("tmp")."/" . "*"));
$path = "../../uploads/tmp/".$utils->ReturnSessionVar("tmp")."/";
if($num==0){
  $response_request["type"] = "error";
  $response_request["msg"] = _("Añade al menos un archivo para continuar, no se ha procesado la solicitud");
  echo json_encode($response_request);
  exit();
}
$response_request = array();
$user = new UserAccount();
$request = new Request();
$lang = new ActiveLang();
$mail = new Mail();
$rules = array();
$exclude = array();
$name = $_POST["File"][0];
$lang = new ActiveLang();
$current = json_decode($_SESSION["order"], true);
$alert = new Alert();
$price=0;
$admins = $user->GetRecordsAdmin();
if($_POST["FromLang"]!="" && $_POST["ToLang"]!="" && $_POST["Words"]>0 ){
  $lang->Id = $_POST["FromLang"];
  $data = $lang->GetRecord();
  $from = $utils->getNameTranslation($data["LangName"]);
  $lang->Id = $_POST["ToLang"];
  $data = $lang->GetRecord();
  $to = $utils->getNameTranslation($data["LangName"]);
  $price = $lang->GetRecordPricing($_POST["FromLang"], $_POST["ToLang"], $_POST["Words"]);
}else{
  $response_request["type"] = "error";
  $response_request["msg"] = _("Hay campos faltantes en tu solicitud, verifica tu información");
  echo json_encode($response_request);
  exit();
}
$total = $price*$_POST["Words"] + ((isset($_POST["Urgent"])?20:0));
$files = $_POST["File"];
SanitizeRequest($rules, $exclude);
AutomaticAssignment($_POST, $user);
AutomaticAssignment($_POST, $request);
$isset = $user->GetRecordByEmail();
if(count($isset)){
  $user->Id = $isset["Id"];
  $user->Token = $isset["Token"];
}else{
  $user->Password = "NS";
  $user->Token = $utils->GenerateLongString(35);
  $user->IsAdmin = 0;
  $user->Id =  $user->InsertRecord();
}
if($user->Id>0){
  $request->UserAccount = $user->Id;
  $request->Urgent=$request->Urgent==""?0:1;
  $request->Certification=$request->Certification==""?0:1;
  $request->Path = "";
  $request->Id = $request->InsertRecord();
  if($request->Id){
    $price = $lang->GetRecordPricing($request->FromLang, $request->ToLang, $_POST["Words"]);
    if($price==""){
      $price = 0.30;
    }
    $words = $_POST["Words"];
    $cert = (isset($_POST["Certification"]) ? 1.5:1);
    $urg = (isset($_POST["Urgent"]) ? 3.5:1);
    $total = round($current["total"], 2);//round($price*$words*$cert*$urg, 2);
    $request->EstimatedPrice = $total;
    $request->UpdateEstimation();
    //payment:
    $paymentDone = false;
    if($_POST["PaymentId"]!=""){
      $response_request["type"] = "success";
      $response_request["msg"] = _("Proceso exitoso");
      $request->UpdateToken($_POST["PaymentId"]);
      $request->PaymentToken = $_POST["PaymentId"];
      $paymentDone = true;
    }else{
      if(isset($_POST["Quoted"])){
        $paymentDone = true;
        $request->PaymentToken = "";
        $request->EstimatedPrice = 0;
        $request->UpdateEstimation();
      }else{
        if(isset($_POST["CompanyQuote"])){
          $paymentDone = true;
          $request->PaymentToken = "company credits";
          $request->UpdateEstimation();
        }else{
          $paymentDone = false;
          //error en pago
          foreach ($admins as $admin) {
            $mail->ShortDescription = "Pago no procesado en proyecto - #".$request->Id;
            $mail->LongDescription = "Ocurrió un error al realizar el pago de este proyecto ";
            $mail->DestinationName = $admin["FullName"];
            $mail->Url = "https://roc.work/precisetranslations/admin/project.php?uk=".$request->Id;
            $mail->DirectMessage($admin["Email"], "Precise translations - Pago rechazado en proyecto");
          }
        }
      }
    }
    if($paymentDone){

      //autologin
      $utils->SetSessionVar("LOGGED-USER",$user->Id);
      $utils->SetSessionVar("PROFILE",2);


      if($request->PaymentToken!=""){
        foreach ($admins as $admin) {
          $mail->ShortDescription = "Pago recibido en proyecto de cliente - #".$request->Id;
          $mail->LongDescription = "Se ha realizado el pago correctamente de este proyecto por parte del cliente, el ID de transacción es el siguiente: ".$request->PaymentToken;
          $mail->DestinationName = $admin["FullName"];
          $mail->Url = "https://roc.work/precisetranslations/admin/project.php?uk=".$request->Id;
          $mail->DirectMessage($admin["Email"], "Precise translations - Pago realizado en proyecto de cliente");
        }
      }

      $response_request["type"] = "success";
      $response_request["msg"] = _("Proceso exitoso");


      //echo "pass"."../../uploads/projects/".$request->Id;

      ///create folders
      mkdir("../../uploads/projects/".$request->Id, 0755);
      mkdir("../../uploads/projects/".$request->Id."/submitted", 0755);
      mkdir("../../uploads/projects/".$request->Id."/translated", 0755);
      //copy content
      $files = scandir($path);
      $files = array_diff(scandir($path), array('.', '..'));
      foreach($files as $item){
        $file = $path.$item;
        //if unzip
        $ext =$utils->GetFileExtension($item);
        if($ext=="zip"){
          /*$archive = RarArchive::open($file);
          $entries = $archive->getEntries();
          foreach ($entries as $entry) {
            $entry->extract("../../uploads/projects/".$request->Id."/submitted/".explode(".", $item)[0]);
          }
          $archive->close();*/
          $zip = new ZipArchive;
          $res = $zip->open($file);
          if ($res === TRUE) {
            $zip->extractTo("../../uploads/projects/".$request->Id."/submitted/".explode(".", $item)[0]);
            $zip->close();
            unlink($file);
          }else{
            if (copy($file,"../../uploads/projects/".$request->Id."/submitted/".$item)) {
              unlink($file);
            }
          }
        }else{
          if (copy($file,"../../uploads/projects/".$request->Id."/submitted/".$item)) {
            unlink($file);
          }
        }
      }
      //delete from cache

      $abandoned->Salt = $utils->ReturnSessionVar("tmp");
      $abandoned->DeleteRecord();

      //send mail
      $mail->ShortDescription = "Nueva orden - #".$request->Id;
      $mail->LongDescription = "Recientemente has creado una orden en Precise Translations, en el siguiente link puedes ingresar para ver el estado del mismo, se te pedirá un acceso o contraseña al iniciar, escribe la que tu consideres";
      $mail->DestinationName = $user->FullName;
      $mail->Url = "https://roc.work/precisetranslations/client/login.php?token=".$user->Token;
      $mail->DirectMessage($user->Email, "Precise translations - Nuevo proyecto en revisión");
      //var_dump($admins);
      foreach ($admins as $admin) {
        $alert->Destination = $admin["Id"];
        $alert->Description = "New quotation ready!";
        $alert->Url = "project.php?uk=".$request->Id;

        $mail->ShortDescription = "Nueva orden - #".$request->Id;
        $mail->LongDescription = "Recientemente se ha creado una orden en Precise Translations, en el siguiente link puedes ingresar para ver el estado del mismo";
        $mail->DestinationName = $admin["FullName"];
        $mail->Url = "https://roc.work/precisetranslations/admin/project.php?uk=".$request->Id;
        $mail->DirectMessage($admin["Email"], "Precise translations - Nuevo proyecto en revisión");


        $alert->InsertRecord();
      }
      echo json_encode($response_request);
      exit();
    }else{
      $response_request["type"] = "error";
      $response_request["msg"] = _("Error al añadir el proyectos, intenta de nuevo");
    }
  }
}else{
  $response_request["type"] = "error";
  $response_request["msg"] = _("Error al añadir el proyectoa, intenta de nuevo");
}

echo json_encode($response_request);
