<?php

/**
 * file: firstpass.php
 *
 * Scan through a (long) list of emails, marking ones that don't have a CMC technologies enquiry number
 * in the subject for deletion.
 */





class FirstpassShell extends Shell {


    var $uses = array('Enquiry');


    function main() {


        $username = 'vault';
        $password = 'xjdYOsmJWc37'; /* The password for the account to be checked */

        $testing = 0;

        if($testing == 1) {

            $mbox = imap_open("{192.168.0.8:143}INBOX", $username, $password) or die("can't connect: " . imap_last_error());
        }
        else {
            $mbox = imap_open("{192.168.0.8:143/novalidate-cert}INBOX", $username, $password) or die("can't connect: " . imap_last_error());

        }



        $MC = imap_check($mbox);
        $number_of_messages = $MC->Nmsgs;

        echo "Number of messages to Process ".$number_of_messages."\n";

        if($number_of_messages == 0) {
            exit(0);
        }

        $enquiries = $this->Enquiry->find('all', array('recursive'=>0,'fields' => array('Enquiry.title', 'Enquiry.id')));



        foreach ($enquiries as $enq) {
            $enqNumber = $enq['Enquiry']['title'];
            $id = $enq['Enquiry']['id'];
            $enquiryList[$enqNumber] = $id;
        }



        //while($number_of_messages > 0) {


        // for($i=1; $i <= $number_of_messages; $i++) {
        for($i=1; $i <= 100; $i++) {
            $this_header = imap_headerinfo($mbox, $i);
            $message = $this->getMessage($mbox, $i, $this_header);

            //echo "Checking msg number: $i\tSubject: ".$message['subject']."\n";
            //echo "Checking msg number: $i\n";

            $enqID = $this->checkIfValidEnquiry($message['subject'], $enquiryList);

            if($enqID == false) {
                echo "Deleting msg number: $i\tSubject: ".$message['subject']."\n";
                imap_delete($mbox, $i);
                //$discardArray[] = $i;

            }

        }


        echo "Tidying up now.\n";


      //  reset($discardArray);


       // $numberToDiscard= count($discardArray);



       /* if($numberToDiscard > 0) {
            echo "Going to discard $numberToDiscard messages\n";


            $discardSet = implode(",",$discardArray);

            $delete_result = imap_delete($mbox, $discardSet);

            if($delete_result == false) {
                echo "Error deleting messages";
                echo imap_last_error();
            }
            else {
                echo "Success";
            }
        }*/





        imap_expunge($mbox);

          echo "Messages before delete: ".$number_of_messages."\n";
        

        $check = imap_check($mbox);
        
        echo "Messages after delete: ".$number_of_messages."\n";

       $number_of_messages = $check->Nmsgs;


      // }



        imap_close($mbox);

    }



    function checkIfValidEnquiry($subject, &$enqList) {
        $subject = iconv_mime_decode($subject, 0, "ISO-8859-1");

        $output = array();
//	$decoded_subject = iconv_mime_decode($subject, 2, "ISO-8859-1");

        preg_match("/CMC\d+([NVQWSOT]|ACT|NT)E\d+-\d+/", $subject, $output);


        if(isset($output[0])) { //Found a valid-looking Enquiry Number
            $fetched_enquirynumber = $output[0];

            echo "'$fetched_enquirynumber'\n";

            if(array_key_exists($fetched_enquirynumber, $enqList)) { //check if it actually exists.
                $enqid = $enqList[$fetched_enquirynumber];

                return $enqid;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }

    }



    function getMessage($mbox, $msgnumber, $headers) {

        $subject = $headers->subject;
        //$subject = iconv_mime_decode($subject, 0, "ISO-8859-1//IGNORE");
        // $subject = mb_convert_encoding($subject, "ISO-8859-1");
        // $subject = mb_convert_encoding($subject, "UTF-8");
        $subject = mb_decode_mimeheader($subject);

        $date = $headers->date;

        $message['subject'] = $subject;

        return $message;

    }






}


?>
