<?php
function docuchat_plugin_uploadFile()
{
  echo wp_json_encode(docuchat_process_file_toRemote());
  wp_die();
}

function docuchat_process_file_toRemote()
{ 
  try {

    $token = get_option( DOCUCHAT_TOKEN ) ?  get_option( DOCUCHAT_TOKEN ) : false; 


    if (
      isset($_POST["nonce"]) && !empty($_POST["nonce"]) &&
      isset($_POST["file"]) && !empty($_POST["file"]) && 
      isset($token) && !empty($token) &&
      wp_verify_nonce( wp_unslash($_POST["nonce"] ), 'upload')
    ) {

                $sanitized_unlashed_file = sanitize_file_name(wp_unslash($_POST["file"]));
                $sanitized_unlashed_token = sanitize_file_name(wp_unslash($token));

                $file_path = get_attached_file(intval($sanitized_unlashed_file));

                if (!file_exists($file_path)) {
                  return new WP_Error('file_not_found', 'File not found.');
                }

                $file = @fopen($file_path, 'r');
                $file_size = filesize($file_path);
                $file_data = fread($file, $file_size);

                $boundary = wp_generate_password(45);

                $filename = basename($file_path);
                $boundary = wp_generate_password(32, false, false);

                $body = "--{$boundary}\r\n";
                $body .= 'Content-Disposition: form-data; name="file"; filename="' . $filename . '"' . "\r\n";
                $body .= 'Content-Type: application/octet-stream' . "\r\n\r\n";
                $body .= $file_data . "\r\n";
                $body .= "--{$boundary}\r\n";
                $body .= 'Content-Disposition: form-data; name="token"' . "\r\n\r\n";
                $body .= "{$sanitized_unlashed_token}" . "\r\n";
                $body .= "--{$boundary}--\r\n";

                $args = array(
                  'method'      => 'POST',
                  'timeout'     => 45,
                  'redirection' => 5,
                  'httpversion' => '1.0',
                  'blocking'    => true,
                  'sslverify' => false,
                  'headers'     => array(
                    'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
                  ),
                  'body'        => $body,
                  'cookies'     => array(),
                );

                $response = wp_remote_post('https://api.docuchat.es/api/v1/upload',  $args);

                if (is_wp_error($response)) {
                  return array("status" => 400, "message" => "Error registering data: " . $response->get_error_message());
                }

                return  $response;
    } else {
      return array("status" => 400, "message" => "Error registering data");
    }
  } catch (\Throwable $th) {
    return array("status" => 400, "message" => "Error registering data: " . $th->getMessage());
  }
}
