<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

// +----------------------------------------------------------------------+
// | File name : Utils.php                                                |
// | PHP version >= 5.2                                                   |
// +----------------------------------------------------------------------+
// | Author: ARUN SADASIVAN<arun.s@armiasystems.com>                      |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems � 2010                                    |
// | All rights reserved                                                  |
// +----------------------------------------------------------------------+
// | This script may not be distributed, sold, given away for free to     |
// | third party, or used as a part of any internet services such as      |
// | webdesign etc.                                                       |
// +----------------------------------------------------------------------+

class Utils {

    private $message = '';

    public static function sendUserMail($userMailId, $mailTemplateName, $arrReplace,$mailBody ='') {

        PageContext::includePath('phpmailer');
        //$userMailId = 'vibncs3@gmail.com';
        // PageContext::includePath('phpmailer');
        // Logger::info("Entering email functionality");
        $db = new Db();
       
        $mailTemplate = $db->selectRecord("email_templates", "*", "vtemplate_name='".$mailTemplateName."'  ");
              

        $adfromemail = $db->selectRow("settings",'site_email');
        $adfromemailname = $db->selectRow("settings",'site_name');
        $adreplyemail = $db->selectRow("settings",'site_email');
        $adreplyemailname = $db->selectRow("settings",'site_name');
        $mailHeader =    Utils::getCommonTemplateHeader();
        $mailFooter =    Utils::getCommonTemplateFooter();

        // updated by Sanal for array replacing
        foreach($arrReplace as $key => $val){
            $arrTSearch[]   =   $key;
            $arrTReplace[]  =   $val;
        }

        if(sizeof($mailTemplate)>0 || $mailBody != '') {
           /*$arrTSearch            = array("{SITE_NAME}","{SITE_URL}","{USER}","{STORE_NAME}","{FBURL}","{MARKETPLACE}","{ORDER_DETAILS}","{SHARE_LINK}","{STORE_EMAIL}","{OPEN_STORE_LINK}","{MARKETPLACE_LINK}","{OPEN_NETWORK_LINK}","{COMMENT}","{NETWORK_LINK}","{STORE_LINK}","{STORE_DASHBOARD_LINK}","{PRODUCT_LISTING}","{PASSWORD}","{MERCHANT}","{ORDERID}","{USEREMAIL}","{MERCHANTEMAIL}");
            $arrTReplace            = array(SITE_NAME, BASE_URL,$arrReplace['user'],$arrReplace['store_name'],$arrReplace['fburl'],$arrReplace['marketplace'],$arrReplace['orderDetails'],$arrReplace['shareLink'],$arrReplace['store_email'],$arrReplace['openStoreLink'],$arrReplace['marketplaceLink'],$arrReplace['openNetworkLink'],$arrReplace['comment'],$arrReplace['networkLink'],$arrReplace['store_link'],$arrReplace['store_dashboard_link'],$arrReplace['product_listing'],$arrReplace['password'],$arrReplace['merchant'],$arrReplace['orderid'],$arrReplace['useremail'],$arrReplace['merchantemail']);*/
            if($mailTemplateName) {
                if(!$mailBody) {
                    $email_body         =   $mailTemplate->vemail_body;
                    $mailBody           =   htmlspecialchars_decode( str_replace($arrTSearch,$arrTReplace,stripslashes($email_body)));
                } 
              
                $mailBody           =   $mailHeader.$mailBody.$mailFooter;
                $mailSubject        =   $mailTemplate->vtemplate_title;
            } 
           
          
          if(ENVIRONMENT == 'LIVE' || ENVIRONMENT == 'PILOTSERVER'){  
            
            $sendername             = "Wildkale";
            $mail                   = new PHPMailer();
                
             if(ENVIRONMENT != 'CLIENTSLIVE' && ENVIRONMENT != 'LOCAL'){
                    $mail->IsSMTP(); // telling the class to use SMTP

                    $mail->SMTPSecure = 'tls';
                    $mail->Host       = "smtp.office365.com"; // SMTP server
                    $mail->SMTPAuth   = true;                  // enable SMTP authentication
                    $mail->Port       = 587;                    // set the SMTP port for the GMAIL server
                    $mail->Username   = "contact@wildkale.com"; // SMTP account username
                    $mail->Password   = "Wildkale2016$";        // SMTP account password
             }
             if($mailTemplateName == 'message_to_buyer' || $mailTemplateName  == 'message_to_buyer_wot_order') {
                $adreplyemail     = 'Noreply@wildkale.com';
                $adreplyemailname = 'Noreply';
             }
                      
            $mail->AddReplyTo($adreplyemail,$adreplyemailname);
            if(ENVIRONMENT == 'LOCAL' || ENVIRONMENT == 'CLIENTSLIVE' || ENVIRONMENT == 'PILOTSERVER') {
                $adfromemail = 'contact@wildkale.com';
            }
            $mail->SetFrom($adfromemail,$adfromemailname);     
            $mail->AddAddress($userMailId);
            
            $mail->Subject              = $mailSubject;
            $mail->AltBody              = ''; // Optional, comment out and test.
            $mail->MsgHTML($mailBody);
            if(ENVIRONMENT != 'LOCAL' ){
                $mail->Send();
            }else {
                 Logger::info("Some error occured");

            }
            
        }
        else{
             
          /*  $headers  = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $headers .= "Reply-To: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $mailsent = @mail($userMailId, $mailSubject, $mailBody,$headers);*/
        }
            
        } else {
            Logger::info("No active email template found");
        }


    }

    public static function sendAdminMail($mailTemplateName, $arrReplace, $fromDetails = array(), $mailBody = '') {

        PageContext::includePath('phpmailer');
        // Logger::info("Entering email functionality");
        $db = new Db();
        $mailTemplate = $db->selectRecord("email_templates", "*", "vtemplate_name='".$mailTemplateName."'  ");

        $adreplyemail       = $db->selectRow("settings",'site_email');
       

        if($fromDetails){
            $adfromemailname    = $fromDetails['name'];
            $adfromemail       = $fromDetails['email'];
        }else{
            $adfromemailname    = $db->selectRow("settings",'site_name');
            $adfromemail       = $db->selectRow("settings",'site_email');
        }


        $adreplyemailname = $db->selectRow("settings",'site_name');
        $mailHeader =    Utils::getCommonTemplateHeader();
        $mailFooter =    Utils::getCommonTemplateFooter();

        // updated by Sanal for array replacing
        foreach($arrReplace as $key => $val){
            $arrTSearch[]   =   $key;
            $arrTReplace[]  =   $val;
        }

        if(sizeof($mailTemplate)>0 || !$mailBody) {
                if(!$mailBody) {
                    $email_body         =   $mailTemplate->vemail_body;
                    $mailBody           =   htmlspecialchars_decode( str_replace($arrTSearch,$arrTReplace,stripslashes($email_body)));
                }
                    
                $mailBody           =   $mailHeader.$mailBody.$mailFooter;
                $mailSubject        =   str_replace($arrTSearch,$arrTReplace,stripslashes($mailTemplate->vtemplate_title));
                //echo $mailBody; die("ddd");
      if(ENVIRONMENT != 'CLIENTSLIVE'){   
            $sendername             = "Wildkale";
            
            
            $mail                   = new PHPMailer();
            
             if(ENVIRONMENT != 'CLIENTSLIVE'){
                    $mail->IsSMTP(); // telling the class to use SMTP

                    $mail->SMTPSecure = 'tls';
                    $mail->Host       = "smtp.office365.com"; // SMTP server
                    $mail->SMTPAuth   = true;                  // enable SMTP authentication
                    $mail->Port       = 587;                    // set the SMTP port for the GMAIL server
                    $mail->Username   = "contact@wildkale.com"; // SMTP account username
                    $mail->Password   = "Wildkale2016$";        // SMTP account password
            
             }   
            
            $mail->AddReplyTo($adreplyemail,$adreplyemailname);
            if(ENVIRONMENT == 'LOCAL' || ENVIRONMENT == 'CLIENTSLIVE' || ENVIRONMENT == 'PILOTSERVER') {
                $adfromemail = 'contact@wildkale.com';
            }
            $mail->SetFrom($adfromemail,$adfromemailname);
           
           // $adreplyemail = 'vibncs3@gmail.com';
            $mail->AddAddress($adreplyemail);
            $mail->Subject              = $mailSubject;
            $mail->AltBody              = ''; // Optional, comment out and test.
            
            $mail->MsgHTML($mailBody);
           
            
            if(ENVIRONMENT != 'LOCAL' && ENVIRONMENT != 'CLIENTSLIVE'){
                $mail->Send();
            }else {
                Logger::info("Some error occured");

            }
      }else{
          
            $headers  = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $headers .= "Reply-To: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $mailsent = @mail($adreplyemail, $mailSubject, $mailBody,$headers);
          
      }
        }else {
            Logger::info("No active email template found");

        }


    }
    /**/
    public static function getCommonTemplateHeader(){
         $header = '<body paddingwidth="0" paddingheight="0"   style="padding-top: 0; padding-bottom: 0; padding-top: 0; padding-bottom: 0; background-repeat: repeat; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; -webkit-font-smoothing: antialiased;" offset="0" toppadding="0" leftpadding="0">
  <table width="100%" border="0" cellspacing="0" cellpadding="0" class="tableContent bgBody" align="center"  style="font-family:Helvetica, sans-serif;">
        <tr>
          <td align="center">
            <table width="600" border="0" cellspacing="0" cellpadding="0" align="center" style="background:#FFF;" >
            <tr>
            <td class="bgItem" align="center">
            <table width="600" border="0" cellspacing="0" cellpadding="0" align="center">
              <tr>
                <td align="center">

                  <div class="movableContent">
                    <table width="600" border="0" cellspacing="0" cellpadding="0" align="center">
                      <tr><td height="15"></td></tr>
                      <tr>
                        <td>
                          <table width="600" border="0" cellspacing="0" cellpadding="0" align="center">
                            <tr>
                              <td width="100%">
                                  <div style="text-align:center;">
                                    <img src="'.SITE_PATH.'/images/wildkale_logo.png" alt="Logo" width="237" height="49" data-default="placeholder" data-max-width="200">
                                  </div>
                              </td>
                            </tr>
                          </table>
                        </td>
                      </tr>
                      <tr><td height="15"></td></tr>
                    </table>  
                  </div>  
                   <div>
              <table width="550" border="0" cellspacing="0" cellpadding="0" align="center">
                <tr>
                  <td>
                    <div>
                      <div style="text-align: center; background:#5ebc3f; width:100%;">
                        <img src="'.SITE_PATH.'/images/banner_1.jpg" alt="Logo" width="600" height="63" data-default="placeholder" data-max-width="600">
                      </div>
                    </div>
                  </td>
                </tr>
              </table>  
            </div>';

        return $header;
    }

    public static function getCommonTemplateFooter(){
        $footer = "</td>
                    </tr>
                  </table>
                  </td>
                  </tr>
                  </table>
                </td>
              </tr>
            </table>";

        return $footer;
    }
    public static function getEmailTemplateHeader(){
        $mailHeader = '<table width="100%" border="0" cellspacing="0" cellpadding="0" style="font-family:Arial, Helvetica, sans-serif;">
                          <tr>
                            <td height="50" align="center" valign="middle" style="background:#f7f7f5; padding:0 0 0 0; color:#bababa;">Having trouble reading this email?  <a href="#"style="color:#bababa; text-decoration:underline;">Click here to view it in your browser</a></td>
                          </tr>
                          <tr>
                            <td align="center" valign="top" style="padding:50px 0 ; "><img src="'.BASE_URL.'project/images/emaillogo.png" width="389" height="220"></td>
                          </tr>

                          <tr>
                            <td align="center" valign="top" style="background:#f7f7f5; padding:60px 0 70px 0;">
                                <table width="745" border="0" cellspacing="0" cellpadding="0">
                                          <tr>
                                                <td  valign="top" style="color:#283c17; font-size:14px; letter-spacing:1px; ">';
        return $mailHeader;
    }

    public static function getEmailTemplateFooter(){
        $mailFooter = '     </td>
                          </tr>
                </table>

            </td>
          </tr>
          <tr>
            <td height="60" align="center" valign="middle" style="background:#263e0a; color:#FFFFFF; font-size:12px;">
                        &copy; '.date("Y").' Wildkale. All rights reserved .
                </td>
          </tr>
        </table>';
        return $mailFooter;
    }
    
    
     public static function sendEmail($toEmail, $mailSubject, $emailContent) {
        
        PageContext::includePath('phpmailer');
        $db                = new Db();

        $adfromemailname    = $db->selectRow("settings",'site_name');
        $adfromemail       = $db->selectRow("settings",'site_email');
        

        $adreplyemail       = $db->selectRow("settings",'site_email');
        $adreplyemailname   = $db->selectRow("settings",'site_name');
        $sendername       = "Wildkale";
        
        // get the mail template        
          
        $mailBody               = $emailContent;
                
        if(ENVIRONMENT == 'PILOTSERVER' || ENVIRONMENT == 'LIVE'){
        
                    $mail                   = new PHPMailer();
                    if(ENVIRONMENT != 'CLIENTSLIVE'){
                        $mail->IsSMTP(); // telling the class to use SMTP

                        $mail->SMTPSecure = 'tls';
                        $mail->Host       = "smtp.office365.com"; // SMTP server
                        $mail->SMTPAuth   = true;                  // enable SMTP authentication
                        $mail->Port       = 587;                    // set the SMTP port for the GMAIL server
                        $mail->Username   = "contact@wildkale.com"; // SMTP account username
                        $mail->Password   = "Wildkale2016$";        // SMTP account password
                    }

                    $mail->AddReplyTo($adreplyemail,$adreplyemailname);
                    if(ENVIRONMENT == 'LOCAL' || ENVIRONMENT == 'CLIENTSLIVE' || ENVIRONMENT == 'PILOTSERVER') {
                        $adfromemail = 'contact@wildkale.com';
                    }
                    $mail->SetFrom($adfromemail,$adfromemailname);

                    if(is_string($toEmail)){
                        if(strpos($toEmail, ',') !== false) {
                            $aToEmail = explode(',', $toEmail);
                            foreach ($aToEmail as $key => $email) {
                               $mail->AddAddress($email);
                            }
                        } else {
                            $mail->AddAddress($toEmail);
                        }
                    }
                   // $mail->AddAddress('armiatester@gmail.com');
                    

                    $mail->Subject              = $mailSubject;
                    $mail->AltBody              = ''; // Optional, comment out and test.
                    $mail->MsgHTML($mailBody);
                    if(ENVIRONMENT != 'LOCAL'){
                        $mail->Send();
                    }
        }else{
            
            /*$headers  = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $headers .= "Reply-To: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $mailsent = @mail($toEmail, $mailSubject, $mailBody,$headers);*/
        }   
        return true;

    }

/*function to send order package pdf both to farmer and admin*/
    public static function sendEmailWithOrderPackageAttachment($adminEmail, $emailContent, $aFileArr)
    {
        PageContext::includePath('phpmailer');
        $db                = new Db();

        $adfromemailname    = $db->selectRow("settings",'site_name');
        $adfromemail       = $db->selectRow("settings",'site_email');
        

        $adreplyemail       = $db->selectRow("settings",'site_email');
        $adreplyemailname   = $db->selectRow("settings",'site_name');
        $sendername       = "Wildkale";
        
        // get the mail template        
          
        $mailBody               = $emailContent;
        $mailSubject            = ' '.SITE_NAME.' - ORDER PACKGE SETTLEMENT INFORMATION ';
        
        
         if(ENVIRONMENT == 'PILOTSERVER' || ENVIRONMENT == 'LIVE'){
        
        $mail                   = new PHPMailer();
       
        
        $mail->AddReplyTo($adreplyemail,$adreplyemailname);
        if(ENVIRONMENT == 'LOCAL' || ENVIRONMENT == 'CLIENTSLIVE' || ENVIRONMENT == 'PILOTSERVER') {
            $adfromemail = 'contact@wildkale.com';
        }
        $mail->SetFrom($adfromemail,$adfromemailname);
        //$mail->SMTPDebug  = 2; 
        $mail->SMTPSecure = 'tls';
        $mail->IsSMTP(); // telling the class to use SMTP
        $mail->Host       = "smtp.office365.com"; // SMTP server
        $mail->SMTPAuth   = true;                  // enable SMTP authentication
        $mail->Port       = 587;                    // set the SMTP port for the GMAIL server
        $mail->Username   = "contact@wildkale.com"; // SMTP account username
        $mail->Password   = "Wildkale2016$";        // SMTP account password
        //
        if($aFileArr['secondary_contact'] != '') {
            $aSecondaryContact = json_decode($aFileArr['secondary_contact']);
            $sSecondaryMail = $aSecondaryContact->email;
            if($sSecondaryMail != '')
                $mail->AddAddress($sSecondaryMail);
        }
        //$adminEmail = 'armiatester@gmail.com';
        $mail->AddAddress($adminEmail);

        //$aFileArr['email'] = 'vibncs3@gmail.com';
        //$adminEmail = 'vibin.j@armiasystems.com';
       // $aFileArr['email'] = 'armiatester@gmail.com';
       // $aFileArr['email'] = 'mikaeltjarnberg@me.com'; //need to replace by farmer mail comment it when actual implemenation.
        $mail->AddAddress($aFileArr['email']);

        $mail->Subject              = $mailSubject;
        $mail->AltBody              = ''; // Optional, comment out and test.
        $mail->MsgHTML($mailBody);
        $mail->AddAttachment( $aFileArr['file_name'] , 'order_package_summary.pdf' );
        if(ENVIRONMENT != 'LOCAL'){
            if (!$mail->Send())
            {
                echo "Error: $mail->ErrorInfo";
            }
            else
            {
                
            }
        }
    }  else{
        
           /* $headers  = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
            $headers .= "From: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $headers .= "Reply-To: armiatester@gmail.com<armiatester@gmail.com>" . "\r\n";
            $mailsent = @mail($adminEmail, $mailSubject, $mailBody,$headers);*/
        
    }
        
        return true;
    } 

    /*
     * Function to create random string
     * Input : string length <M>
     */

    public static function rand_string($length) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $size = strlen($chars);
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[rand(0, $size - 1)];
        } // End For
        return $str;
    }

// End Function

    public static function pageInfo($currentPage, $fullCount, $maxRows) {
        $data = array();
        $maxPages = ceil($fullCount / $maxRows);
        $base = (empty($currentPage)) ? 0 : ($currentPage - 1) * $maxRows;
        $page = (empty($currentPage)) ? 1 : $currentPage;
        $indent = $maxRows;
        // Page Components
        $data['maxPages'] = $maxPages;
        $data['base'] = $base;
        $data['indent'] = $indent;
        $data['limit'] = $base . ',' . $indent;
        $data['page'] = $page;
        $data['pagecount'] = $fullCount;

        return $data;
    }

// End Function

    public static function stripWhitespaces($string = NULL) {
        $stringStripped = NULL;
        if (!empty($string)) {
            $stringStripped = preg_replace('/\s+/', '', $string);
        }
        return $stringStripped;
    }

// End Function

    public static function stripChar($charArr, $string) {
        /*
         * example
          $stringArr[] = "'";
          $stringArr[] = '"';
          $stringArr[] = "-";
         */

        $stringN = str_replace($charArr, "", $string);
        return $stringN;
    }

// End Function

    public static function isValidDomainname($str) {
        if (trim($str) != "") {
            if (preg_match("/[^0-9a-zA-Z+-]/", $str)) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    public static function formatBytes($size, $precision = 2) {
        $base = log($size) / log(1024);
        $suffixes = array('', 'k', 'M', 'G', 'T');

        return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
    }

    public static function formatDate($date, $time = FALSE, $type = 'timestamp') {
        $newDate = '--';
        if (!empty($date)) {
            if (Utils::checkDateTime($date, $type)) {
                $newDate = ($time) ? date('d M Y H:i', strtotime($date)) : date('d M Y', strtotime($date));
            }
        }
        return $newDate;
    }

    public static function formatDateUS($date, $time = FALSE, $type = 'timestamp') {
        $newDate = '--';
        if (!empty($date)) {
            if (Utils::checkDateTime($date, $type)) {
                $newDate = ($time) ? date('m/d/Y H:i', strtotime($date)) : date('m/d/Y', strtotime($date));
            }
        }
        return $newDate;
    }

    public static function reconnect() {

        @mysql_connect(MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD)
                or die('Sorry, Unable to connect server');
        //        or die(mysql_error());
        mysql_select_db(MYSQL_DB);
        return true;
    }

    public static function formatPrice($amount) {
        $amount = (empty($amount)) ? 0 : $amount;
        $price = number_format($amount, 2, '.', '');
        return $price;
    }

//End Function

    public static function serializeNencodeArr($dataArr) {
        return urlencode(serialize($dataArr));
    }

//End Function

    public static function unserializeNdecodeArr($dataArr) {
        return unserialize(urldecode($dataArr));
    }

//End Function

    public static function is_valid_email($address) {
        Logger::info("Checking validity of email :");
        $rx = "^[a-z0-9\\_\\.\\-]+\\@[a-z0-9\\-]+\\.[a-z0-9\\_\\.\\-]+\\.?[a-z]{1,4}$";
        return (preg_match("~" . $rx . "~i", $address));
    }

    public static function replacDateBySlashes($date) {
        $newDate = (!empty($date)) ? str_replace('-', '/', $startDate) : NULL;
        return $newDate;
    }

// End Function

    public static function doExcelExport($fieldHeaders, $fieldValues, $filePrefix = 'Report') {

        $filename = $filePrefix . "_" . date('Ymd') . ".xls";
        PageContext::includePath('Excel');
        $objPHPExcel = new PHPExcel;
        $objPHPExcel->getDefaultStyle()->getFont()->setName('Calibri');
        $objPHPExcel->getDefaultStyle()->getFont()->setSize(8);
        $currencyFormat = '#,#0.## \€;[Red]-#,#0.## \€';
        $numberFormat = '#,#0.##;[Red]-#,#0.##';
        $objSheet = $objPHPExcel->getActiveSheet();
        $objSheet->setTitle('My sales report');
        $rows = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L");
        $index = 0;
        foreach ($fieldHeaders as $row) {
            $column = $rows[$index] . '1';
            $objSheet->getCell($column)->setValue($row);
            $objPHPExcel->getActiveSheet()->getColumnDimension($rows[$index])->setAutoSize(true);
            ;
            $index++;
        }
        $objSheet->getStyle('A1:' . $column)->getFont()->setBold(true)->setSize(12);
        $rowIndex = 2;
        foreach ($fieldValues as $row) {
            $index = 0;
            foreach ($row as $item) {
                $column = $rows[$index] . $rowIndex;
                $objSheet->getCell($column)->setValue($item);
                $index++;
            }
            $rowIndex++;
        }
        ob_end_clean();

        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        ob_end_clean();

        $objWriter->save('php://output');
        $objPHPExcel->disconnectWorksheets();
        unset($objPHPExcel);
        exit;
    }

    public static function number_to_words($number) {

        if ($number > 999999999) {

            throw new Exception("Number is out of range");

        }

        $Gn = floor($number / 1000000);  /* Millions (giga) */

        $number -= $Gn * 1000000;

        $kn = floor($number / 1000);     /* Thousands (kilo) */

        $number -= $kn * 1000;

        $Hn = floor($number / 100);      /* Hundreds (hecto) */

        $number -= $Hn * 100;

        $Dn = floor($number / 10);       /* Tens (deca) */

        $n = $number % 10;               /* Ones */

        $cn = round(($number - floor($number)) * 100); /* Cents */

        $result = "";



        if ($Gn) {

            $result .= Utils::number_to_words($Gn) . " Million";

        }



        if ($kn) {

            $result .= (empty($result) ? "" : " ") . Utils::number_to_words($kn) . " Thousand";

        }



        if ($Hn) {

            $result .= (empty($result) ? "" : " ") . Utils::number_to_words($Hn) . " Hundred";

        }



        $ones = array("", "One", "Two", "Three", "Four", "Five", "Six",

            "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",

            "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eightteen",

            "Nineteen");

        $tens = array("", "", "Twenty", "Thirty", "Fourty", "Fifty", "Sixty",

            "Seventy", "Eigthy", "Ninety");



        if ($Dn || $n) {

            if (!empty($result)) {

                $result .= " and ";

            }



            if ($Dn < 2) {

                $result .= $ones[$Dn * 10 + $n];

            } else {

                $result .= $tens[$Dn];

                if ($n) {

                    $result .= "-" . $ones[$n];

                }

            }

        }



        if ($cn) {

            if (!empty($result)) {

                $result .= ' and ';

            }

            $title = '';


            //$title = $cn==1 ? 'cent ': 'cents';
            $title = $cn==1 ? 'coin ': 'coins';

            $coinInWordsArr = Utils::coinInWords();
            $coinInWordsSingleArr = Utils::coinInWordsSingle();


            $currency = CURRENCY;
           if(!empty($currency)) {
               if(array_key_exists($currency, $coinInWordsSingleArr) && array_key_exists($currency, $coinInWordsArr)){

                   $title = $cn==1 ? $coinInWordsSingleArr[$currency].' ': $coinInWordsArr[$currency];
               }
           }

            $result .= strtolower(Utils::number_to_words($cn)) . ' ' . $title;

        }



        if (empty($result)) {

            $result = "zero";

        }



        return $result;

    } //End Function

    public static function checkDateTime($data, $type = 'timestamp') {
        $checkDate = ($type == 'date') ? date('Y-m-d', strtotime($data)) : date('Y-m-d H:i:s', strtotime($data));
        if ($checkDate == $data) {
            return true;
        } else {
            return false;
        }
    }

// End Function

    public static function formatServiceExpiry($dataArr) {
        /* Example
          $dataArr = array('dGeneratedDate' => '',
          'vBillingInterval' => '',
          'nBillingDuration' => '');
         */
        $bStartDate = $dataArr['dGeneratedDate'];

        switch ($dataArr['vBillingInterval']) { // $dataArr['nBillingDuration']
            case 'M':
                $addDays = NULL;
                if ($dataArr['nBillingDuration'] == 1) {
                    $addDays = " +" . $dataArr['nBillingDuration'] . " day";
                } else if ($dataArr['nBillingDuration'] > 1) {
                    $addDays = " +" . $dataArr['nBillingDuration'] . " days";
                }

                $bStopDate = strtotime(date("Y-m-d", strtotime($bStartDate)) . $addDays);
                $bStopDate = date("Y-m-d H:i:s", $bStopDate);
                break;
            case 'Y':
                $addYear = NULL;
                $addYear = " +" . $dataArr['nBillingDuration'] . " years";
                $bStopDate = strtotime(date("Y-m-d", strtotime($bStartDate)) . $addYear);
                $bStopDate = date("Y-m-d H:i:s", $bStopDate);
                break;
            case 'L':
                $bStopDate = NULL;  // Unlimited Service
                break;
        }
        Logger::info($bStopDate);

        return $bStopDate;
    }

// End Function


    /*
     * funtion to get the active theme
     */

    public static function loadActiveTheme() {
        $db = new Db();
        $themeData = $db->selectResult('themes', 'theme_name', 'theme_status=1');
        $activeTheme = $themeData[0]->theme_name;
        //TODO: add theme folder existing validation
        PageContext::addStyle("themes/" . $activeTheme . "/layout.css");
        PageContext::addStyle("themes/" . $activeTheme . "/theme.css");
        //return $activeTheme;
    }

    public static function getThemeUrl() {
        $db = new Db();
        $themeData = $db->selectResult('themes', 'theme_name', 'theme_status=1');
        $activeTheme = $themeData[0]->theme_name;
        return BASE_URL . 'project/styles/themes/' . $activeTheme . '/';
    }

    public static function loadScreenShots() {
        $db = new Db();
        $res = $db->selectResult('Products', '*', 'nStatus=1');
        return $res;
    }

    // For Stripslashes
    public static function stripslashes($string) {

        return stripslashes($string);
    }

    // Escape Strings before post  // data sanitising
    public static function formatPostData($string) {
        return mysql_real_escape_string($string);
    }

    public static function subString($string, $length = 100, $append = NULL, $start = 0) {
        $content = NULL;
        if (!empty($string)) {
            $content = stripslashes(substr($string, $start, $length));
            $content .= $append;
        }
        return $content;
    }
    
    
    public static function getSettingsData($field)
    {
        $db = new Db();
        $settingsData = $db->selectResult('Settings', 'value', "settingfield='".$field."'");
        $settingsVal = $settingsData[0]->value;
        return $settingsVal;
         
    }

    public function uploadFile($files) {
        $fileHandler = new Filehandler();

        $upload = $fileHandler->handleUpload($files);
        return $upload;
    }

    /*
    * function to generate thumbnail
    */
    public function createThumbnail($photoid,$thumbtype,$crop=true) {

        global $imageTypes;
        
        $model          = new Db();
        $fileDet    = $model->selectRecord("files","file_orig_name,file_path","file_id=".$photoid);
        $sourceFile = FILE_UPLOAD_DIR.'/'. $fileDet->file_path;
        $destFile  = FILE_UPLOAD_DIR.'/'.$imageTypes[$thumbtype]['prefix']. $fileDet->file_path;
        $ih = new Gdimagehandler($sourceFile);
        $ih->generateThumbnail($destFile,$imageTypes[$thumbtype]['width'],$imageTypes[$thumbtype]['height'],$crop);

    }

    public function generateThumbnail($imgUrl,$thumbtype,$crop=true) {

        global $imageTypes;

        $sourceFile = FILE_UPLOAD_DIR.'/'. $imgUrl;
        $destFile  = FILE_UPLOAD_DIR.'/'.$thumbtype['new_name'];

        $ih = new Gdimagehandler($sourceFile);
        $ih->generateThumbnail($destFile,$thumbtype['width'],$thumbtype['height'],$crop);
        return true;
    }

    public static function bindEmailTemplate($mailContent){
        $mailMsgArr = Admincomponents::getListItem("Cms", array('cms_title','cms_desc'), array(array('field' => 'LOWER(cms_name)', 'value' => strtolower('email_template'))));
            Logger::info($mailMsg);

           $mailMsg = NULL;

            if(count($mailMsgArr) > 0) {
                
                $mailMsg = $mailMsgArr[0]->cms_desc;
            } // End If

            if(!empty($mailMsg)){
                $mailMsg = str_replace("{SITE_LOGO}", SITE_LOGO, $mailMsg);
                $mailMsg = str_replace("{DATE}", Utils::formatDateUS(date('Y-m-d'), false, 'date'), $mailMsg);
                $mailMsg = str_replace("{MAIL_CONTENT}", $mailContent, $mailMsg);
                $mailMsg = str_replace("{SITE_NAME}", SITE_NAME, $mailMsg);
            } else {
                $mailMsg =$mailContent;
            }
            return $mailMsg;

    }
    
    public static function splitEmailIntoParts($email, $opType = 'all'){
        $partsArr = array();
        if(!empty($email)){
            $parts = explode('@', $email);
            $user = $parts[0];
            //$domain = "@" . $parts[1];
            $domain = $parts[1];
            $partsArr = array('user' => $user,
                               'domain' => $domain);
        } // End If

        switch($opType){
            case 'user':
                return $user;
                break;
            case 'domain':
                return $domain;
                break;
            case 'all':
                return $partsArr;
                break;
        }
       
    } // End Function

    public static function coinInWordsSingle(){
        $dataArr = array("USD" => "cent",
                          "CAD" => "cent",
                         "GBP" => "pence");
        return $dataArr;
    } // End Function

    public static function coinInWords(){
        $dataArr = array("USD" => "cents",
                          "CAD" => "cents",
                         "GBP" => "pence");

        return $dataArr;
    } // End Function

    // Code added after 31/July/2014
    // 
    // For checking mandatory fields of a request
    private function validateFields($mandatoryFields,$requestType='post'){
        
       $requestArr = ( $requestType == 'post' ) ? $_POST : $_GET ;


       
       foreach($mandatoryFields as $key=>$val){
           $myVar = trim($requestArr[$key]);
           
           if( $myVar == ''){
               $message .= self::provideMessage('mandatory');
               return false;
           }

           $validations = explode('|',$val);
           if(count($validations)>1){

               
               foreach($validations as $type){

                   $type = trim($type);
                   $valid = true;
                   switch($type){
                       case 'email' : $valid = self::validateEmail($myVar);
                                      break;
                       case 'nameString' : $valid = self::validateNameString($myVar);
                                      break;
                       case 'numeric' : $valid = self::validateNumeric($myVar);
                                      break;

                   }
                   if(!$valid){
                      $message .= self::provideMessage($type);
                       //break;
                   }
               }

           }
            
       }
       return true;
    }

    // For validating email field of a request
    private function validateEmail($email) {

        return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{1,6}$", $email);
    }

     // For validating name field of a request
    private function validateNameString($name) {

        return eregi("^([ \u00c0-\u01ffa-zA-Z'\-])+$", $name);
    }

    // For validating name field of a request
    private function validateNumeric($number) {

        return eregi("^[0-9]+$", $name);
    }
    
    // For returning output as json
    public static function sendResponse($returnArray,$resultFlag='json'){
        
        echo json_encode($returnArray);
        exit;

    }

    // Data sanitizing beofre db operation
    public static function sanitize($string){
        return mysql_real_escape_string($string);
    }

    private function provideMessage($type =''){
        switch($type){
            case 'mandatory' : $message = "Please provide all mandatory fields.";
                                break;
            case 'email'     : $message = "Please provide a valid email.";
                                break;
            case 'nameString': $message = "Please provide a valid name.";
                                break;
            case 'numeric'   : $message = "Please provide a valid number.";
                                break;

        }
        return "<p>$message</p>";
    }

    public static function processFormData($mandatoryFields,$requestType='post'){

        $valid  =   self::validateFields($mandatoryFields,$requestType);
        
        
        if(!$valid) {
           $response['status'] = 0;
           $response['message'] = $message;

           
           self::sendResponse($response);
           
        }

    }

    // Encrypt card detail
    public static function encrytCreditCardDetails($string) {
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5(USER_CREDIT_CARD_ENCRYPT_KEY), $string, MCRYPT_MODE_CBC, md5(md5(USER_CREDIT_CARD_ENCRYPT_KEY))));
    }

    // Decrypt card details
    public static function decrytCreditCardDetails($string) {
    return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5(USER_CREDIT_CARD_ENCRYPT_KEY), base64_decode($string), MCRYPT_MODE_CBC, md5(md5(USER_CREDIT_CARD_ENCRYPT_KEY))), "\0");
    }


    public static function boxResize($path, $sourceFileName, $destFileName,$destination_path, $img_width, $img_height,$method='ZEBRA_IMAGE_BOXED',$bgcolor='FFFFFF') {


        PageContext::includePath('imagehandle');
        $ObjImagehandle                         = new ImagehandleComponent();
        $ObjImagehandle->source_path            = $path.'/'.$sourceFileName;
        $ObjImagehandle->preserve_aspect_ratio  = false;
        $ObjImagehandle->enlarge_smaller_images = true;
        $ObjImagehandle->preserve_time          = true;

        $ObjImagehandle->target_path = $destination_path.'/'.$destFileName;
        $ObjImagehandle =$ObjImagehandle->resize($img_width, $img_height,ZEBRA_IMAGE_BOXED,$bgcolor);

    }

    public static function imageResize($sourceFile,$info, $image, $hashId,$imageName,$imageType,$thumbnailWidth,$thumbnailHeight) {
        $jpeg_quality = 100;
        copy($sourceFile,FILE_UPLOAD_DIR."/stores/".$hashId."/products/$imageName");

        $oldWidth = $info[0];
        $oldHeight = $info[1];

        $aspect = $oldWidth / $oldHeight;
        if($oldWidth>=$oldHeight) {
            $newWidth = $thumbnailWidth;
            $newHeight = $newWidth / $aspect;
            if($newHeight>$thumbnailHeight) {
                $newWidth = ($thumbnailHeight*$thumbnailWidth)/$newHeight;
                $newHeight = $thumbnailHeight;

            }
        }
        else {
            $newHeight = $thumbnailHeight;
            $newWidth  = $newHeight *  $aspect;
            if($newWidth>$thumbnailWidth) {
                $newHeight = ($thumbnailHeight*$thumbnailWidth)/$newWidth;
                $newWidth = $thumbnailWidth;

            }
        }

        $dst_r = ImageCreateTrueColor($newWidth, $newHeight );
        imagealphablending( $dst_r, false );
        imagesavealpha( $dst_r, true );
        imagecopyresampled($dst_r, $image, 0, 0, 0, 0, $newWidth, $newHeight, $oldWidth, $oldHeight);
        $destLocation = "project/files/stores/".$hashId."/products/";
        $destImage = "project/files/stores/".$hashId."/products/".$imageName;

        switch ($imageType) {
            case jpeg: {
                    imagejpeg($dst_r,$destImage,$jpeg_quality);
                    break;
                }
            case jpg: {
                    imagejpeg($dst_r,$destImage,$jpeg_quality);
                    break;
                }
            case png: {
                    imagepng($dst_r,$destImage,9);
                    break;
                }
            case gif: {
                    imagegif($dst_r,$destImage);
                    break;
                }

        }
        $destLocation = "project/files/stores/".$hashId."/products//";
        $destImage = "project/files/stores/".$hashId."/products/".$imageName;
        $destinationFile        =  FILE_UPLOAD_DIR."/stores/".$hashId."/products/".$thumbnailWidth."_".$thumbnailHeight;
        copy($destImage,$destinationFile."/".$imageName);
        unlink($destImage);

    }
    
     public static function formatText($txtString)
        {
            if($txtString)
               $newString =  strip_tags(html_entity_decode(stripslashes(nl2br($txtString)),ENT_NOQUOTES,"Utf-8"));
            return $newString;
        }
    
    public static function sendEmailTest($toEmail, $mailSubject, $emailContent) {

        /*mail test 1 start*/
        /*ini_set( 'display_errors', 1 );
        error_reporting( E_ALL );
        $from = "vibin.j@armiasystems.com";
        $to = "armiatester@gmail.com";
        $subject = "PHP Mail Test script";
        $message = "This is a test to check the PHP Mail functionality";
        $headers = "From:" . $from;
        if(mail($to,$subject,$message, $headers)) {
            echo "mail send";
        } else {

            print_r(error_get_last());
        }*/

        /*mail test1 end*/

        /*mail test2 start*/

        $smtpMail = 1;
        PageContext::includePath('phpmailer');
        $db = new Db();
        $adfromemail = $db->selectRow("settings",'site_email');
        $adfromemailname = $db->selectRow("settings",'site_name');
        $adreplyemail = $db->selectRow("settings",'site_email');
        $adreplyemailname = $db->selectRow("settings",'site_name');
        $mailHeader =    Utils::getCommonTemplateHeader();
        $mailFooter =    Utils::getCommonTemplateFooter();
        $mail  = new PHPMailer(true);

       /* try {*/
            $mailBody           = '<h1>Test mail</h1></br><h1>test mail2</h2>';
            $mailBody           =   $mailHeader.$mailBody.$mailFooter;
            $mailSubject        =   'Testing mail';        
            if($smtpMail){
                    $mail->IsSMTP(); // telling the class to use SMTP

                    $mail->SMTPSecure = 'tls';
                    $mail->Host       = "smtp.office365.com"; // SMTP server
                    $mail->SMTPAuth   = true;                  // enable SMTP authentication
                    $mail->Port       = 587;                    // set the SMTP port for the GMAIL server
                    $mail->Username   = "contact@wildkale.com"; // SMTP account username
                    $mail->Password   = "Wildkale2016$";        // SMTP account password  
            }
                            
                $mail->AddReplyTo($adreplyemail,$adreplyemailname);
                if(ENVIRONMENT == 'LOCAL' || ENVIRONMENT == 'CLIENTSLIVE' || ENVIRONMENT == 'PILOTSERVER') {
                    $adfromemail = 'contact@wildkale.com';
                }
                $mail->SetFrom($adfromemail,$adfromemailname);          
                $mail->AddAddress('serverhelp000@gmail.com');
                
                
                $mail->Subject              = $mailSubject;
                $mail->AltBody              = ''; 
                $mail->MsgHTML($mailBody);
                echo "in"; echo "<br>";
               
            if(!$mail->Send()) {
                echo $mail->ErrorInfo;
            } else {
                echo "success";
            }
                 
               
       /* }catch (phpmailerException $e) {
          echo $e->errorMessage(); 
        } catch (Exception $e) {
          echo $e->getMessage();
        }*/
        /*mail test2 end*/
        
        

    }
    
    
     public static function convertin24_HourFormat($time)
        {
         // 12-hour time to 24-hour time 
            $timevalue = $time. "PM";
            $time_in_24_hour_format  = date("H", strtotime($timevalue));
            return $time_in_24_hour_format;
        }
        
     public static function convertin12_HourFormat($time)
    {
        // 24-hour time to 12 hour
        $timevalue = $time.":00";
        $time_in_12_hour_format  = date("g", strtotime($timevalue));
        return $time_in_12_hour_format;
    }
    
    public static function format_time($time)
    {
        // 24-hour time to 12 hour
        if(strlen($time)<=1)
        {
            $newVal = str_pad($time, 2, '0', STR_PAD_LEFT);
        }else{
            $newVal = $time;
        }
        
        return  $newVal;

    }
    
     public static function current_time_24HourFormat($time)
    {
        // 24-hour time to 12 hour
         $current_time = date('G:i:a');
         $time_in_24_hour_format  = date("H");
         return $time_in_24_hour_format;        
    }
    
    
      public static function escapeString($txtString)
        {
            if($txtString)
               $newString =  strip_tags(stripslashes(nl2br($txtString)));
            return $newString;
        }
        
        
        public static function formatString($txtString)
        {
            if($txtString)
               $newString =  html_entity_decode(stripslashes(nl2br($txtString)),ENT_NOQUOTES,"Utf-8");
            return $newString;
        }
    

   

}

// End Class
?>