<?php
if (!defined('_GNUBOARD_')) exit;

function generate_filename($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function get_lotto_info($item, $height, $vspace=30) {
    global $height_array, $top_array;

    if( !$height ) {
        return null;
    }

    $info['count'] = 0;
    $info['height'] = 0;

    $height_count = count($height_array[$item]);

    for( $i=1; $i <= $height_count; $i++ ) {
        if( $height_array[$item][$i] - $vspace <= $height && $height <= $height_array[$item][$i] + $vspace ) {
            $info['count'] = $i;
            $info['height'] = $height_array[$item][$i];
            $info['crop_y'] = $top_array[$item][$i];
        }
    }

    return $info;
}

function get_lotto_info2($item, $height, $vspace=30) {
    global $height_array2, $top_array2;

    if( !$height ) {
        return null;
    }

    $info['count'] = 0;
    $info['height'] = 0;

    $height_count = count($height_array2[$item]);

    for( $i=1; $i <= $height_count; $i++ ) {
        if( $height_array2[$item][$i] - $vspace <= $height && $height <= $height_array2[$item][$i] + $vspace ) {
            $info['count'] = $i;
            $info['height'] = $height_array2[$item][$i];
            $info['crop_y'] = $top_array2[$item][$i];
        }
    }

    return $info;
}

function get_lotto_info3($item, $height, $vspace=30) {
    global $height_array3;

    if( !$height ) {
        return null;
    }

    $info['count'] = 0;
    $info['height'] = 0;

    $height_count = count($height_array3[$item]);

    for( $i=1; $i <= $height_count; $i++ ) {
        if( $height_array3[$item][$i] - $vspace <= $height && $height <= $height_array3[$item][$i] + $vspace ) {
            $info['count'] = $i;
            $info['height'] = $height_array3[$item][$i];
        }
    }

    return $info;
}

function get_lotto_info4($item, $height, $vspace=30) {
    global $height_array4;

    if( !$height ) {
        return null;
    }

    $info['count'] = 0;
    $info['height'] = 0;

    $height_count = count($height_array4[$item]);

    for( $i=0; $i <= $height_count; $i++ ) {
        if( $height_array4[$item][$i] - $vspace <= $height && $height <= $height_array4[$item][$i] + $vspace ) {
            $info['count'] = $i;
            $info['height'] = $height_array4[$item][$i];
        }
    }

    return $info;
}

## 원격 이미지 엑박검사 || 유효성검사
function file_exit_check($url) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL,$url); // don't download content
    curl_setopt($curl, CURLOPT_NOBODY, 1);
    curl_setopt($curl, CURLOPT_FAILONERROR, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    return (curl_exec($curl)!==FALSE)? true : false;
}

function array_strlen_filter($array) {
    return array_filter($array, function($var) {
               if( strlen($var) == 2 ) {
                   return $var;
               }
    });
}

function array_strlen_filter2($array) {
    $temp = implode('', $array);

    $size = floor(strlen($temp) / 2);
    $numbers = str_split($temp, 2);

    return array_slice($numbers, 0 , $size);
}

function array_strlen_filter2_1($array) {
    $result = array();
    
    // Process each element in the given array.
    foreach ($array as $item) {
        // Check if the element contains an "X" (case insensitive)
        if (stripos($item, 'X') !== false) {
            // Remove all occurrences of "X" (or "x") and add the numeric part to the result.
            // For example, "3X" becomes "3", "10X" becomes "10".
            $clean = str_ireplace('X', '', $item);
            $result[] = $clean;
        } else {
            // Remove any non-digit characters (if any) from the item.
            $digits_only = preg_replace('/\D/', '', $item);
            
            // If the cleaned string is longer than 2 digits, split it into chunks of 2 digits.
            if (strlen($digits_only) > 2) {
                $chunks = str_split($digits_only, 2);
                foreach ($chunks as $chunk) {
                    // Only add chunks that have exactly 2 characters.
                    if (strlen($chunk) == 2) {
                        $result[] = $chunk;
                    }
                }
            } else {
                // For 1 or 2 digit strings, just add them to the result.
                $result[] = $digits_only;
            }
        }
    }
    
    return $result;
}

function naver_ocr_api($file_name, $file_url, $file_type) {
    if( !$file_name || !$file_url ) {
        return array();
    }

    if( !in_array($file_type, array('jpg','jpeg','png')) ) {
        return array();
    }

    $post_field = array();
    $post_field["version"] = "V2";
    $post_field["requestId"] = $file_name;
    $post_field["timestamp"] = time();
      
    // 첫 번째 코드와 동일
    $images = array("format" => $file_type, "name" => "demo", "url" => $file_url);
    // JSON Array를 연관 배열로 저장 키이름은 images
    $post_field["images"] = array($images);
    $curl = curl_init();
    $api_url = 'https://zgmsmnb1s8.apigw.ntruss.com/custom/v1/16034/455221c6cfa4c571ba167d55cdb681a9e9b0756a0c694689cbdb1a60b846cd95/general';

    $timeout = 10; // 1 second timeout
    $header = array(
        'Content-Type: application/json',
        'X-OCR-SECRET: cVpNYk50c0dKV2t2UlNyenJFVUlXUEJsbUpGSnRJSU0='
    );

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);// 헤더를 포함한다.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_field));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    $error = curl_error($curl);

    curl_close($curl);

    $response = json_decode($response);

    $text_array = array();
    $count = count($response->images[0]->fields);
    for( $i=0; $i < $count; $i++ ) {
        //$text = preg_replace("/[^0-9]*/s", "", $response->images[0]->fields[$i]->inferText);
        $text = preg_replace("/[^0-9Xx]+/", "", $response->images[0]->fields[$i]->inferText);
        if( $text ) {
            $text_array[] = $text;
        }
    }

    return $text_array;
}

function naver_ocr_api_text($file_name, $file_url, $file_type) {
    if( !$file_name || !$file_url ) {
        return array();
    }

    if( !in_array($file_type, array('jpg','jpeg','png')) ) {
        return array();
    }

    $post_field = array();
    $post_field["version"] = "V2";
    $post_field["requestId"] = $file_name;
    $post_field["timestamp"] = time();
      
    // 첫 번째 코드와 동일
    $images = array("format" => $file_type, "name" => "demo", "url" => $file_url);
    // JSON Array를 연관 배열로 저장 키이름은 images
    $post_field["images"] = array($images);
    $curl = curl_init();
    $api_url = 'https://zgmsmnb1s8.apigw.ntruss.com/custom/v1/16034/455221c6cfa4c571ba167d55cdb681a9e9b0756a0c694689cbdb1a60b846cd95/general';

    $timeout = 10; // 1 second timeout
    $header = array(
        'Content-Type: application/json',
        'X-OCR-SECRET: cVpNYk50c0dKV2t2UlNyenJFVUlXUEJsbUpGSnRJSU0='
    );

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);// 헤더를 포함한다.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_field));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    $error = curl_error($curl);

    curl_close($curl);

    $response = json_decode($response);

    $text_array = array();
    if (!empty($response->images[0]->fields)) {
        $count = count($response->images[0]->fields);
        for ($i = 0; $i < $count; $i++) {
            // Keep raw text (including potential '2X', '3X', etc.)
            $raw_text = $response->images[0]->fields[$i]->inferText;
            if ($raw_text) {
                $text_array[] = $raw_text;
            }
        }
    }

    return $text_array;
}

function naver_ocr_api_find_count($file_name, $file_url, $file_type) {
    if( !$file_name || !$file_url ) {
        return array();
    }

    if( !in_array($file_type, array('jpg','jpeg','png')) ) {
        return array();
    }

    $post_field = array();
    $post_field["version"] = "V2";
    $post_field["requestId"] = $file_name;
    $post_field["timestamp"] = time();
      
    // 첫 번째 코드와 동일
    $images = array("format" => $file_type, "name" => "demo", "url" => $file_url);
    // JSON Array를 연관 배열로 저장 키이름은 images
    $post_field["images"] = array($images);
    $curl = curl_init();
    $api_url = 'https://zgmsmnb1s8.apigw.ntruss.com/custom/v1/16034/455221c6cfa4c571ba167d55cdb681a9e9b0756a0c694689cbdb1a60b846cd95/general';

    $timeout = 10; // 1 second timeout
    $header = array(
        'Content-Type: application/json',
        'X-OCR-SECRET: cVpNYk50c0dKV2t2UlNyenJFVUlXUEJsbUpGSnRJSU0='
    );

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);// 헤더를 포함한다.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_field));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    if (!$response) {
        curl_close($curl);
        return 999;
    }
    curl_close($curl);

    $response = json_decode($response);
    if (!isset($response->images[0]->fields) || !is_array($response->images[0]->fields)) {
        return 99;
    }

    $lotto_cnt = 0;
    foreach ($response->images[0]->fields as $field) {
        $text = $field->inferText;
        if ($text == 'A.') $lotto_cnt = 1;
        if ($text == 'B.') $lotto_cnt = 2;
        if ($text == 'C.') $lotto_cnt = 3;
        if ($text == 'D.') $lotto_cnt = 4;
        if ($text == 'E.') $lotto_cnt = 5;
    }
    return $lotto_cnt;
}

function naver_ocr_api_find_count_oregon($file_name, $file_url, $file_type) {
    if( !$file_name || !$file_url ) {
        return array();
    }

    if( !in_array($file_type, array('jpg','jpeg','png')) ) {
        return array();
    }

    $post_field = array();
    $post_field["version"] = "V2";
    $post_field["requestId"] = $file_name;
    $post_field["timestamp"] = time();
      
    // 첫 번째 코드와 동일
    $images = array("format" => $file_type, "name" => "demo", "url" => $file_url);
    // JSON Array를 연관 배열로 저장 키이름은 images
    $post_field["images"] = array($images);
    $curl = curl_init();
    $api_url = 'https://zgmsmnb1s8.apigw.ntruss.com/custom/v1/16034/455221c6cfa4c571ba167d55cdb681a9e9b0756a0c694689cbdb1a60b846cd95/general';

    $timeout = 10; // 1 second timeout
    $header = array(
        'Content-Type: application/json',
        'X-OCR-SECRET: cVpNYk50c0dKV2t2UlNyenJFVUlXUEJsbUpGSnRJSU0='
    );

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);// 헤더를 포함한다.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_field));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    curl_close($curl);

    $response = json_decode($response);

    $lotto_cnt = 0;
    $count = count($response->images[0]->fields);
    $txt_count_1 = 0;
    $start_y_axis = 0;
    $txt_count_2 = 0;
    $end_y_axis = 0;
    for( $i=0; $i < $count; $i++ ) {
        //$text = preg_replace("/[^0-9]*/s", "", $response->images[0]->fields[$i]->inferText);
        $text = $response->images[0]->fields[$i]->inferText;
        $vertices = $response->images[0]->fields[$i]->boundingPoly->vertices;
        if( $text == "POWERBALL" || $text == "MEGA") {
            $json_string = json_encode($vertices, JSON_PRETTY_PRINT);
            $data = json_decode($json_string, true);
            foreach ($data as $point) {
                $start_y_axis = $point['y'];
            }
        }
        if( $text == "SINGLE" ) {
            $json_string = json_encode($vertices, JSON_PRETTY_PRINT);
            $data = json_decode($json_string, true);
            foreach ($data as $point) {
                $end_y_axis = $point['y'];
            }
        }
    }

    $lotto_cnt_calc = intdiv(($end_y_axis - $start_y_axis), 75);
    if ($lotto_cnt_calc == 7) {
        $lotto_cnt = 5;
    } else if ($lotto_cnt_calc == 6) {
        $lotto_cnt = 4;
    } else if ($lotto_cnt_calc == 5) {
        $lotto_cnt = 3;
    } else if ($lotto_cnt_calc == 4) {
        $lotto_cnt = 2;
    } else if ($lotto_cnt_calc == 3) {
        $lotto_cnt = 1;
    } else {
        $lotto_cnt = 0;
    }
    return $lotto_cnt;
}

function naver_ocr_api_yaxis($file_name, $file_url, $file_type) {
    if( !$file_name || !$file_url ) {
        return array();
    }

    if( !in_array($file_type, array('jpg','jpeg','png')) ) {
        return array();
    }

    $post_field = array();
    $post_field["version"] = "V2";
    $post_field["requestId"] = $file_name;
    $post_field["timestamp"] = time();
      
    // 첫 번째 코드와 동일
    $images = array("format" => $file_type, "name" => "demo", "url" => $file_url);
    // JSON Array를 연관 배열로 저장 키이름은 images
    $post_field["images"] = array($images);
    $curl = curl_init();
    $api_url = 'https://zgmsmnb1s8.apigw.ntruss.com/custom/v1/16034/455221c6cfa4c571ba167d55cdb681a9e9b0756a0c694689cbdb1a60b846cd95/general';

    $timeout = 10; // 1 second timeout
    $header = array(
        'Content-Type: application/json',
        'X-OCR-SECRET: cVpNYk50c0dKV2t2UlNyenJFVUlXUEJsbUpGSnRJSU0='
    );

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);// 헤더를 포함한다.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_field));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    $error = curl_error($curl);

    curl_close($curl);

    $response = json_decode($response);

    $text_array = array();
    $yaxis = 0;
    $count = count($response->images[0]->fields);
    $txt_cnt = 0;
    for( $i=0; $i < $count; $i++ ) {
        //$text = preg_replace("/[^0-9]*/s", "", $response->images[0]->fields[$i]->inferText);
        $text = $response->images[0]->fields[$i]->inferText;
        $vertices = $response->images[0]->fields[$i]->boundingPoly->vertices;
        if( $text == "POWER" ) {
            $txt_cnt += 1; 
            $json_string = json_encode($vertices, JSON_PRETTY_PRINT);
            $data = json_decode($json_string, true);
            foreach ($data as $point) {
                $yaxis = $point['y'];
            }
            break;
        }
        if( $text == "MEGA" ) {
            $txt_cnt += 1;
            if ($txt_cnt == 2) {
                $json_string = json_encode($vertices, JSON_PRETTY_PRINT);
                $data = json_decode($json_string, true);
                foreach ($data as $point) {
                    $yaxis = $point['y'];
                }
            }
        }
    }
    return $yaxis;
}

function naver_ocr_api_yaxis_oregon($file_name, $file_url, $file_type) {
    if( !$file_name || !$file_url ) {
        return array();
    }

    if( !in_array($file_type, array('jpg','jpeg','png')) ) {
        return array();
    }

    $post_field = array();
    $post_field["version"] = "V2";
    $post_field["requestId"] = $file_name;
    $post_field["timestamp"] = time();
      
    // 첫 번째 코드와 동일
    $images = array("format" => $file_type, "name" => "demo", "url" => $file_url);
    // JSON Array를 연관 배열로 저장 키이름은 images
    $post_field["images"] = array($images);
    $curl = curl_init();
    $api_url = 'https://zgmsmnb1s8.apigw.ntruss.com/custom/v1/16034/455221c6cfa4c571ba167d55cdb681a9e9b0756a0c694689cbdb1a60b846cd95/general';

    $timeout = 10; // 1 second timeout
    $header = array(
        'Content-Type: application/json',
        'X-OCR-SECRET: cVpNYk50c0dKV2t2UlNyenJFVUlXUEJsbUpGSnRJSU0='
    );

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);// 헤더를 포함한다.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_field));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    $error = curl_error($curl);

    curl_close($curl);

    $response = json_decode($response);

    $text_array = array();
    $yaxis = 0;
    $count = count($response->images[0]->fields);
    $txt_cnt = 0;
    for( $i=0; $i < $count; $i++ ) {
        //$text = preg_replace("/[^0-9]*/s", "", $response->images[0]->fields[$i]->inferText);
        $text = $response->images[0]->fields[$i]->inferText;
        $vertices = $response->images[0]->fields[$i]->boundingPoly->vertices;
        if( $text == "POWERBALL" ) {
            $txt_cnt += 1; 
            $json_string = json_encode($vertices, JSON_PRETTY_PRINT);
            $data = json_decode($json_string, true);
            foreach ($data as $point) {
                $yaxis = $point['y'];
            }
        }
        if( $text == "MEGA" ) {
            $txt_cnt += 1;
            $json_string = json_encode($vertices, JSON_PRETTY_PRINT);
            $data = json_decode($json_string, true);
            foreach ($data as $point) {
                $yaxis = $point['y'];
            }
        }
    }

    return $yaxis;
}

function naver_ocr_api_show_json($file_name, $file_url, $file_type) {
    if( !$file_name || !$file_url ) {
        return array();
    }

    if( !in_array($file_type, array('jpg','jpeg','png')) ) {
        return array();
    }

    $post_field = array();
    $post_field["version"] = "V2";
    $post_field["requestId"] = $file_name;
    $post_field["timestamp"] = time();
      
    // 첫 번째 코드와 동일
    $images = array("format" => $file_type, "name" => "demo", "url" => $file_url);
    // JSON Array를 연관 배열로 저장 키이름은 images
    $post_field["images"] = array($images);
    $curl = curl_init();
    $api_url = 'https://zgmsmnb1s8.apigw.ntruss.com/custom/v1/16034/455221c6cfa4c571ba167d55cdb681a9e9b0756a0c694689cbdb1a60b846cd95/general';

    $timeout = 10; // 1 second timeout
    $header = array(
        'Content-Type: application/json',
        'X-OCR-SECRET: cVpNYk50c0dKV2t2UlNyenJFVUlXUEJsbUpGSnRJSU0='
    );

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_URL, $api_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_HEADER, 0);// 헤더를 포함한다.
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($post_field));
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);

    $response = curl_exec($curl);
    $error = curl_error($curl);

    curl_close($curl);

    $response = json_decode($response);

    $pretty_json = json_encode($response, JSON_PRETTY_PRINT);

    return $pretty_json;
}