<?php

namespace Flyerimage\Core\Util;

use DateTime;
use Throwable;
use GeoIp2\Database\Reader;

/**
 * Helper class
 * @author Pritom Kumar Mondal <pritomkucse@gmail.com>
 */
class Helper
{
    static function is_valid_string( $data ) {
        return  !is_null( $data ) && mb_strlen( Helper::get_valid_string( $data ) ) > 0;
    }

    static function get_valid_string( $data ) {
        if (is_null( $data )) {
            return "";
        }
        if (is_array( $data )) {
            return json_encode( $data );
        }
        return  trim( strval( $data ) );
    }

    static function get_param_value_from_get( $name, $default = null ) {
        return isset( $_GET[$name] ) ? sanitize_text_field( wp_unslash( $_GET[$name] ) ) : $default;
    }

    static function print_r2( $data ) {
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }

    static function is_positive_integer( $data ) {
        return Helper::is_valid_string( $data ) && preg_match( '/^[0-9]{0,8}$/', $data );
    }

    static function is_positive_number($data) {
        return Helper::is_valid_string($data) && preg_match('/^[0-9]{0,8}(\.[0-9]{1,6})?$/', $data);
    }

    static function is_positive_number_8_12($data) {
        return Helper::is_valid_string($data) && preg_match('/^[0-9]{0,8}(\.[0-9]{1,12})?$/', $data);
    }

    static function is_valid_number($data) {
        return Helper::is_valid_string($data) && preg_match('/^(-?)[0-9]{0,8}(\.[0-9]{1,6})?$/', $data);
    }

    static function is_valid_integer($data) {
        return Helper::is_valid_string($data) && preg_match('/^(-?)[0-9]{0,8}$/', $data);
    }

    static function is_valid_table_id($data) {
        return Helper::is_valid_string($data) && preg_match('/^[0-9]{0,15}$/', $data);
    }

    static function is_valid_table_id_concat($data) {
        return Helper::is_valid_string($data) && preg_match('/^(-?)\d+(?:,\d+)*$/', $data);
    }

    static function get_sub_string($string, $length) {
        if (is_null($string)) {
            return $string;
        }
        return self::is_valid_string($string) && $length > 0 && mb_strlen($string) > $length ? mb_substr($string, 0, $length) : $string;
    }

    static function get_valid_date_string($var) {
        if (is_null($var) || !preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $var)) {
            return null;
        }
        $date = DateTime::createfromformat('Y-m-d H:i:s', $var." 00:00:00");
        if ($date === false) {
            return null;
        }
        return $date->format('Y-m-d') == $var ? $date : null;
    }

    static function is_valid_date_string_mdy($var) {
        if (is_null($var) || !preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/", $var)) {
            if (is_null($var) || !preg_match("/^[0-9]{2}\/[0-9]{2}\/[0-9]{2}$/", $var)) {
                return null;
            }
            $date = DateTime::createfromformat('m/d/y', $var);
            if ($date === false) {
                return null;
            }
            return $date->format('m/d/y') == $var ? $date : null;
        }
        $date = DateTime::createfromformat('m/d/Y', $var);
        if ($date === false) {
            return null;
        }
        return $date->format('m/d/Y') == $var ? $date : null;
    }

    static function get_valid_time_string($var) {
        if (is_null($var) || !preg_match("/^[0-9]{2}:[0-9]{2}$/", $var)) {
            return null;
        }
        $date = DateTime::createfromformat('Y-m-d H:i:s', "2020-01-01 $var:00");
        if ($date === false) {
            return null;
        }
        return $date->format('H:i') == $var ? $var : null;
    }

    static function parse_json_string($str, $default = null) {
        if (!Helper::is_valid_string($str)) {
            return $default;
        }
        $str = json_decode($str, true);
        if ($str == null) {
            return $default;
        }
        return $str;
    }

    static function get_country_by_ip($ip) {
        try {
            if ($ip == "::1") {
                return "Unknown";
            }
            $reader = new Reader(FLYER_IMAGE_PATH."/src/GeoLite2-Country.mmdb");
            $record = $reader->country($ip);
            return $record->country->isoCode;
        }
        catch (Throwable $e) {
            self::log_throwable_few_lines($e);
            return "Unknown";
        }
    }

    /**
     * @param $throwable Throwable
     * @param int $line
     */
    static function log_throwable_few_lines($throwable, $line = 3) {
        // Only log in debug mode
        if (!defined('WP_DEBUG') || !WP_DEBUG) {
            return;
        }
        
        $trace = explode("\n", $throwable->getTraceAsString());
        $size = count($trace);
        $output = [];
        $output[] = "--------------------------EXCEPTION-START------------------------------------------------------------------------------------------------";
        $output[] = "-->Error=[".$throwable->getMessage()."]-->File=".$throwable->getFile()."#".$throwable->getLine();
        for ($index = 0; $index < $line; $index++) {
            $output[] = $size > $index ? trim($trace[$index]) : "";
        }
        $output[] = "-->Error=[".$throwable->getMessage()."]-->File=".$throwable->getFile()."#".$throwable->getLine();
        $output[] = "--------------------------EXCEPTION-END--------------------------------------------------------------------------------------------------";
        error_log ( implode("\n", $output) );
    }

    static function log($message) {
        // Only log in debug mode
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log ( $message );
        }
    }
}