<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
require_once(SF_ROOT_DIR . "/lib/uProduce.class.php");
require_once(SF_ROOT_DIR . "/lib/class.ProofHistoryStorage.php");
require_once(SF_ROOT_DIR . DIRECTORY_SEPARATOR . 'classes'. DIRECTORY_SEPARATOR .'class.customer_profile.php');

class ProofHistory
{
    private $_AssetTypeList;
    
    function __construct()
    {
        $this->_AssetTypeList   = array('tiny',
                                        'small',
                                        'medium',
                                        'large',
                                        'pdf'
            );
    }
    
    public function GenerateNewProofs($CustomerId, $ProfileName='Default')
    {
        # Get the list of products that the customer has configured in the store.
        $ProductList            = array();
        
        echo "GenerateNewProofs($CustomerId, $ProfileName)\n";
        
        $C = new Criteria();
        $C->add(Us2ProductCustomerDialPeer::CUSTOMER_ID, $CustomerId);
        $C->addSelectColumn(Us2ProductCustomerDialPeer::US2_PRODUCT_ID);
        $C->setDistinct(Us2ProductCustomerDialPeer::US2_PRODUCT_ID);
        $C->addJoin(Us2ProductCustomerDialPeer::US2_PRODUCT_ID, Us2ProductPeer::PRODUCT_ID);
        $C->add(Us2ProductPeer::STATUS_ID, 2);      # Online
        $C->add(Us2ProductPeer::ACTIVE_YN, 'Y');    # Is active
        $Rs = Us2ProductCustomerDialPeer::doSelectRs($C);
        //echo "Rs = {$Rs}\n";
        while($Rs->next())
        {
            $ProductId      = $Rs->getInt(1);
            //echo "ProductId = {$ProductId}\n";
            $ProductList[]  = $ProductId;
        }
        
        # 
        
        //echo "ProductList = " . print_r($ProductList, true) . "\n";
        $ProofGroup = uniqid("{$CustomerId}_");
        echo "ProofGroup = {$ProofGroup}\n";
        foreach($ProductList as $ProductId)
        {
            //echo "Creating new record for {$ProductId}\n";
            $NewHist = new Us2ProofHistory();
            $NewHist->setCustomerId($CustomerId);
            $NewHist->setProfileName($ProfileName);
            $NewHist->setProductId($ProductId);
            $NewHist->setProofGroupId($ProofGroup);
            $NewHist->setRequestedDate(date("Y-m-d H:i:s"));
            //echo "Saving now: \n";
            $NewHist->save();
            echo ".";
            
        }
        
        # Create new tracking record
        $ProofAlert = new Us2ProofAlert();
        $ProofAlert->setProofGroupId($ProofGroup);
        $ProofAlert->save();
        
    }
    
    public function GetAssetTypeList()
    {
        return $this->_AssetTypeList;
    }
    
    public function GetAsset($Us2ProofHistoryId, $AssetType)
    {
        
    }
    
    
    public function AddAsset($Us2ProofHistoryId, $AssetType, $AssetPath)
    {
        
    }
    
    public function SendAlertEmail($ProofGroupId)
    {
        
    }
    
    public function SendAlertEmails()
    {
       # Get list of proof groups to check to see if we can send email on
        $AlertList = array();
        $C = new Criteria();
        $C->add(Us2ProofAlertPeer::PROOF_GROUP_ID, $ProofGroupId);
        $C->add(US2ProofAlertPeer::EMAIL_SENT_DATE, '0000-00-00 00:00:00');
        $C->addSelectColumn(Us2ProofAlertPeer::US2_PROOF_ALERT_ID);
        $C->addSelectColumn(Us2ProofAlertPeer::PROOF_GROUP_ID);
        $Rs = Us2ProofAlertPeer::doSelectRs($C);
        while($Rs->next())
        {
            $AlertList[$Rs->getInt(1)]    = $Rs->getString(2);
        }
        
        # Spin through pending lists and see if they we're done
        foreach($AlertList as $Us2ProofAlertId => $ProofGroupId)
        {
            $C = new Criteria();
            $C->add(Us2ProofHistoryPeer::PROOF_GROUP_ID, $ProofGroupId);
            $C->add(Us2ProofHistoryPeer::COMPLETE_YN, 'N');
            $PendingCount = Us2ProofHistoryPeer::doCount($C);
            if ( $PendingCount == 0 )
            {
                echo "should send email for proof_group: $ProofGroupId (Us2ProofHistoryId: {$Us2ProofAlertId})\n";
            }
        }
    }
    
    public function GetNextProofGroup()
    {
        
        $C = new Criteria();
        $C->add( Us2ProofHistoryPeer::TRY_NEXT_DATE, date("Y-m-d H:i:s"), Criteria::LESS_THAN);
        $Proof = Us2ProofHistoryPeer::doSelectOne($C);
        if ( !$Proof ) return false;
        
        $ProofGroupId = $Proof->getProofGroupId();
        echo "Proof = " . print_r($Proof, true) . "\n";
        return $ProofGroupId;
    }
    
    public function GenerateNextProof($ProofGroupId)
    {
        
        # Cancel any invalid products for this proof group
        $C = new Criteria();
        $C->add(Us2ProofHistoryPeer::PROOF_GROUP_ID, $ProofGroupId);
        $C->addJoin(Us2ProofHistoryPeer::PRODUCT_ID, Us2ProductPeer::PRODUCT_ID);
        $C->add(Us2ProductPeer::STATUS_ID, 2, Criteria::NOT_EQUAL);
        $C->add(US2ProductPeer::ACTIVE_YN, 'N');
        $C->addSelectColumn(Us2ProofHistoryPeer::US2_PROOF_HISTORY_ID);
        $Rs = Us2ProofHistoryPeer::doSelectRs($C);
        echo "Rs = " . print_r($Rs, true) . "\n";
        $KillList = array();
        while($Rs->next())
        {
                echo "Should kill us2_history_proof_id: $HistoryId\n";
                $KillList[] = $Rs->getInt(1);
        }
        
        
        $C = new Criteria();
        $C->add( Us2ProofHistoryPeer::PROOF_GROUP_ID, $ProofGroupId );
        $C->add( Us2ProofHistoryPeer::TRY_NEXT_DATE, date("Y-m-d H:i:s"), Criteria::LESS_THAN);
        $Proof = Us2ProofHistoryPeer::doSelectOne($C);
        if ( !$Proof ) return false;
        
        $ProductId              = $Proof->getProductId();
        $ProofHistoryId         = $Proof->getUs2ProofHistoryId();
        $Us2Product 		= Us2ProductPeer::retrieveByPk ($ProductId);
        $ProductTemplateId 	= $Us2Product->getUs2ProductTemplateId();
        $uProduceDocId		= Us2ProductTemplatePeer::GetuProduceDocId ($ProductTemplateId);
        $CustomerId             = $Proof->getCustomerId();
        
        if($CustomerId)
                $ClientId = CustomerPeer::GetClientByCustomer($CustomerId);
        

        # Create the CSV
        $ProofCsvFile = $this->CreateProofCsv($ProductId, $CustomerId);
        $Result = array('error'=> 'Pending');
        //while($Result['error'])
        //{
            $Result = uProduce::GetProofByCsvWithJpgPreview($ProductId, $CustomerId, $ProofCsvFile);
            echo "Result = " . print_r($Result, true) . "\n";   
        //}
        $ProofDone = false;
        
        if ( !$Result['error'])
        {
            echo "Trying to store proofs\n";
            $StoreProofResult = $this->StoreProofs($ProofHistoryId, $Result);
            if ( $StoreProofResult )    $ProofDone = true;
        }
        if ( $ProofDone )
        {
            echo "Proof storage completed - Done\n";
            $Proof->setTryNextDate("2029-12-31 23:59:59");
            $Proof->setCompleteYn('Y');
            $Proof->setCompletedDate(date("Y-m-d H:i:s"));
            $Proof->save();
        } else {
            echo "Try later\n";
            $Proof->setTryNextDate(date("Y-m-d H:i:s", time() + (60 * 60)));
            $Proof->save();
            
        }
            

    }
    
    
    
    
    function CreateProofCsv($ProductId, $CustomerId)
    {
        # Find the most recent list for this product for this customer
        
        $C = new Criteria();
        $C->add(Us2OrderProductPeer::CUSTOMER_ID, $CustomerId);
        $C->add(Us2OrderProductPeer::PRODUCT_ID, $ProductId);
        $C->add(Us2OrderProductPeer::RECIPIENT_TYPE_ID, 2); # AMMS_LIST
        $C->add(Us2OrderProductPeer::TOTAL_QUAN, 0, Criteria::GREATER_THAN);
        $C->addJoin(Us2OrderProductPeer::RECIPIENT_LIST_ID, AmmsListDataPeer::AMMS_LIST_DATA_ID);
        $C->add(AmmsListDataPeer::ACCUZIP_COMPLETE_YN, 'Y');
        $C->addDescendingOrderByColumn(Us2OrderProductPeer::ORDER_PRODUCT_ID);
        $C->addSelectColumn(Us2OrderProductPeer::RECIPIENT_LIST_ID);
        $C->setLimit(1);
        $Rs = Us2OrderProductPeer::doSelectRs($C);
        while($Rs->next())
        {
            $RecipientListId = $Rs->getInt(1);
        }
        $RecipientListData = array();
            
        if ( $RecipientListId > 0 )
        {
            echo "Using Recipient List: {$RecipientListId}\n";
            $C = new Criteria();
            $C->add(AmmsListDataDetailPeer::AMMS_LIST_DATA_ID, $RecipientListId);
            $C->add(AmmsListDataDetailPeer::DUPLICATE_DETECTED_YN, 'N');
            $C->add(AmmsListDataDetailPeer::VALID_YN, 'Y');
            $C->setLimit(4);
            $ListData = AmmsListDataDetailPeer::doSelect($C);
            if ( $ListData && !is_array($ListData))
            {
                $ListData = array('0' => $ListData);
                
            }
            foreach($ListData as $Row => $Data )
            {
                $Detail = unserialize($Data->getNameInfo());
                if ( $Detail->extra)
                {
                    $Extra = unserialize($Detail->extra);
                }
                $Full = "";
                if ( strlen($Detail->First) > 0 ) $Full = $Detail->First;
                if ( strlen($Full) > 0 ) $Full .= " ";
                if ( strlen($Detail->Middle) > 0 ) $Full .= $Detail->Middle;
                if ( strlen($Full) > 0 ) $Full .= " ";
                if ( strlen($Detail->Last) > 0 ) $Full .= $Detail->Last;
                if ( strlen($Full) > 0 ) $Full .= " ";
                if ( strlen($Detail->Suffix) > 0 ) $Full .= $Detail->Suffix;
                $Full = trim($Full);
                
               $RecipientListData[] = array(
                            $Row + 1,
                            10,
                            $Detail->First,
                            $Detail->Last,
                            $Full,
                            $Detail->Address,
                            $Detail->City,
                            $Detail->State,
                            $Detail->Zip,
                            '/335407340803/',
                            '',
                            '602782',
                            '100595E09E',
                            sprintf("%s%s", $Detail->First, $Detail->Last),
                            'chk5m',
                            $Extra->MAKE,
                            $Extra->MODEL,
                            $Extra->YEAR,
                            $Extra->MILEAGE,
                            $Extra->VIN,
                            '$14575',
                            '',
                            ''                
                        ); 
            }
            
        } else {
            # Load hard coded data - which may be garbage
            echo "Using Hard Coded List\n";
            for($i = 1; $i < 5; $i++)
            {
                $RecipientListData[] = array(
                            $i,
                            10,
                            'Michelle',
                            'Williams-Washigton',
                            'Michelle Williams-Washigton',
                            '9427 Corporate Lake Drive',
                            'Tampa',
                            'FL',
                            '33634-0000',
                            '/335407340803/',
                            '',
                            '602782',
                            '100595E09E',
                            'MichelleWilliamsWashington',
                            'chk5m',
                            'Honda',
                            'Element',
                            '2010',
                            '15',
                            'VIN1234567890',
                            '$14575',
                            '',
                            ''                
                        );
            }
        }
        
        $File = SF_ROOT_DIR . "/data/" . uniqid('proof_') . ".csv";
        $fh = fopen($File, "w+");
        $Header = array('INDEX',
                        'CODE',
                        'FIRSTNAME',
                        'LASTNAME',
                        'FULLNAME',
                        'ADDRESS',
                        'CITY',
                        'STATE',
                        'ZIP',
                        'BARCODE',
                        'ENDORSE',
                        'MATCHCODE',
                        'SEQ',
                        'PURLNAME',
                        'PURLCODE',
                        'MAKE',
                        'MODEL',
                        'YEAR',
                        'MILEAGE',
                        'VIN',
                        'VEH_ESTIMAGED_VALUE',
                        'LOYALTY_IS_MEMBER',
                        'LOYALTY_POINTS'
                    );
        fputcsv($fh, $Header);
        foreach($RecipientListData as $Row => $Buffer)
        {
            fputcsv($fh, $Buffer);
            
        }
        fclose($fh);
        return $File;
    }
    
    
    /**
     *
     * @param type $ProofHistoryId
     * @param type $Result 
     */
    function StoreProofs($ProofHistoryId, $Result)
    {
        
        $ProofStorage   = new ProofHistoryStorage();
        
        $ProofJpgList   = array('tiny', 'small', 'medium', 'large');
        
        $outdir         = SF_ROOT_DIR . "/data/temp_proof";
        $FilePath       = $Result['file_location'];
        $JpgsList       = $Result['jpgs'];
        $ProofData      = array('pdf' => array());
        $ResultOut      = false;
        
        $DataKey        = 'pdf';
        if($Result['file_location'])
        {
            $Data = $this->GetLinkAssetData($Result['file_location']);
            
            if ( $Data )
            {
                $FileName = pathinfo($Result['file_location'], PATHINFO_FILENAME);
                echo "Size: " . strlen($Data) . " bytes\n";

                # Try and store the data into the bucket
                $DataObjectKey = sprintf("%d_%s", $ProofHistoryId, $FileName);

                echo "Trying to save proof part: $DataObjectKey\n";

                $SaveResult = $ProofStorage->SaveProofPart($DataObjectKey, $Data);
                echo "Back\n";
                //echo "SaveResult: " . $SaveResult . "\n";
                $ProofData[$DataKey][] = $DataObjectKey;
            }
            
            foreach($ProofJpgList as $ProofSize)
            {
                $JpgResult = $this->MakeJpg($ProofHistoryId, $Result['file_location'], $ProofSize);
                echo "JpgResult = " . print_r($JpgResult, true) . "\n";
                $ProofData[$ProofSize] = array();
                foreach($JpgResult as $Key => $ProofImagePath)
                {
                    $Data = $this->GetLinkAssetData($ProofImagePath);

                    if ( $Data )
                    {
                        $FileName = pathinfo($ProofImagePath, PATHINFO_FILENAME);
                        echo "Size: " . strlen($Data) . " bytes\n";

                        # Try and store the data into the bucket
                        $DataObjectKey = sprintf("%s", $FileName);

                        echo "Trying to save proof part: $DataObjectKey\n";

                        $SaveResult = $ProofStorage->SaveProofPart($DataObjectKey, $Data);
                        echo "Back\n";
                        //echo "SaveResult: " . $SaveResult . "\n";
                        $ProofData[$ProofSize][] = $DataObjectKey;
                    }
                }
            }
            
            echo "ProofHistoryId = {$ProofHistoryId}\n";
            echo "ProofData = " . print_r($ProofData, true) . "\n";
            $SaveProof = $ProofStorage->SaveProofData($ProofHistoryId, $ProofData);
            echo "SaveProof returned: " . print_r($SaveProof, true) . "\n";
        
            $ResultOut = true;
        }
        
        return $ResultOut;
        
    }
    
    
        
    function GetLinkAssetData($Link)
    {
        $Data = file_get_contents($Link);

        return $Data;
    }
    
    
    function MakeJpg($ProofHistoryId, $PdfPath, $Size)
    {
        $outdir                         = SF_ROOT_DIR . "/data/temp_proof";
        $Result                         = array();
        
        $pathinfo 			= pathinfo($PdfPath);
        //$filename 			= $pathinfo['filename'];
        $filename                       = sprintf("%s_%s", $ProofHistoryId, $Size);
        switch($Size)
        {
            case 'tiny':
                $Scale = '200x100';
                break;
            case 'small':
                $Scale = '400x200';
                break;
            case 'medium':
                $Scale = '1000x500';
                break;
            default:
                $Scale = '2000x1000';
                break;
        }
        exec("/usr/bin/convert -density 200 $PdfPath -scale {$Scale} $outdir/{$filename}.jpg");
        
        $arrayImage = array(
                "{$outdir}/{$filename}.jpg",
                "{$outdir}/{$filename}-0.jpg",
                "{$outdir}/{$filename}-1.jpg",
                "{$outdir}/{$filename}-2.jpg",
                "{$outdir}/{$filename}-3.jpg",
        );

        foreach($arrayImage as $file)
        {
                if(file_exists($file)) $Result[] = str_replace(SF_ROOT_DIR . '/web/', 'http://gateway.printhd.us/', $file);
        }

        return $Result;
    }
    
    
    function AddNewProfileProofs()
    {
        $MainConn   = Propel::GetConnection('dms_main');
        $Conn       = Propel::GetConnection();
        
        
        $Query =  "select max(requested_date) as max_date "
                . "from us2_proof_history where 1 "
                . "limit 1 ";
        $Rs = $Conn->executeQuery($Query);
        while($Rs->next())
        {
            $MaxDate = $Rs->getString('max_date');
        }
        echo "MaxDate: {$MaxDate}\n";
        
        # Get the profiles that have been updated since we last ran this process.
        
        $ToDoList = array();
        
        $Query = "select distinct(customer_profile_id) "
                . "from customer_profile_history "
                . "where updated_date > '{$MaxDate}' ";
        $Rs = $MainConn->executeQuery($Query);
        while($Rs->next())
        {
            $ToDoList[] = $Rs->getInt('customer_profile_id');
        }
        
        if ( count($ToDoList) > 0 )
        {
            # Get the customer ID and profile names for each of the profile_id's collected.
            $AddList = array();
            $Query = "select customer_id, profile_name "
                    . "from customer_profile "
                    . "where customer_profile_id in (" . join(",", $ToDoList) . ") ";
            $Rs = $MainConn->executeQuery($Query);
            while($Rs->next())
            {
                $AddList[] = array('customer_id'    => $Rs->getString('customer_id'),
                                    'profile_name'  => $Rs->getString('profile_name')
                            );
            }

            foreach($AddList as $key => $Data)
            {
                echo "Adding proof: customer_id: {$Data['customer_id']} / {$Data['profile_name']}\n";
                $this->GenerateNewProofs($Data['customer_id'], $Data['profile_name']);
            }
        
        }
        
        
//        
//        SELECT DISTINCT (
//customer_profile_id
//)
//FROM `customer_profile_history`
//WHERE updated_date > '2012-04-01'
    }
}
?>
