<?php


class schaden_helper_functions{

    /**
     * @var array $rep_general character to replace in general
     * @var array $rep_kz character to replace in $kennzeichen
     * @var array $rep_kn character to replace in $kundennummer
     *
     * @var array $find_az pattern to find Aktenzeichen ( 01234/56 )
     * @var array $find_kz pattern to find Kennzeichen ( AB-DC 1234, AB - CD 1234, AB CD 1234 )
     * @var array $find_kn pattern to find Kundennummer ( 12345.... )
     * @var array $find_kb pattern to find Kennbuchstabe ( A )
     */

    public static $rep_general = [',',';','RE:','Re:','WG:','Wg:','AW:','Aw:'];
    public static $rep_kz = ['Kennzeichen:','Kennz:','Kennz.:','Kenn.:','KZ:','Kz:','Kz.:','K.:'];
    public static $rep_kn = ['Kd-Nr.:','Kd.-Nr.:','Kd.-Nr.','Kdnr.:','Kdr.:',];
    public static $find_az = '#\d\d\d\d\d/\d\d#';
    public static $find_kz = '#([A-Za-zöäüÖÄÜ]{1,3})([\s]{0,1})([-]{0,1})([\s]{0,1})([A-Za-zöäüÖÄÜ]{1,3})([\s]{0,1})([0-9]{1,4})#';
    public static $find_kn = '#[0-9]{5,}#';
    public static $find_kb = '#\s[A-E]\W#';

    /**
     * @param string $subject collected from incoming mail
     * @return array
     */
    public static function process_email_subject( string $subject )
    {
        if( !$subject ){
            return [];
        }

        $processed_subject = [];
        $processed_subject['full']= esc_attr( normalize_whitespace( $subject ) );

        $subject = str_replace(
            self::$rep_general ,
            '',
            $subject
        );
        /*
         * extract az number
         * match: "01234/"
         */
        $az_number = preg_match(
            self::$find_az,
            $subject,
            $match
        );

        if( $az_number ){
            $m = reset( $match );
            $subject = str_replace( $m, '', $subject);
            $az = explode('/', $m );

            $processed_subject['aznr'] = !empty( $az[0] )
                ? sprintf(
                    '%s/',
                    esc_attr( normalize_whitespace( $az[0] ) )
                )
                : false;

            $processed_subject['azjahr'] = !empty( $az[1] )
                ? sprintf(
                    '%s',
                    absint( esc_attr( normalize_whitespace( $az[1] ) ) ) + 2000
                )
                : false;

            $processed_subject['emailz'] = !empty( $az[0] ) && !empty( $az[1] )
                ? sprintf(
                    '%s/%s',
                    esc_attr( normalize_whitespace( $az[0] ) ),
                    esc_attr( normalize_whitespace( $az[1] ) )
                )
                : false;
        }else{
            return [];
        }

        /*
         * extract kennzeichen
         * match: "AB-DC 1234, AB - CD 1234, AB CD 1234"
         */
        $kennzeichen = preg_match(
            self::$find_kz,
            $subject,
            $match
        );

        if( $kennzeichen ){
            $k = reset( $match );
            $subject = str_replace( $k, '', $subject);
            $subject = str_replace( self::$rep_kz, '', $subject);
            $processed_subject['kennz'] = esc_attr( normalize_whitespace( $k ) );
        }

        /*
         * extract kundennummer
         * match: "12345....."
         */
        $kundennummer = preg_match(
            self::$find_kn,
            $subject,
            $match
        );

        if( $kundennummer ){
            $k = reset( $match );
            $subject = str_replace( $k, '', $subject);
            $subject = str_replace( self::$rep_kn, '', $subject);
            $processed_subject['kndnr'] = esc_attr( normalize_whitespace( $k ) );
        }

        /*
         * extract kennbuchstabe
         * match: "A"
         */
        $kennbuchstabe = preg_match(
            self::$find_kb,
            $subject,
            $match
        );

        if( $kennbuchstabe ){
            $k = reset( $match );
            $subject = str_replace( $k, '', $subject);
            $processed_subject['casestatus'] = esc_attr( normalize_whitespace( $k ) );
        }

        $processed_subject['aktenbezeichnung']= esc_attr( normalize_whitespace( $subject ) );

        $standard = [
            'full'  => '',
            'aznr'  => '',
            'azjahr'=> '',
            'emailz'    => '',
            'kennz'    => '',
            'aktenbezeichnung' => '',
            'casestatus' => '',
        ];

        return wp_parse_args( $processed_subject, $standard );

    }

    /**
     * @param string $content
     * @return string
     */
    public static function process_email_content( string $content )
    {
        return $content;
    }

    /**
     * @param string $emailz
     * @return array|string
     */
    public static function process_upload_directory( string $emailz )
    {
        $upload_dir = wp_get_upload_dir();
        $upload_dir = sprintf('%s/anhang/%s',
            $upload_dir['basedir'],
            sanitize_file_name( $emailz )
        );
        $upload_dir = trailingslashit( $upload_dir );

        if( !file_exists( $upload_dir ) ){
            mkdir( $upload_dir );
        }

        return $upload_dir;
    }

    /**
     * @param string $attachment_name
     * @param array $allowed_filetypes
     * @return bool|string
     * @throws Exception
     */
    public static function process_attachment_name( string $attachment_name, array $allowed_filetypes )
    {
        $type = wp_check_filetype( $attachment_name );
        $type = strtolower( $type['ext'] );

        if( !in_array( $type, $allowed_filetypes ) ) {
            return false;
        }

        if( !$attachment_name ){
            return false;
        }

        $random = bin2hex(random_bytes(10));

        $hashname = $random .'_'. wp_hash( $attachment_name ) . '.' . $type;

        return $hashname;
    }

    /**
     * @param int $postid
     * @param string $nachricht
     * @param array $anhang
     * @return bool|int
     */
    public static function save_processed_mail(
        int $postid,
        string $nachricht,
        array $anhang
    )
    {
        global $wpdb;

        $postid     = absint( $postid );
        $nachricht  = wp_kses_post( $nachricht );
        $anhang     = serialize( $anhang );
        $time       = date('Y-m-d H:i:s');

        $table_name = $wpdb->prefix . 'akte';

        $insert_data   = $wpdb->query(
            $wpdb->prepare(
                "INSERT INTO $table_name SET postid=%d,nachricht=%s,anhang=%s,eintrag=%s",
                        $postid, $nachricht,$anhang,$time
            ), OBJECT
        );

        return $insert_data;

    }

}