<?php

defined( 'ABSPATH' ) || exit;

use Ddeboer\Imap\Server;

class schaden_mail_abruf{

    public $data = "";
    public $server  = "imap.strato.de";
    public $port    = "993";
    public $user    = "backend2@Schadenlounge.de";
    public $pw      = "KTE7syMN?6825EtBtQ";
    public $box     = "INBOX";
    public $box2    = "ungueltig";

    public $mail_server = null; // Mailserver Connection
    public $mail_conn   = null; // Mailbox Connection
    public $mail_box    = null; // Mailbox INBOX
    public $mail_box2   = null; // Mailbox ungueltig

    public $allowed_filetypes = ['pdf','xlsx','xls','csv','odf','jpg','jpeg','png'];

    public function __construct()
    {
        add_action('SA_cron_runner', [$this ,'load_mail'] );
    }

    public function load_mail( )
    {
        if( get_option('SA_lock_bit', false ) == true ) {
            return;
        }

        update_option('SA_lock_bit', true, false );

        include_once SA_VEN_PATH . 'autoload.php';
        // https://github.com/ddeboer/imap

        /*
         * connect to mailserver
         */
        $this->mail_server = new Server(
            $this->server,
            $this->port
        );
        /*
         * Login in mailbox
         */
        $this->mail_conn = $this->mail_server->authenticate(
            $this->user,
            $this->pw
        );
        /*
         * connect to INBOX
         */
        $this->mail_box = $this->mail_conn->getMailbox(
            $this->box
        );
        /*
         * connect to "ungueltig"
         */
        $this->mail_box2 = $this->mail_conn->getMailbox(
            $this->box2
        );
        /**
         * check counter in INBOX
         */
        $counter = $this->mail_box->count();
        if( $counter == 0 ){
            $this->remove_lock();
            return;
        }
        /*
         * get oldest message first
         */
        $messages = $this->mail_box->getMessages();

        if( !$messages ){
            $this->remove_lock();
            return;
        }

        foreach($messages as $message ) {
            /*
             * process subject to array values
             */
            $subject = schaden_helper_functions::process_email_subject($message->getSubject());

            if ( !$subject || empty( $subject )) {
                $message->move( $this->mail_box2 );
                continue;
            }
            /*
             * process email content
             */
            $content = schaden_helper_functions::process_email_content($message->getBodyText());
            /*
             * get/create upload directory
             */
            $upload_dir = schaden_helper_functions::process_upload_directory($subject['emailz']);
            /*
             * get all mail attachment
             */
            $attachments = $message->getAttachments();
            /*
             * process mail attachment
             */
            $attach_details = [];
            if ($attachments) {

                foreach ($attachments as $attachment) {

                    $original_name = esc_attr($attachment->getFilename());

                    try {
                        $name = schaden_helper_functions::process_attachment_name(
                            $original_name,
                            $this->allowed_filetypes
                        );
                    } catch (Exception $e) {
                        continue;
                    }

                    if (!$name) {
                        continue;
                    }

                    $upload = file_put_contents(
                        $upload_dir . $name,
                        $attachment->getDecodedContent()
                    );

                    if ($upload) {
                        $attach_details[] = [$original_name, $name];
                    }

                }

            }
            /*
             * find post by meta value "emailz" from email subject
             */
            $args = [
                'posts_per_page' => 1,
                'post_type' => 'zt_lawyersportal',
                'meta_key' => 'emailz',
                'meta_value' => $subject['emailz']
            ];

            /**
             * @var $akten WP_Post
             */
            $akten = get_posts($args);

            if ($akten) {
                foreach ($akten as $akte) {
                    $eintrag = schaden_helper_functions::save_processed_mail(
                        $akte->ID,
                        $content,
                        $attach_details
                    );
                }
            } else {
                $defaults = [
                    'post_author' => 0,
                    'post_content' => '',
                    'post_title' => $subject['aktenbezeichnung'] . ' ' . $subject['casestatus'],
                    'post_excerpt' => '',
                    'post_status' => 'publish',
                    'post_type' => 'zt_lawyersportal',
                    'comment_status' => 'closed',
                    'ping_status' => 'closed',
                    'meta_input' => [
                        'aznr' => $subject['aznr'],
                        'azjahr' => $subject['azjahr'],
                        'emailz' => $subject['emailz'],
                        'casestatus' => $subject['casestatus'],
                        'full' => $subject['full'],
                        'kennz' => $subject['kennz'],
                    ]
                ];
                $id = wp_insert_post($defaults);

                $eintrag = schaden_helper_functions::save_processed_mail(
                    $id,
                    $content,
                    $attach_details
                );
            }

            if ($eintrag) {
                $message->delete();
            }
        }

        $this->mail_conn->expunge();
        $this->remove_lock();
    }

    public function remove_lock()
    {
        update_option('SA_lock_bit', false, false );
    }

}


# echo '<pre>'.print_r( $val, true ).'</pre><hr>';