<?php

require_once 'library/DateTime.php';
require_once 'library/imap/ImapMailbox.php';

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

    public function __construct($host, $username, $password, $protocol, $mailbox)
    {
        $charterSSO = new CharterSSO();
        $password = $charterSSO->decodeString($password);

        $this->hostname = $host;
        $this->username = $username;
        $this->password = $password;
        $this->protocol = $protocol;
        $this->mailbox  = $mailbox;
        $this->imapPath = '{' . $host . '/' . $protocol . '/ssl}' . $mailbox;
    }
}

class Inbox_EmailHeaderController extends Inbox_Controller_Base
{
    public function init()
    {
        parent::init();

        $this->_table = 'ui_emailheader';

        $this->_columns = array(
            'accountId'  => '',
            'subject'    => '',
            'from'       => '',
            'to'         => '',
            'date'       => '',
            'message_id' => '',
            'size'       => '',
            'uid'        => '',
            'msgno'      => '',
            'recent'     => '',
            'flagged'    => '',
            'answered'   => '',
            'deleted'    => '',
            'seen'       => '',
            'draft'      => '',
            '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'],
                               'INBOX');
    }

    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();

            if ($result)
            {
                $this->renderJson($result);
            }
            else
            {
                $this->renderJson($this->_noResults);
            }
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }
    }

    public function postAction()
    {
        try
        {
            $this->populateParameters();

            $sql = $this->getInsertStatement();

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

            foreach($this->_columns as $key => $val)
            {
                $stmt->bindParam($key, $this->_columns[$key]);
            }

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

            $select = $this->_dbAdapter
                ->select()
                ->from($this->getTableName())
                ->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
        {
            $this->populateParameters();
            $sql = $this->getUpdateStatement();

            $stmt = $this->_dbAdapter->prepare($sql);
            $stmt->bindParam('id', $id);

            foreach ($this->_restParameters as $key => $val)
            {
                $stmt->bindParam($key, $this->_restParameters[$key]);
            }

            $success = $stmt->execute();

            $select = $this->_dbAdapter
                ->select()
                ->from($this->getTableName())
                ->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())));
        }
    }
}
