<?php
/**
 * Created by PhpStorm.
 * User: JairMunoz
 * Date: 31/05/2018
 * Time: 8:39 AM
 */

class Mail_reader
{
    private $connect_to;
    private $connection;
    private $user;
    private $password;
    private $emails;
    private $unseen;

    public function __construct($params)
    {
    }

    public function connect($params)
    {
        $this->connect_to = $params['connect_to'];
        $this->user = $params['user'];
        $this->password = $params['password'];
        $this->connection = imap_open($this->connect_to, $this->user, $this->password);
        if (!$this->connection) {
            throw new Exception('Error de conexion al servidor de correo', 12);
        }
    }

    public function email($number)
    {
        $email = imap_fetch_overview($this->connection, $number, 0);
        return $email[0];
    }

    public function message($number)
    {
        $info = imap_fetchstructure($this->connection, $number, 0);

        if ($info->encoding == 3) {
            $message = base64_decode(imap_fetchbody($this->connection, $number, 1));
        } elseif ($info->encoding == 4) {
            $message = imap_qprint(imap_fetchbody($this->connection, $number, 1));
        } else {
            $message = imap_fetchbody($this->connection, $number, 1);
        }
        //$message = imap_fetchbody($this -> connection, $number, 2);
        return decode_qprint($message);
    }

    /**
     * @return resource
     */
    public function ultimo_mensaje()
    {
        //Check no.of.msgs
        $num = 1; #imap_num_msg($this->connection);
        //if there is a message in your inbox
        if ($num > 0) {
            //read that mail recently arrived
            echo imap_qprint(imap_body($this->connection, $num));
        }
        echo '<br>-------- <br>--';
        $mensaje = imap_fetchbody($this->connection, $num, 1);
        echo nl2br(strip_tags($mensaje, '<p>')); // Util para los mensajes HTML, los transforma en texto plano


        $struct = imap_fetchstructure($this->connection, $num);

        $i = 1;
        while (imap_fetchbody($this->connection, $num, $i)) {
            $struct->parts[$i - 1] = imap_bodystruct($this->connection, $num, $i);
            $j = 1;
            while (imap_fetchbody($this->connection, $num, "$i.$j")) {
                $struct->parts[$i - 1]->parts[$j - 1] = imap_bodystruct($this->connection, $num, "$i.$j");
                $j++;
            }
            $i++;
        }
        echo json_encode($struct, true);

    }

    public function list_messages()
    {
        $mails = [];
        $i = 0;
        $emails = imap_sort($this->connection, SORTDATE, 1, 0, 'ALL');
        foreach ($emails as $email_number) {
            $mail = imap_headerinfo($this->connection, $email_number);
            #$overview = imap_fetch_overview($this->connection, $email_number, 0);
            #var_dump($mail);
            $name = '';
            if (isset($mail->from[0]->personal)) {
                $name = $mail->from[0]->personal;
            }
            $mails[] = array(
                'id' => trim($mail->Msgno),
                'subject' => iconv_mime_decode($mail->subject), 'date' => $mail->date,
                'from' => [
                    "name" => iconv_mime_decode($name),
                    'email' => $mail->from[0]->mailbox . '@' . $mail->from[0]->host
                ],
                'otros' => $mail
            );
            if ($i++ > 19) {
                break;
            }
        }
        return $mails;
    }

    public function list_messages_1()
    {
        $i = 0;
        $emails = imap_search($this->connection, 'ALL');
        echo '<div class="row"><div class="col-sm-20"><table class="table table-bordered table-condensed">';
        foreach ($emails as $email_number) {
            echo '<tr>';
            $overview = imap_fetch_overview($this->connection, $email_number, 0);
            echo '<td>' . $i++ . '</td>';
            echo '<td> - ' . json_encode($overview[0], true) . '</td>';
            echo '<td>' . $overview[0]->from . '</td>';
            echo '</tr>';

        }
        echo '<table></div></div>';
    }

    public function __destruct()
    {
        if ($this->connection) {
            imap_close($this->connection);
        }
    }

    public function __get($var)
    {
        $temp = strtolower($var);
        if (property_exists('mail_reader', $temp)) {
            return $this->$temp;
        }
        return NULL;
    }

}

/*Funcion para decodificar los mensajes*/
function decode_qprint($str)
{
    $str = preg_replace("/\=([A-F][A-F0-9])/", "%$1", $str);
    $str = urldecode($str);
    $str = utf8_encode($str);
    return $str;
}