<?php
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//show javascript message

use Aws\Textract\Exception\TextractException;


function etfi_error($array, $type, $status_code) {
    $message['isError'] = TRUE;
    if ($array != (object) null)
        $message['message'] = $type . ' ' . implode(',', $array);
    else
        $message['message'] = $type;
    $message['data'] = $array;
    header('HTTP/1.1 ' . $status_code, true, $status_code);
    header('Content-Type: application/json');
    echo json_encode($message);
    die();
}

function etfi_success($array, $type, $status_code) {
    $message['isError'] = FALSE;
    $message['message'] = $type;
    $message['data'] = $array;
    header('HTTP/1.1 ' . $status_code, true, $status_code);
    header('Content-Type: application/json');
    echo json_encode($message);
    die();
}
add_action('wp_head', 'etfi_plugin_ajaxurl');

function etfi_plugin_ajaxurl() {

   echo '<script type="text/javascript">
           var ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
} 

function etfi_extract_text_from_image(){
ob_start();
?>
<div class="extracted_text_wrap">
<form id="etfi-image-upload-form" method="post" enctype="multipart/form-data">
<aks-file-upload></aks-file-upload>
</form>
<div class="extracting-text-loder" style="display:none">
<img src="<?php echo esc_url(ETFI_URL."assets/images/ajax-loader.gif");?>"/>
<p><?php esc_html_e( 'Extracting text...', 'extract-text-from-image-etfi' );?></p>
</div>
<div class="extracted_wrap">
<h5><?php esc_html_e( 'Extracted text:', 'extract-text-from-image-etfi' );?></h5>
<textarea id="extracted_text" readonly="" rows="4"></textarea>
</div> 
</div>
<?php
$data_form = ob_get_contents();
		ob_end_clean();
		return $data_form;
}
add_shortcode( 'etfi-extract-text', 'etfi_extract_text_from_image' );


add_action( 'wp_ajax_nopriv_etfi_get_text_form_image', 'etfi_get_text_form_image' );
add_action( 'wp_ajax_etfi_get_text_form_image', 'etfi_get_text_form_image' );

function etfi_get_text_form_image(){
if(!isset($_FILES['file']['name'])){
    etfi_error((object) null, 'Missing Parameter file', 400);
}	
$region = get_option('etfi_region');
$version = get_option('etfi_version');;
$S3_KEY = get_option('etfi_S3_KEY');
$S3_SECRETE = get_option('etfi_S3_SECRETE');

$tmp_name = sanitize_text_field($_FILES['file']['tmp_name']);
$filename = sanitize_text_field($_FILES['file']['name']);
$file_tmp_ext = explode('.', $filename);
$file_extension = strtolower(end($file_tmp_ext));

$key = date('dmyhis').$file_extension;

try{
$client = new Aws\Textract\TextractClient([
    'region' => $region,
    'version' => $version,
    'credentials' => [
        'key'    => $S3_KEY,
        'secret' => $S3_SECRETE
    ]
]);

// The file in this project.
$file = fopen($tmp_name, "rb");
//echo $contents = fread($file, filesize($filename));
$contents = fread($file, filesize($tmp_name));
fclose($file);
$options = [
    'Document' => [
        'Bytes' => $contents,
    ],
    'FeatureTypes' => ['FORMS'], // REQUIRED
];
try{
    $result = $client->analyzeDocument($options);
    // If debugging:
    //echo print_r($result, true);
    if($result)
    {
        if(isset($result['Blocks']) && !empty($result['Blocks']))
        {
            $blocks = $result['Blocks'];
            // Loop through all the blocks:
            $text=array();
			
            foreach ($blocks as $key => $value) {
                if (isset($value['BlockType']) && $value['BlockType']) {
                    $blockType = $value['BlockType'];
					if($blockType=='LINE'){ //or WORD
						if (isset($value['Text']) && $value['Text']) {
							$text[] = $value['Text'];
						}
					}
                }
            }
            if(!empty($text)){
                $data['text']=implode(' ',$text);
            }else{
                $data['text']=''; 
            }
            etfi_success($data,'Text found successfully.',200);
        }else{
            etfi_error((object) null, 'Text can not process from uploaded image.', 400);
        }
    }else{
        etfi_error((object) null, 'Text can not process from uploaded image.', 400);
    }
}catch (TextractException $e) {
    etfi_error((object) null, 'You have passed worng details. Please make sure all details must be correct.', 400);
}
}catch (TextractException $e) {
    etfi_error((object) null, 'You have passed worng details. Please make sure all details must be correct.', 400);
    //echo $e->getMessage() . "\n";
}	
  wp_die();	
}
