<?php

require_once '../library/DateTime.php';
require_once('lib/php-imap-master/src/ImapMailbox.php');

class AccountInfo
{
    public $host;
    public $username;
    public $password;
    public $protocol;
    public $imapPath;

    public function __construct($host, $username, $password, $protocol)
    {
        $this->hostname = $host;
        $this->username = $username;
        $this->password = $password;
        $this->protocol = $protocol;
        $this->imapPath = '{' . $host . '/' . $protocol . '/ssl}INBOX';
    }
}

class HeaderManager
{
    protected $accountId;
    protected $subject;
    protected $from;
    protected $to;
    protected $date;
    protected $message_id;
    protected $size;
    protected $uid;
    protected $msgno;
    protected $recent;
    protected $flagged;
    protected $answered;
    protected $deleted;
    protected $seen;
    protected $draft;
    protected $udate;

    protected function getAccountInfo($accountId)
    {
        $select = $this->_dbAdapter
            ->select()
            ->from('ui_account')
            ->where('id = ' . $this->_dbAdapter->quote($accountId, 'INTEGER'));

        $accountRow = $this->_dbAdapter->fetchRow($select);

        return new AccountInfo($accountRow['serverAddress'], $accountRow['accountEmail'],
                               $accountRow['password'], $accountRow['protocol']);
    }


    public function getAcctInfo()
    {
        return $this->getAccountInfo(1);
    }



    protected function populateParameters()
    {
        if ($this->isJson())
        {
            $inputJson = file_get_contents('php://input');
            $input = json_decode( $inputJson, TRUE );

            $this->accountId =  $this->getJsonParam($input, 'accountId', '');
            $this->subject =    $this->getJsonParam($input, 'subject', '');
            $this->from =       $this->getJsonParam($input, 'from', '');
            $this->to =         $this->getJsonParam($input, 'to', '');
            $this->date =       $this->getJsonParam($input, 'date', '');
            $this->message_id = $this->getJsonParam($input, 'message_id', '');
            $this->size =       $this->getJsonParam($input, 'size', '');
            $this->uid =        $this->getJsonParam($input, 'uid', '');
            $this->msgno =      $this->getJsonParam($input, 'msgno', '');
            $this->recent =     $this->getJsonParam($input, 'recent', '');
            $this->flagged =    $this->getJsonParam($input, 'flagged', '');
            $this->answered =   $this->getJsonParam($input, 'answered', '');
            $this->deleted =    $this->getJsonParam($input, 'deleted', '');
            $this->seen =       $this->getJsonParam($input, 'seen', '');
            $this->draft =      $this->getJsonParam($input, 'draft', '');
            $this->udate =      $this->getJsonParam($input, 'udate', '');
        }
        else
        {
            $this->accountId =  $this->_getParam('accountId','');
            $this->subject =    $this->_getParam('subject','');
            $this->from =       $this->_getParam('from','');
            $this->to =         $this->_getParam('to','');
            $this->date =       $this->_getParam('date','');
            $this->message_id = $this->_getParam('message_id','');
            $this->size =       $this->_getParam('size','');
            $this->uid =        $this->_getParam('uid','');
            $this->msgno =      $this->_getParam('msgno','');
            $this->recent =     $this->_getParam('recent','');
            $this->flagged =    $this->_getParam('flagged','');
            $this->answered =   $this->_getParam('answered','');
            $this->deleted =    $this->_getParam('deleted','');
            $this->seen =       $this->_getParam('seen','');
            $this->draft =      $this->_getParam('draft','');
            $this->udate =      $this->_getParam('udate','');
        }
    }

    public function indexAction()
    {
        try
        {

//            $imapPath = '{imap.gmail.com:993/imap/ssl}INBOX';
//            $username = 'tcga00@gmail.com';
//            $password = 'Peru.995';
//            $attachmentDir = dirname(__FILE__) . '/attachments';

            $accountId = 1;
            $accountInfo = $this->getAccountInfo($accountId);

            $imapPath = $accountInfo->imapPath;
            $username = $accountInfo->username;
            $password = $accountInfo->password;

            $attachmentDir = dirname(__FILE__) . '/attachments';

            $mailbox = new ImapMailbox($imapPath, $username, $password, $attachmentDir, 'utf-8');

            print("\nINBOX INFO: ===========================================\n");

            $mailboxInfo = $mailbox->getMailboxInfo();
            print_r($mailboxInfo);


            // Get some mail
            // $mailsIds = $mailbox->searchAndSortMails('SUBJECT "Gmail"');
            //sequence-set
            $mailsIds = $mailbox->searchAndSortMails('ALL');
            // $mailsIds = $mailbox->searchMailbox('UID 3');
            // $mailsIds = $mailbox->searchAndSortMails('UID "3:*"');
            if(!$mailsIds)
            {
                die('Mailbox is empty');
            }

            print("START EMAIL UIDs: ===========================================<br />");
            print_r($mailsIds);
            // $mailbox->markMailsAsRead($mailsIds);
            print("END EMAIL UIDs: ===========================================<br />");

            $mailId = reset($mailsIds);

            if (!empty($mailsIds))
            {
                // for every email...
                foreach($mailsIds as $mailId)
                {
                    echo '<br />EMAIL_NUMBER <hr />';
                    print_r($mailId);

                    //$mailbox->markMailAsUnread($mailId);

                    // get header information
                    $mailsInfo = $mailbox->getMailsInfo(array($mailId));

                    //$mail = $mailbox->getMail($mailId);
                    //$attachments = $mail->getAttachments();

                    echo '<br />Mail Info <hr />';
                    print_r($mailsInfo);
                    echo '<hr />';

                    // echo '<br />MESSAGE <hr />';
                    // print_a($mail);
                    // echo '<hr />';

                    // echo '<br />ATTACHMENTS<hr />';
                    // print_a($attachments);
                    // echo '<hr />';
               }
            }

            $this->renderJson($mailboxInfo);

            //////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////


            $accountId = $this->_getParam('accountId');

            if (null === $accountId)
            {
                $sql = 'SELECT * from ui_emailheader';
                $accounts = $this->_dbAdapter->fetchAll($sql);
                $this->renderJson($accounts);
            }
            else
            {
                $sql = 'SELECT * from ui_emailheader where accountId=:accountId';
                $stmt = $this->_dbAdapter->prepare($sql);
                $stmt->bindParam('accountId', $accountId);
                $stmt->execute();
                $result = $stmt->fetchAll();
                $this->renderJson($result);
            }
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }

    }

    public function getAction()
    {
        $id = $this->_getParam('id', 0);
        $sql = 'SELECT * from ui_emailheader where id=:id';

        try
        {
            $stmt = $this->_dbAdapter->prepare($sql);
            $stmt->bindParam('id', $id);
            $stmt->execute();
            $result = $stmt->fetchObject();
            $this->renderJson($result);
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }
    }

    public function postAction()
    {
        try
        {
            $sql = <<<EOD
INSERT INTO ui_emailheader (
`accountId`,
`subject`,
`from`,
`to`,
`date`,
`message_id`,
`size`,
`uid`,
`msgno`,
`recent`,
`flagged`,
`answered`,
`deleted`,
`seen`,
`draft`,
`udate`,
) VALUES (
:accountId,
:subject,
:from,
:to,
:date,
:message_id,
:size,
:uid,
:msgno,
:recent,
:flagged,
:answered,
:deleted,
:seen,
:draft,
:udate
);
EOD;

            $this->populateParameters();

            $stmt = $this->_dbAdapter->prepare($sql);

            $stmt->bindParam('accountId',  $this->accountId);
            $stmt->bindParam('subject',    $this->subject);
            $stmt->bindParam('from',       $this->from);
            $stmt->bindParam('to',         $this->to);
            $stmt->bindParam('date',       $this->date);
            $stmt->bindParam('message_id', $this->message_id);
            $stmt->bindParam('size',       $this->size);
            $stmt->bindParam('uid',        $this->uid);
            $stmt->bindParam('msgno',      $this->msgno);
            $stmt->bindParam('recent',     $this->recent);
            $stmt->bindParam('flagged',    $this->flagged);
            $stmt->bindParam('answered',   $this->answered);
            $stmt->bindParam('deleted',    $this->deleted);
            $stmt->bindParam('seen',       $this->seen);
            $stmt->bindParam('draft',      $this->draft);
            $stmt->bindParam('udate',      $this->udate);

            $success = $stmt->execute();
            $id = $this->_dbAdapter->lastInsertId();

            $select = $this->_dbAdapter
                ->select()
                ->from('ui_emailheader')
                ->where('id = ' . $this->_dbAdapter->quote($id, 'INTEGER'));

            $this->renderJson($this->_dbAdapter->fetchRow($select));
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }
    }

    public function putAction()
    {
        $id = $this->_getParam('id', 0);

        try
        {
            $sql = <<<EOD
UPDATE ui_emailheader SET
`accountId`  = :accountId,
`subject`    = :subject,
`from`       = :from,
`to`         = :to,
`date`       = :date,
`message_id` = :message_id,
`size`       = :size,
`uid`        = :uid,
`msgno`      = :msgno,
`recent`     = :recent,
`flagged`    = :flagged,
`answered`   = :answered,
`deleted`    = :deleted,
`seen`       = :seen,
`draft`      = :draft,
`udate`      = :udate
WHERE id=:id
EOD;

            $this->populateParameters();

            $stmt = $this->_dbAdapter->prepare($sql);

            $stmt->bindParam('accountId',  $this->accountId);
            $stmt->bindParam('subject',    $this->subject);
            $stmt->bindParam('from',       $this->from);
            $stmt->bindParam('to',         $this->to);
            $stmt->bindParam('date',       $this->date);
            $stmt->bindParam('message_id', $this->message_id);
            $stmt->bindParam('size',       $this->size);
            $stmt->bindParam('uid',        $this->uid);
            $stmt->bindParam('msgno',      $this->msgno);
            $stmt->bindParam('recent',     $this->recent);
            $stmt->bindParam('flagged',    $this->flagged);
            $stmt->bindParam('answered',   $this->answered);
            $stmt->bindParam('deleted',    $this->deleted);
            $stmt->bindParam('seen',       $this->seen);
            $stmt->bindParam('draft',      $this->draft);
            $stmt->bindParam('udate',      $this->udate);

            $stmt->bindParam('id',         $id);

            $success = $stmt->execute();

            $select = $this->_dbAdapter
                ->select()
                ->from('ui_emailheader')
                ->where('id = ' . $this->_dbAdapter->quote($id, 'INTEGER'));

            $this->renderJson($this->_dbAdapter->fetchRow($select));
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }
    }

    public function deleteAction()
    {
        $id = $this->_getParam('id', 0);

        try
        {
            $sql = 'DELETE FROM ui_emailheader WHERE id=:id';

            $stmt = $this->_dbAdapter->prepare($sql);
            $stmt->bindParam('id', $id);
            $success = $stmt->execute();
            $this->renderJson($this->_statusOK);
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }
    }
}

$headerManager = new HeaderManager();

print_r($headerManager->getAcctInfo());
