<?php

class Mail_Manager_model extends CI_Model {

    var $adminContactProfile = null;
    var $invoiceEmailContent = array();
    public function __construct() {
        parent::__construct();
        $this->load->library('email');
    }

    function getMail($merchantRowId, $code) {
        $sql = 'SELECT * FROM tbl_email_manager
                WHERE merchant_row_id = ' . $this->db->escape($merchantRowId) . '
                AND customer_email_number = ' . $this->db->escape($code);

        $resultSet = $this->db->query($sql);
        $row = $resultSet->row();

        if ($row) {
            $row->email_body = html_entity_decode($row->email_body, ENT_QUOTES);
        }

        return $row;
    }

    function getAdminMail($code) {
        $sql = 'SELECT * FROM tbl_admin_email_manager
                WHERE email_code = ' . $this->db->escape($code);
        $resultSet = $this->db->query($sql);
        $row = $resultSet->row();  
        $this->db->reset_query();
        if ($row) {
            $row->email_body = html_entity_decode($row->email_body, ENT_QUOTES);
        }

        return $row;
    }

    function getAdminContactProfile() {
        if (empty($this->adminContactProfile)) {
            $ci = get_instance();
            $ci->load->model('administration/contact_profile_model', 'Contact_Profile_model', TRUE);
            $this->adminContactProfile = $ci->Contact_Profile_model->getSuperAdminContactDetails();
        }
        return $this->adminContactProfile;
    }

    function parseMerchantContactProfile($merchantRowId, $email) {
        $sql = 'SELECT email_from_name,
                    first_name,
                    last_name,
                    company_name,
                    public_email,
                    merchant_contact_phone,
                    merchant_address,
                    merchant_city,
                    state_province_name,
                    merchant_zip_code,
                    merchant_postal_code,
                    merchant_country,
                    website_url,
                    merchant_fax_number,
                    merchant_skype_id,
                    merchant_yahoo_id,
                    merchant_facebook,
                    merchant_tagline,
                    merchant_image,
                    show_first_name,
                    show_last_name,
                    show_company_name,
                    show_public_email,
                    show_merchant_contact_phone,
                    show_merchant_address,
                    show_merchant_city,
                    show_state_province_name,
                    show_merchant_zip_code,
                    show_merchant_postal_code,
                    show_merchant_country,
                    show_website_url,
                    show_merchant_fax_number,
                    show_merchant_skype_id,
                    show_merchant_yahoo_id,
                    show_merchant_facebook,
                    show_merchant_tagline,
                    show_merchant_image
                FROM tbl_merchant
                WHERE merchant_row_id = ' . $this->db->escape($merchantRowId);

        $resultSet = $this->db->query($sql);
        $row = $resultSet->row();

        if ($row) {
            $tags = array('<#MerchantEmailFromName#>',
                '<#MerchantFirstName#>',
                '<#MerchantLastName#>',
                '<#MerchantCompanyName#>',
                '<#MerchantPublicEmail#>',
                '<#MerchantContactPhone#>',
                '<#MerchantAddress#>',
                '<#MerchantCity#>',
                '<#MerchantStateProvinceName#>',
                '<#MerchantZipCode#>',
                '<#MerchantPostalCode#>',
                '<#MerchantCountry#>',
                '<#MerchantWebsiteUrl#>',
                '<#MerchantFaxNumber#>',
                '<#MerchantSkypeId#>',
                '<#MerchantYahooId#>',
                '<#MerchantFacebook#>',
                '<#MerchantTagline#>',
                '<#MerchantImage#>',
                '<#MerchantContactProfile#>');

            $values = array($row->email_from_name);
            $merchantContactProfile = '';

            if ($row->show_first_name) {
                $values[] = $row->first_name;
                $merchantContactProfile .= $row->first_name;
            } else {
                $values[] = '';
            }

            if ($row->show_last_name) {
                $values[] = $row->last_name;
                $merchantContactProfile .= ' ' . $row->last_name;
            } else {
                $values[] = '';
            }

            $merchantContactProfile .= $row->show_first_name || $row->last_name ? '<br />' : '';

            if ($row->show_company_name) {
                $values[] = $row->company_name;
                $merchantContactProfile .= $row->company_name . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_public_email) {
                $values[] = $row->public_email;
                $merchantContactProfile .= $row->public_email . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_contact_phone) {
                $values[] = $row->merchant_contact_phone;
                $merchantContactProfile .= $row->merchant_contact_phone . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_address) {
                $values[] = $row->merchant_address;
                $merchantContactProfile .= $row->merchant_address . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_city) {
                $values[] = $row->merchant_city;
                $merchantContactProfile .= $row->merchant_city . ', ';
            } else {
                $values[] = '';
            }

            if ($row->show_state_province_name) {
                $values[] = $row->state_province_name;
                $merchantContactProfile .= $row->state_province_name . ' ';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_zip_code) {
                $values[] = $row->merchant_zip_code;
                $merchantContactProfile .= $row->merchant_zip_code . ' ';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_postal_code) {
                $values[] = $row->merchant_postal_code;
                $merchantContactProfile .= $row->merchant_postal_code . ' ';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_country) {
                $values[] = $row->merchant_country;
                $merchantContactProfile .= $row->merchant_country;
            } else {
                $values[] = '';
            }

            $merchantContactProfile .= $row->show_merchant_city || $row->show_state_province_name || $row->show_merchant_zip_code || $row->show_merchant_postal_code || $row->show_merchant_country ? '<br />' : '';

            if ($row->show_website_url) {
                $values[] = $row->website_url;
                $merchantContactProfile .= $row->website_url . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_fax_number) {
                $values[] = $row->merchant_fax_number;
                $merchantContactProfile .= 'Fax: ' . $row->merchant_fax_number . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_skype_id) {
                $values[] = $row->merchant_skype_id;
                $merchantContactProfile .= 'Skype: ' . $row->merchant_skype_id . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_yahoo_id) {
                $values[] = $row->merchant_yahoo_id;
                $merchantContactProfile .= 'Yahoo: ' . $row->merchant_yahoo_id . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_facebook) {
                $values[] = $row->merchant_facebook;
                $merchantContactProfile .= 'FaceBook: ' . $row->merchant_facebook . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_tagline) {
                $values[] = $row->merchant_tagline;
                $merchantContactProfile .= $row->merchant_tagline . '<br />';
            } else {
                $values[] = '';
            }

            if ($row->show_merchant_image) {
                $imagePath = $row->merchant_image ? '<img src="' . NONSECUREBASEURL . $this->config->item('mechant_profile_image_path') . $row->merchant_image . '"/>' : '';
                $values[] = $imagePath;
                $merchantContactProfile .= $imagePath;
            } else {
                $values[] = '';
            }

            $values[] = $merchantContactProfile;

            $email->from_name = $row->email_from_name ? $row->email_from_name : ($row->company_name ? $row->company_name : $row->first_name . ' ' . $row->last_name);
            $email->email_body = str_replace($tags, $values, $email->email_body);
            $email->email_subject = str_replace($tags, $values, $email->email_subject);
        }

        return $email;
    }

    function parseAffiliateManagerProfile($merchantRowId, $email) {
        $sql = 'SELECT  amp.first_name,
                        amp.last_name,
                        amp.email_from_name,
                        amp.phone,
                        amp.web_url,
                        amp.show_first_name,
                        amp.show_last_name,
                        amp.show_email_from_name,
                        amp.show_phone,
                        amp.show_web_url,
                        ans.aff_admin_url
                FROM tbl_affiliate_manager_profile amp
                LEFT OUTER JOIN tbl_aff_notification_setup ans ON ans.merchant_row_id = amp.merchant_row_id
                WHERE amp.merchant_row_id = ' . $this->db->escape($merchantRowId);

        $resultSet = $this->db->query($sql);
        $row = $resultSet->row();

        if ($row) {
            $affiliateManagerProfile = '';
            if ($row->show_first_name)
                $affiliateManagerProfile .= $row->first_name . ' ';
            if ($row->show_last_name)
                $affiliateManagerProfile .= $row->last_name . '<br />';

            $affiliateManagerProfile .= $row->aff_admin_url . '<br />';

            if ($row->show_email_from_name)
                $affiliateManagerProfile .= $row->email_from_name . '<br />';
            if ($row->show_phone)
                $affiliateManagerProfile .= $row->phone . '<br />';
            if ($row->show_web_url)
                $affiliateManagerProfile .= $row->web_url;

            $tags = array('<#AffiliateManagerProfile#>',
                '<#MerchantAffFirstName#>',
                '<#MerchantAffLastName#>',
                '<#MerchantAffEmailName#>',
                '<#MerchantAffPhone#>',
                '<#MerchantAffWebUrl#>',
                '<#AffiliateAdminEmail#>',
                '<#AffAdminEmail#>');

            $values = array($affiliateManagerProfile,
                $row->first_name,
                $row->last_name,
                $row->email_from_name,
                $row->phone,
                $row->web_url,
                $row->aff_admin_url,
                $row->aff_admin_url);

            $email->from_name = $row->email_from_name ? $row->email_from_name : $row->first_name . ' ' . $row->last_name;
            $email->email_body = str_replace($tags, $values, $email->email_body);
        }

        return $email;
    }

    function parseAffiliateInformation($affiliateRowId, $emailBody) {
        $sql = 'SELECT  a.affiliate_id,
                        a.merchant_row_id,
                        a.affiliate_name,
                        a.affiliate_email,
                        a.affiliate_company,
                        a.affiliate_username,
                        a.affiliate_password,
                        asal.generated_link
                FROM tbl_affiliate a
                JOIN tbl_merchant_aff_program AS map ON map.merchant_row_id = a.merchant_row_id AND map.is_default=1
                JOIN tbl_ads_program_specific_affiliate_link AS asal ON asal.merchant_aff_program_row_id = map.merchant_aff_program_row_id
                WHERE a.affiliate_row_id = ' . $this->db->escape($affiliateRowId);

        $resultSet = $this->db->query($sql);
        $row = $resultSet->row();

        if ($row) {
            $tags = array('<#AffiliateID#>',
                '<#AffiliateName#>',
                '<#AffiliateEmail#>',
                '<#AffiliateCompany#>',
                '<#AffiliateUsername#>',
                '<#AffiliatePassword#>',
                '<#AffiliateLink#>',
                '<#AffiliateLogin#>');

            $values = array($row->affiliate_id,
                $row->affiliate_name,
                $row->affiliate_email,
                $row->affiliate_company,
                $row->affiliate_email,
                $row->affiliate_password,
                $row->generated_link . $affiliateRowId,
                BASEURL . 'affLogin/' . $row->merchant_row_id . '.html');


            $emailBody->email_subject = str_replace($tags, $values, $emailBody->email_subject);
            $emailBody->email_body = str_replace($tags, $values, $emailBody->email_body);
        }
        return $emailBody;
    }

    function sendMail($fromAddress, $fromName, $toAddress, $subject, $emailBody, $ccAddress = '', $replyToEmail = '', $replyToName = '', $mailCode = '') {
        $this->email->set_mailtype('html');
        $this->email->from($fromAddress, $fromName);
        if ($replyToEmail)
            $this->email->reply_to($replyToEmail, $replyToName);
        else
            $this->email->reply_to($fromAddress);

        $this->email->to($toAddress);

        if ($ccAddress) {
            $this->email->cc($ccAddress);
        }

        //$this->email->bcc('demo@athena-soft.com');

        $this->email->subject($subject);
        $info['mailBody'] = $emailBody;
        $info['mailCode'] = $mailCode;
        $emailBody = $this->load->view('template_mail', $info, true);
        $this->email->message($emailBody);
        $this->email->send();
        $this->email->clear();
    }

    function getOrderInvoice($data) {
        if(isset($this->invoiceEmailContent[$data['orderDetails']->order_row_id]) && $this->invoiceEmailContent[$data['orderDetails']->order_row_id])
           return $this->invoiceEmailContent[$data['orderDetails']->order_row_id];

        $currency_symbol = $data['currency_symbol'];
        $data = assignObjects($data, array('customer_info'));
        $data['customer_info'] = assignProperties($data['customer_info'], array('company_name',
            'first_name',
            'last_name',
            'work_phone_number',
            'home_phone_number',
            'customer_email',
            'shipping_name',
            'shipping_company_name',
            'address_line1',
            'address_line2',
            'shipping_address_line1',
            'shipping_address_line2',
            'customer_city',
            'shipping_customer_city',
            'customer_state',
            'shipping_customer_state',
            'customer_zip',
            'shipping_customer_zip',
            'country',
            'shipping_country'));

        $data = assignObjects($data, array('orderDetails'));
        $data['orderDetails'] = assignProperties($data['orderDetails'], array('order_id',
            'order_discount',
            'country_tax',
            'state_tax',
            'shpping_amount',
            'coupon_discount',
            'total_amount'));

        $ci = get_instance();    
        $ci->load->model('carts/Cart_Setup_model', 'Cart_Setup_model', TRUE);    
        $optionalFieldsLabel = $ci->Cart_Setup_model->getCustomizeField($data['orderDetails']->merchant_row_id);    
        $additionalInformation = '';
        
        for($i = 4; $i <= 13; $i++)
        {
           $index =  'field' .$i ;
           if($data['orderDetails']->$index)
           {   
               $additionalInformation .= "<tr><td>" . $optionalFieldsLabel['field' . $i . '_label']. "</td><td>" . $data['orderDetails']->$index ." </td></tr>";
           } 
        }        
        if($data['orderDetails']->cmb1)
        {   
            $additionalInformation .= "<tr><td>" . $optionalFieldsLabel['cmb1_label']. "</td><td>" . $data['orderDetails']->cmb1 ." </td></tr>";
        } 
        if($data['orderDetails']->hear_about)
        {
            $additionalInformation .= "<tr><td><strong>How Did You Hear of Us?</strong></td><td>{$data['orderDetails']->hear_about}</td></tr>";
        }
        if($additionalInformation)
        {
            $additionalInformation = '<tr><td colspan="2"><b>Additional Information</b></td></tr><tr><td colspan="2"><hr class="headHR"/></td></tr>' . $additionalInformation;
        }
            
        $returnHtml = '<p>
                        <table cellpadding="4" cellspacing="0" border="0" width="70%" align="center">
                            <tr>
                                <td colspan="2" style="font-size:14px; font-weight:bold;">' . (!empty($data['customer_info']->company_name) ? $data['customer_info']->company_name . ' ' : '') . 'Invoice</td>
                            </tr>
                            <tr>
                                <td colspan="2" height="10"><hr /></td>
                            </tr>
                            <tr>
                                <td width="35%">First Name:</td>
                                <td>' . $data['customer_info']->first_name . '</td>
                            </tr>
                            <tr>
                                <td>Last Name:</td>
                                <td>' . $data['customer_info']->last_name . '</td>
                            </tr>
                            <tr>
                                <td>Work Phone Number:</td>
                                <td>' . $data['customer_info']->work_phone_number . '</td>
                            </tr>
                            <tr>
                                <td>Home Phone Number:</td>
                                <td>' . $data['customer_info']->home_phone_number . '</td>
                            </tr>
                            <tr>
                                <td>Email:</td>
                                <td>' . $data['customer_info']->customer_email . '</td>
                            </tr>
                            <tr>
                                <td><b>Billing Address</b></td>
                                <td><b>Shipping Address</b></td>
                            </tr>
                            <tr>
                                <td><hr /></td>
                                <td><hr /></td>
                            </tr>
                            <tr>
                                <td>' . $data['customer_info']->first_name . ' ' . $data['customer_info']->last_name . '</td>
                                <td>' . $data['customer_info']->shipping_name . '</td>
                            </tr>
                            <tr>
                                <td>' . $data['customer_info']->company_name . '</td>
                                <td>' . $data['customer_info']->shipping_company_name . '</td>
                            </tr>
                            <tr>
                                <td>' . $data['customer_info']->address_line1 . '<br />' . $data['customer_info']->address_line2 . '</td>
                                <td>' . $data['customer_info']->shipping_address_line1 . '<br />' . $data['customer_info']->shipping_address_line2 . '</td>
                            </tr>
                            <tr>
                                <td>' . $data['customer_info']->customer_city . '</td>
                                <td>' . $data['customer_info']->shipping_customer_city . '</td>
                            </tr>
                            <tr>
                                <td>' . $data['customer_info']->customer_state . '</td>
                                <td>' . $data['customer_info']->shipping_customer_state . '</td>
                            </tr>
                            <tr>
                                <td>' . $data['customer_info']->customer_zip . '</td>
                                <td>' . $data['customer_info']->shipping_customer_zip . '</td>
                            </tr>
                            <tr>
                                <td>' . $data['customer_info']->country . '</td>
                                <td>' . $data['customer_info']->shipping_country . '</td>
                            </tr>' . $additionalInformation . '
                            <tr>
                                <td colspan="2" style="padding-top:10px;">Order Details (Order Id : ' . $data['orderDetails']->order_id . ')</td>
                            </tr>
                        </table>
                        <div>&nbsp;</div>
                        <table cellpadding="4" cellspacing="0" border="0" width="70%" align="center">
                            <tr>
                                <th align="left">SKU</th>
                                <th align="left">Description</th>
                                <th align="left">Option</th>
                                <th align="left">Quantity</th>
                                <th align="left">Price</th>
                                <th align="right">Total Price</th>
                            </tr>
                            <tr><td colspan="6"><hr class="headHR"/></td></tr>';
        $bundleId = '';
        $isFirst = TRUE;

        if (isset($data['orderProductList']) && $data['orderProductList']) {
            foreach ($data['orderProductList'] as $aOrder) {
                $returnHtml .= '
                            <tr>
                                <td>' . $aOrder->product_code . '&nbsp;</td>
                                <td>';

                if ($aOrder->bundle_type == $this->config->item('offerTypeAdvanced')) {
                    if ($bundleId != $aOrder->bundle_id) {
                        $returnHtml .= $aOrder->offer_name;
                        $bundleId = $aOrder->bundle_id;
                        $isFirst = TRUE;
                    } else {
                        $returnHtml .= $aOrder->product_quantity . ' X ' . $aOrder->product_description;
                        $isFirst = FALSE;
                    }
                } else {
                    $returnHtml .= $aOrder->product_description;
                    $isFirst = TRUE;
                }
                $returnHtml .= ' </td>
                                <td>';

                $returnHtml .=$aOrder->product_attribute;

                if ($aOrder->free_text_attribute) {
                    $comma = trim($aOrder->product_attribute) ? ',' : '';
                    $returnHtml .= $comma . $aOrder->free_text_attribute;
                }
                $returnHtml .= '&nbsp;</td>
                                <td>';

                if ($isFirst) {
                    $returnHtml .= $aOrder->product_quantity;
                }

                $returnHtml .= '&nbsp;</td>
                                <td>';

                if ($isFirst) {
                    $returnHtml .= $currency_symbol . $aOrder->product_price;
                }

                $returnHtml .= '&nbsp;</td>
                                 <td align="right">';

                if ($isFirst) {
                    $returnHtml .= $currency_symbol . $aOrder->product_total_price;
                }

                $returnHtml .= '&nbsp;</td>
                            </tr>';
            }
        }

        if ($data['orderDetails']->order_discount_type == $this->config->item('discount_type_free_shipping')) {
            $returnHtml .="<tr>
                               <td colspan='3'>&nbsp;</td>
                               <td><font color='blue'>Shipping</font></td>
                               <td><font color='blue'>FREE</font></td>
                               <td align='right'><font color='blue'>FREE</font></td>
                           </tr>";
        }

        if ($data['orderDetails']->order_discount > 0) {
            $returnHtml .= '<tr>
                                <td colspan="6"><hr class="headHR"/></td>
                            </tr>
                            <tr>
                                <td colspan="5" align="right">Order Discount</td>
                                <td align="right">' . $currency_symbol . number_format($data['orderDetails']->order_discount, 2) . '</td>
                            </tr>';
        }

        if ($data['orderDetails']->country_tax > 0) {
            $returnHtml .= '<tr>
                                <td colspan="6"><hr class="headHR"/></td>
                            </tr>
                            <tr>
                                <td colspan="5" align="right">Country Tax</td>
                                <td align="right">' . $currency_symbol . number_format($data['orderDetails']->country_tax, 2) . '</td>
                            </tr>';
        }

        if ($data['orderDetails']->state_tax > 0) {
            $returnHtml .= '<tr>
                                <td colspan="6"><hr class="headHR"/></td>
                            </tr>
                            <tr>
                                <td colspan="5" align="right">State Tax</td>
                                <td align="right">' . $currency_symbol . number_format($data['orderDetails']->state_tax, 2) . '</td>
                            </tr>';
        }

        if ($data['orderDetails']->shpping_amount > 0) {

            $returnHtml .= '<tr>
                                <td colspan="6"><hr class="headHR"/></td>
                            </tr>
                            <tr>
                                <td colspan="5" align="right">Shipping';
            if ($data['shippingDetails']->shipping_id != $this->config->item('shipping_flat_rate_advanced') && !empty($data['shippingDetails']->method_name)) {
                $returnHtml .= ' &gt;&gt; ' . $data['shippingDetails']->method_name;
            }
            if (!empty($data['shippingDetails']->shipping_service)) {
                $returnHtml .= ' - ' . $data['shippingDetails']->shipping_service;
            }
            $returnHtml .= '</td>
                                <td align="right">' . $currency_symbol . number_format($data['orderDetails']->shpping_amount, 2) . '</td>
                            </tr>';
        }

        if ($data['orderDetails']->coupon_discount > 0) {
            $returnHtml .= '<tr>
                                <td colspan="6"><hr class="headHR"/></td>
                            </tr>
                            <tr>
                                <td colspan="3" align="left">
                                    Applied Coupon Codes --';

            $couponsArray = array();

            foreach ($data['appliedCoupons'] as $aCoupon) {
                $couponsArray[] = $aCoupon->coupon_code;
            }

            $couponCodes = implode(',', $couponsArray);

            $returnHtml .= $couponCodes . '
                                </td>
                                <td colspan="2" align="right">Coupon Discount</td>
                                <td align="right">' . $currency_symbol . number_format($data['orderDetails']->coupon_discount, 2) . '</td>
                            </tr>';
        }

        $orderAmount = $data['orderDetails']->total_amount;

        if (isset($data['orderDetails']->gift_certificate_payment) && $data['orderDetails']->gift_certificate_payment > 0) {
            $returnHtml .= '<tr>
                                <td colspan="6"><hr class="headHR"/></td>
                            </tr>
                            <tr>
                                <td colspan="5" align="right">Total</td>
                                <td align="right">' . $currency_symbol . number_format($orderAmount, 2) . '</td>
                            </tr>
                            <tr>
                                <td colspan="6"><hr class="headHR" /></td>
                            </tr>
                            <tr>
                                <td colspan="5" align="right">Gift Certificate Payment</td>
                                <td align="right">' . $currency_symbol . number_format($data['orderDetails']->gift_certificate_payment, 2) . '</td>
                            </tr>';

            $orderAmount -= $data['orderDetails']->gift_certificate_payment;
        }

        $returnHtml .= '    <tr>
                                <td colspan="6"><hr class="headHR" /></td>
                            </tr>
                            <tr>
                                <td colspan="5" align="right">Grand Total</td>
                                <td align="right">' . $currency_symbol . number_format($orderAmount, 2) . '</td>
                            </tr>
                        </table>
                    </p>';

        if ($data['orderDetails']->special_comments) {
            $returnHtml .= '<p>
                <table cellpadding="4" cellspacing="0" border="0" width="70%" align="center">
                    <tr>
                        <td width="175" valign="top"><b>Special Instructions/ Comments<b></td>
                        <td valign="top">' . $data['orderDetails']->special_comments . '</td>
                    </tr>
                </table>
            </p>';
        }
        $this->invoiceEmailContent[$data['orderDetails']->order_row_id] = $returnHtml;
        return $returnHtml;
    }

    function getRecurringProductDetails($data) {
        $invoiceData = $data['order_info'];
        $appliedCoupons = $data['appliedCoupons'];
        $data = assignObjects($data, array('orderDetails'));
        $data['orderDetails'] = assignProperties($data['orderDetails'], array('order_discount',
            'country_tax',
            'state_tax',
            'shpping_amount',
            'coupon_discount',
            'total_amount'));

        $currency_symbol = isset($_SESSION['currency_symbol']) ? $_SESSION['currency_symbol'] : $data['currency_symbol'];

        $returnHtml = "<p><b>Recurring Product Description</b>
                    <table cellpadding=\"2\" cellspacing=\"1\" border=\"1\" width=\"500\">

                    <tr>
                        <td>
                            <table cellpadding=\"4\" cellspacing=\"0\" border=\"0\" width=\"100%\">
                                <tr>
                                    <th class=\"leftMenuText\">SKU</th>
                                    <th class=\"leftMenuText\">Description</th>
                                    <th class=\"leftMenuText\">Option</th>
                                    <th class=\"leftMenuText\">Quantity</th>
                                    <th class=\"leftMenuText\">Recurring Price</th>
                                    <th class=\"leftMenuText\" nowrap=\"nowrap\">Total Price</th>
                                </tr>
                                <tr><td colspan=\"6\"><hr class=\"headHR\"/></td></tr>";


        $bundleId = '';
        $isFirst = TRUE;
        if (isset($data['orderRecurringProductList']) && count($data['orderRecurringProductList'])) {
            foreach ($data['orderRecurringProductList'] as $aOrder) {
                $returnHtml .="<tr>
                                    <td align=\"left\" valign=\"top\">";
                $returnHtml .=$aOrder->product_code ? $aOrder->product_code : 'N/A';
                $returnHtml .="</td>
                                    <td align=\"left\" valign=\"top\">";
                if ($aOrder->bundle_type == $this->config->item("offerTypeAdvanced")) {
                    if ($bundleId != $aOrder->bundle_id) {
                        $returnHtml .= $aOrder->offer_name;
                        $bundleId = $aOrder->bundle_id;
                        $isFirst = TRUE;
                    } else {
                        $returnHtml .= $aOrder->recurring_quantity . ' X ' . $aOrder->product_description;
                        $isFirst = FALSE;
                    }
                } else {
                    $returnHtml .= $aOrder->product_description;
                    $isFirst = TRUE;
                }
                $returnHtml .="</td>
                                    <td align=\"left\" valign=\"top\">";
                $returnHtml .=$aOrder->product_attribute;
                if ($aOrder->free_text_attribute) {
                    $comma = trim($aOrder->product_attribute) ? ',' : '';
                    $returnHtml .= $comma . $aOrder->free_text_attribute;
                }
                $returnHtml .="</td>
                                    <td align=\"left\" valign=\"top\">";
                if ($isFirst) {
                    $returnHtml .= $aOrder->recurring_quantity;
                }
                $returnHtml .="</td>
                                    <td align=\"left\" valign=\"top\">";
                if ($isFirst) {
                    $returnHtml .= $currency_symbol . $aOrder->recurring_price;
                }
                $returnHtml .="</td>
                                    <td  align=\"right\" valign=\"top\">";
                if ($isFirst) {
                    $returnHtml .= $currency_symbol . $aOrder->recurring_price;
                }
                $returnHtml .="</td>
                                </tr>";
            }
        }

        $returnHtml .="
                        <tr><td colspan=\"6\"><hr class=\"headHR\"/></td></tr>";
        if ($invoiceData->order_discount > 0) {
            $returnHtml .="
                        <tr>
                            <td colspan=\"4\"></td>
                            <td>Order Discount</td>
                            <td align=\"right\">" . $currency_symbol . number_format($invoiceData->order_discount, 2) . "</td>
                        </tr>
                        <tr><td colspan=\"6\"><hr class=\"middleHR\" /></td></tr>";
        }
        if ($invoiceData->country_tax > 0) {
            $returnHtml .="
                        <tr>
                            <td colspan=\"4\"></td>
                            <td>Country Tax</td>
                            <td align=\"right\" >" . $currency_symbol . number_format($invoiceData->country_tax, 2) . "</td>
                        </tr>
                        <tr><td colspan=\"6\"><hr class=\"middleHR\" /></td></tr>";
        }
        if ($invoiceData->state_tax > 0) {
            $returnHtml .="
                        <tr><td colspan=\"6\"><hr class=\"middleHR\" /></td></tr>
                        <tr>
                            <td colspan=\"4\"></td>
                            <td>State Tax</td>
                            <td align=\"right\" >" . $currency_symbol . number_format($invoiceData->state_tax, 2) . "</td>
                        </tr>";
        }
        if ($invoiceData->shpping_amount > 0) {
            $returnHtml .="
                        <tr>
                            <td colspan=\"4\"></td>
                            <td>Shipping</td>
                            <td align=\"right\" >" . $currency_symbol . number_format($invoiceData->shpping_amount, 2) . "</td>
                        </tr>
                        <tr><td colspan=\"6\"><hr class=\"middleHR\" /></td></tr>";
        }
        if ($invoiceData->coupon_discount > 0) {
            $returnHtml .="
                        <tr>
                            <td colspan=\"4\"></td>
                            <td>Coupon Discount</td>
                            <td align=\"right\" >" . $currency_symbol . number_format($invoiceData->coupon_discount, 2) . "</td>
                        </tr><tr><td colspan=\"6\"><hr class=\"middleHR\" /></td></tr>";
        }
        $returnHtml .="<tr>
                                        <td colspan=\"4\" valign=\"top\">";
        if ($invoiceData->coupon_discount > 0) {
            $returnHtml .="Coupon Code Applied - (";
            $index = 0;
            $couponsArray = array();
            foreach ($appliedCoupons as $aCoupon) {
                $couponsArray[$index] = $aCoupon->coupon_code;
                $index++;
            }
            $couponCodes = implode(',', $couponsArray);
            $returnHtml .= $couponCodes . ")";
        }
        $returnHtml .= "</td>
                                <td nowrap=\"nowrap\" align=\"right\" valign=\"top\">Total</td>
                                <td align=\"right\" valign=\"top\">";
        $returnHtml .= $invoiceData->total_amount ? $currency_symbol . $invoiceData->total_amount : $currency_symbol . $aOrder->recurring_price;
        $returnHtml .="</td>
                                </tr>
                            </table>
                         </td>
                      </tr>
                   </table></p>"; 
        return $returnHtml;
    }

    function getOrderProductDetails($data) {
        $data = assignObjects($data, array('orderDetails'));
        $data['orderDetails'] = assignProperties($data['orderDetails'], array('order_discount',
            'country_tax',
            'state_tax',
            'shpping_amount',
            'coupon_discount',
            'total_amount'));

        $currency_symbol = isset($_SESSION['currency_symbol']) ? $_SESSION['currency_symbol'] : $data['currency_symbol'];

        $returnHtml = '<p>
                        <b>Ordered Product Description</b>
                        <table cellpadding="2" cellspacing="1" border="1" width="500">
                            <tr>
                                <td>
                                    <table cellpadding="4" cellspacing="0" border="0" width="100%">
                                        <tr>
                                            <th class="leftMenuText">SKU</th>
                                            <th class="leftMenuText">Description</th>
                                            <th class="leftMenuText">Option</th>
                                            <th class="leftMenuText">Quantity</th>
                                            <th class="leftMenuText">Price</th>
                                            <th class="leftMenuText" nowrap="nowrap">Total Price</th>
                                        </tr>
                                        <tr>
                                            <td colspan="6"><hr class="headHR"/></td>
                                        </tr>';
        $bundleId = '';
        $isFirst = TRUE;

        if (isset($data['orderProductList']) && $data['orderProductList']) {
            foreach ($data['orderProductList'] as $aOrder) {
                $returnHtml .= '        <tr>
                                            <td>' . ($aOrder->product_code ? $aOrder->product_code : "N/A") . '&nbsp;</td>
                                            <td>';

                if ($aOrder->bundle_type == $this->config->item('offerTypeAdvanced')) {
                    if ($bundleId != $aOrder->bundle_id) {
                        $returnHtml .= $aOrder->offer_name;
                        $bundleId = $aOrder->bundle_id;
                        $isFirst = TRUE;
                    } else {
                        $returnHtml .= $aOrder->product_quantity . ' X ' . $aOrder->product_description;
                        $isFirst = FALSE;
                    }
                } else {
                    $returnHtml .= $aOrder->product_description;
                    $isFirst = TRUE;
                }
                $returnHtml .= '            </td>
                                            <td>';
                $returnHtml .=$aOrder->product_attribute;
                if ($aOrder->free_text_attribute) {
                    $comma = trim($aOrder->product_attribute) ? ',' : '';
                    $returnHtml .= $comma . $aOrder->free_text_attribute;
                }
                $returnHtml .= '&nbsp;</td>
                                            <td align="left">';

                if ($isFirst) {
                    $returnHtml .= $aOrder->product_quantity;
                }

                $returnHtml .= '&nbsp;</td>
                                            <td align="left">';
                if ($isFirst) {
                    $returnHtml .= $currency_symbol . $aOrder->product_price;
                }

                $returnHtml .= '&nbsp;</td>
                                            <td align="right">';

                if ($isFirst) {
                    $returnHtml .= $currency_symbol . $aOrder->product_total_price;
                }

                $returnHtml .= '&nbsp;</td>
                                        </tr>';
            }
        }

        if ($data['orderDetails']->order_discount > 0) {
            $returnHtml .= '            <tr>
                                            <td colspan="6"><hr class="headHR"/></td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" align="right">Order Discount</td>
                                            <td align="right">' . $currency_symbol . number_format($data['orderDetails']->order_discount, 2) . '</td>
                                        </tr>';
        }

        if ($data['orderDetails']->country_tax > 0) {
            $returnHtml .= '           <tr>
                                            <td colspan="6"><hr class="headHR"/></td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" align="right">Country Tax</td>
                                            <td align="right">' . $currency_symbol . number_format($data['orderDetails']->country_tax, 2) . '</td>
                                        </tr>';
        }

        if ($data['orderDetails']->state_tax > 0) {
            $returnHtml .= '           <tr>
                                            <td colspan="6"><hr class="headHR"/></td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" align="right">State Tax</td>
                                            <td align="right">' . $currency_symbol . number_format($data['orderDetails']->state_tax, 2) . '</td>
                                        </tr>';
        }

        if ($data['orderDetails']->shpping_amount > 0) {
            $returnHtml .= '           <tr>
                                            <td colspan="6"><hr class="headHR"/></td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" align="right">Shipping</td>
                                            <td align="right">' . $currency_symbol . number_format($data['orderDetails']->shpping_amount, 2) . '</td>
                                        </tr>';
        }

        if ($data['orderDetails']->coupon_discount > 0) {
            $returnHtml .= '           <tr>
                                            <td colspan="6"><hr class="headHR"/></td>
                                        </tr>
                                        <tr>
                                            <td colspan="3" align="left">';
            $returnHtml .= '
                                            </td>
                                            <td colspan="2" align="right">Coupon Discount</td>
                                            <td align="right">' . $currency_symbol . number_format($data['orderDetails']->coupon_discount, 2) . '</td>
                                        </tr>';
        }

        $orderAmount = $data['orderDetails']->total_amount;

        if (isset($data['orderDetails']->gift_certificate_payment) && $data['orderDetails']->gift_certificate_payment > 0) {
            $returnHtml .= '           <tr>
                                            <td colspan="6"><hr class="headHR"/></td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" align="right">Total</td>
                                            <td align="right">' . $currency_symbol . number_format($orderAmount, 2) . '</td>
                                        </tr>
                                        <tr>
                                            <td colspan="6"><hr class="headHR" /></td>
                                        </tr>
                                        <tr>
                                            <td colspan="5" align="right">Gift Certificate Payment</td>
                                            <td align="right">' . $currency_symbol . number_format($data['orderDetails']->gift_certificate_payment, 2) . '</td>
                                        </tr>';
            $orderAmount -= $data['orderDetails']->gift_certificate_payment;
        }

        $returnHtml .= '           <tr>
                                    <td colspan="6"><hr class="headHR" />
                                     </tr> <td colspan="4">';

        if ($data['orderDetails']->coupon_discount > 0) {
            $returnHtml .= 'Coupon Code Applied - (';
            $index = 0;
            $couponsArray = array();
            foreach ($data['appliedCoupons'] as $aCoupon) {
                $couponsArray[$index] = $aCoupon->coupon_code;
                $index++;
            }
            $couponCodes = implode(',', $couponsArray);
            $returnHtml .= $couponCodes . ')';
        }

        $returnHtml .= '</td>
                        <td align="right">Grand Total</td>
                        <td align="right">' . $currency_symbol . number_format($orderAmount, 2) . '</td>
                        </tr>
         </table></p>';


        if ($data['orderDetails']->special_comments) {
            $returnHtml .= '<p>
                <table cellpadding="4" cellspacing="0" border="0" width="70%" align="center">
                    <tr>
                        <td width="175" valign="top"><b>Special Instructions/ Comments<b></td>
                        <td valign="top">' . $data['orderDetails']->special_comments . '</td>
                    </tr>
                </table>
            </p>';
        }
        return $returnHtml;
    }

    function getRefundSummary($refundOrder) {
        if (!$refundOrder)
            return '';

        $currency_symbol = $_SESSION['currency_symbol'];

        $returnHtml = "
                        <table width=\"100%\" cellpadding=\"4\" cellspacing=\"4\" align=\"center\" border=\"0\">
                        <tr>
                            <td align=\"left\">
                                <b>Refund Summary</b>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <table width=\"90%\" cellpadding=\"4\" cellspacing=\"4\" align=\"center\" border=\"0\">
                                    <tr>
                                        <th align=\"left\">Refund Number</th>
                                        <th align=\"left\">Refund Status</th>
                                        <th align=\"left\">Refund Type</th>
                                        <th align=\"left\">Refund Total</th>
                                    </tr>
                                    <tr>
                                        <td colspan=\"4\">
                                            <hr class=\"headHR\"/>
                                        </td>
                                    </tr>";
        if (count($refundOrder)) {
            foreach ($refundOrder as $rOrder) {
                $returnHtml .=" <tr>
                                                                <td align=\"left\">";
                $returnHtml .= $rOrder->refund_row_id;
                $returnHtml .="</td>
                                                        <td align=\"left\">";

                if ($rOrder->amount_refund_status == $this->config->item('refund_amount_partial')) {
                    $returnHtml .=" Partial Refund";
                } else {
                    $returnHtml .="
                                                            Full Refund ";
                }
                $returnHtml .="
                                                        </td>
                                                        <td align=\"left\">";

                if ($rOrder->refund_status == $this->config->item('refund_status_charge_back')) {
                    $returnHtml .="
                                                            Charge Back";
                } else {
                    $returnHtml .="
                                                            Refund ";
                }
                $returnHtml .="
                                                        </td>
                                                        <td align=\"left\">";
                $returnHtml .= $currency_symbol . ' ' . $rOrder->refund_total;
                $returnHtml .="</td>
                                                    </tr>";
            }
        }
        $returnHtml .="
                                </table>
                            </td>
                        </tr>";
        return $returnHtml;
    }

    function sendRecurringPaymentSuccessEmail($merchantRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1006);

        $tags = array('<#CustomerName#>',
            '<#MerchantCompanyName#>',
            '<#OrderId#>',
            '<#RecurringPrice#>',
            '<#RecurringProductDetails#>',
            '<#OrderedProductDetails#>',
            '<#EditBillingInformationLink#>',
            '<#EditBillingAddressUrl#>');

        $billingLink = BASEURL . 'edit_billinginfo/editCustomerInfo/' . md5($data['orderDetails']->order_row_id);
        $values = array($data['customer_info']->first_name . ' ' . $data['customer_info']->last_name,
            $data['merchant_info']->company_name,
            $data['orderDetails']->order_id . ' - ' . $data['serial_recurring_event'],
            $data['currency_symbol'] . ' ' . $data['recurring_price'],
            $this->getRecurringProductDetails($data),
            $this->getOrderProductDetails($data),
            $billingLink,
            $billingLink
        );

        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1006);
    }

    function sendDeclineNotification($aRecurring, $merchantBasicInfo, $merchantDetails, $customerInfo, $attemptNo = 0) {
        $this->db->select('product_description');
        $this->db->from('tbl_product');
        $this->db->where('product_row_id', $aRecurring->product_row_id);
        $recordSet = $this->db->get();
        $product = $recordSet->row();

        if ($attemptNo == 0) { //decline mail
            $mailCode = 1007;
        } else if ($attemptNo == 1) {
            $mailCode = 1035;
        } else if ($attemptNo == 2) {
            $mailCode = 1036;
        } else if ($attemptNo == 3) {
            $mailCode = 1037;
        }

        $email = $this->getMail($aRecurring->merchant_row_id, $mailCode);

        $tags = array('<#CustomerName#>',
            '<#RecurringCycle#>',
            '<#RecurringPrice#>',
            '<#RecurringProductDes#>',
            '<#EditBillingInformationLink#>',
            '<#EditBillingAddressUrl#>');

        $billingLink = BASEURL . 'edit_billinginfo/editCustomerInfo/' . md5($aRecurring->order_row_id);
        $values = array($customerInfo->first_name . ' ' . $customerInfo->last_name,
            $aRecurring->recurring_cycle,
            $merchantBasicInfo->currency_symbol . $aRecurring->recurring_price,
            $product->product_description,
            $billingLink,
            $billingLink
        );

        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email = $this->parseMerchantContactProfile($aRecurring->merchant_row_id, $email);

        $this->sendMail($merchantBasicInfo->from_address, $email->from_name, $customerInfo->customer_email, $email->email_subject, $email->email_body, '', '', '', $mailCode);
    }

    function sendRecurringCartExpireNotification($aRecurring, $merchantBasicInfo) {
        $this->db->select('product_description');
        $this->db->from('tbl_product');
        $this->db->where('product_row_id', $aRecurring->product_row_id);
        $recordSet = $this->db->get();
        $product = $recordSet->row();

        $email = $this->getMail($aRecurring->merchant_row_id, 1040);

        $tags = array('<#CustomerName#>',
            '<#RecurringCycle#>',
            '<#RecurringPrice#>',
            '<#RecurringProductDes#>',
            '<#EditBillingInformationLink#>',
            '<#EditBillingAddressUrl#>',
            '<#NextSubscriptionDate#>');

        $billingLink = BASEURL . 'edit_billinginfo/editCustomerInfo/' . md5($aRecurring->order_row_id);
        $values = array(
            $aRecurring->first_name . ' ' . $aRecurring->last_name,
            $aRecurring->recurring_cycle,
            $merchantBasicInfo->currency_symbol . $aRecurring->recurring_price,
            $product->product_description,
            $billingLink,
            $billingLink,
            $aRecurring->next_subscription_date);

        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email = $this->parseMerchantContactProfile($aRecurring->merchant_row_id, $email);

        $this->sendMail($merchantBasicInfo->from_address, $email->from_name, $aRecurring->customer_email, $email->email_subject, $email->email_body, '', '', '', 1040);
    }

    function sendTellFriendMail($merchantRowId, $data) {
        $email = $this->getMail($merchantRowId, 1041);
        $tags = array('<#FriendName#>',
            '<#AffiliateProgramLink#>'
        );
        $values = array($data['first_name'],
            $data['link'],
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email = $this->parseAffiliateInformation($data['affiliate_row_id'], $email);
        $this->sendMail($data['affiliate_email'], $data['affiliate_name'], $data['email'], $email->email_subject, $email->email_body, '', $this->config->item('adminNotifyEmail'), $this->config->item('adminNotifyName'), 1041);
    }

    function sendOrderPlaceCustomerEmail($merchantRowId, $fromEmail, $fromName, $to, $data, $emailCode) {
        $email = $this->getMail($merchantRowId, $emailCode);

        $tags = array('<#CustomerName#>',
            '<#OrderInvoice#>',
            '<#OrderId#>'
        );
        $values = array($data['customer_info']->first_name . ' ' . $data['customer_info']->last_name,
            $this->getOrderInvoice($data),
            $data['orderDetails']->order_id
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $this->sendMail($fromEmail, $fromName, $to, $email->email_subject, $email->email_body, '', '', '', $emailCode);
    }

    function sendCreditCartUpdateLink($merchantRowId, $fromEmail, $fromName, $to, $data, $emailCode) {
        $email = $this->getMail($merchantRowId, $emailCode);
        $tags = array('<#CustomerName#>',
            '<#OrderInvoice#>',
            '<#OrderId#>',
            '<#EditBillingInformationLink#>',
            '<#EditBillingAddressUrl#>'
        );

        $billingLink = BASEURL . 'edit_billinginfo/editCustomerInfo/' . md5($data['orderDetails']->order_row_id);
        $values = array($data['customer_info']->first_name . ' ' . $data['customer_info']->last_name,
            $this->getOrderInvoice($data),
            $data['orderDetails']->order_id,
            $billingLink,
            $billingLink
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $this->sendMail($fromEmail, $fromName, $to, $email->email_subject, $email->email_body, '', '', '', $emailCode);
    }

    function sendRegularOrderEmailToFulfillmentUser($order_row_id, $merchantRowId, $data) {
        $email = $this->getMail($merchantRowId, 1038);
        $freshEmail = $email;

        $sql = "SELECT smu.username as username,
              mer.company_name as merchant_company_name,
              smu.email as email,
              fc.fulfillment_company,
              smu.name as name,
              mer.merchant_row_id as merchant_row_id,
              mer.email_address as email_address,
              CONCAT(mer.first_name,' ',mer.last_name) as merchant_name,
              ord.order_id as order_id
              FROM tbl_order_shipping_info osi
              INNER JOIN tbl_shipping_module_user AS smu ON (smu.company_id=osi.assigned_company_id) AND smu.active_status = 1
              INNER JOIN tbl_fulfillment_company AS fc ON(fc.company_id = smu.company_id)
              INNER JOIN tbl_merchant AS mer ON (mer.merchant_row_id=osi.merchant_row_id)
              INNER JOIN tbl_order AS ord ON (ord.order_row_id=osi.order_row_id)
              WHERE osi.order_row_id=" . $this->db->escape($order_row_id) . " AND osi.merchant_row_id=" . $this->db->escape($merchantRowId);

        $query = $this->db->query($sql);
        $result = $query->result_array();
        $emailBody = $email->email_body;

        foreach ($result as $item) {
            $email = $freshEmail;


            $pairs = array('<#FulfillmentCompanyName#>' => $item['fulfillment_company'],
                '<#UserName#>' => $item['username'],
                '<#OrderInvoice#>' => $this->getOrderInvoice($data),
                '<#OrderId#>' => $item['order_id']);


            $email->email_body = strtr($emailBody, $pairs);
            $email = $this->parseMerchantContactProfile($merchantRowId, $email);
            $this->sendMail($item['email_address'], $item['merchant_name'], $item['email'], $email->email_subject, $email->email_body, '', '', '', 1038);
        }
    }

    function sendRecurringOrderEmailToFulfillmentUser($order_row_id, $merchantRowId) {
        $email = $this->getMail($merchantRowId, 1038);
        $freshEmail = $email;

        $sql = "SELECT smu.username as username,
              mer.company_name as merchant_company_name,
              smu.email as email,
              smu.name as name,
              mer.merchant_row_id as merchant_row_id,
              mer.email_address as email_address,
              CONCAT(mer.first_name,' ',mer.last_name) as merchant_name,
              ord.order_id as order_id
              FROM tbl_recurring_order_shipping_info rosi
              INNER JOIN tbl_shipping_module_user AS smu ON (smu.company_id=rosi.assigned_company_id)
              INNER JOIN tbl_fulfillment_company AS fc ON (fc.company_id = smu.company_id)
              INNER JOIN tbl_merchant AS mer ON (mer.merchant_row_id=rosi.merchant_row_id)
              INNER JOIN tbl_order AS ord ON (ord.order_row_id=rosi.order_row_id)
              WHERE rosi.order_row_id=" . $this->db->escape($order_row_id) . " AND rosi.merchant_row_id=" . $this->db->escape($merchantRowId) . " GROUP BY rosi.order_row_id";

        $query = $this->db->query($sql);
        $result = $query->result_array();

        foreach ($result as $item) {
            $email = $freshEmail;

            $pairs = array('<#FulfillmentCompanyName#>' => $item['fulfillment_company'],
                '<#UserName#>' => $item['username'],
                '<#OrderId#>' => $item['order_id']);

            $email->email_body = strtr($email->email_body, $pairs);
            $email = $this->parseMerchantContactProfile($merchantRowId, $email);
            $this->sendMail($item['email_address'], $item['merchant_name'], $item['email'], $email->email_subject, $email->email_body, '', '', '', 1038);
        }
    }

    function sendRefundCustomerEmail($merchantRowId, $fromEmail, $fromName, $to, $data, $emailCode) {
        $email = $this->getMail($merchantRowId, $emailCode);

        $tags = array('<#CustomerName#>',
            '<#RefundSummary#>',
            '<#OrderId#>'
        );
        $values = array($data['customer_info']->first_name . ' ' . $data['customer_info']->last_name,
            $this->getRefundSummary($data['refundOrder']),
            $data['orderDetails']->order_id
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $this->sendMail($fromEmail, $fromName, $to, $email->email_subject, $email->email_body, '', '', '', $emailCode);
    }

    function sendShippedConfirmationToCustomers($ord_ship_id, $merchant_row_id, $data) {
        $email = $this->getMail($merchant_row_id, 1042);

        //Get all data
        $sql = "SELECT osi.shipper,
                     osi.track_id,
                     mer.public_email,
                     CONCAT(mer.first_name,' ',mer.last_name) as from_name,
                     cart.currency_symbol
               FROM tbl_order_shipping_info osi
               INNER JOIN tbl_merchant mer ON mer.merchant_row_id=osi.merchant_row_id
               INNER JOIN tbl_cart_basic cart ON cart.merchant_row_id=mer.merchant_row_id
               WHERE osi.ord_ship_id=" . $this->db->escape($ord_ship_id) . " AND osi.merchant_row_id=" . $this->db->escape($merchant_row_id);
        $query = $this->db->query($sql);
        $result = $query->row_array();
        $data['currency_symbol'] = $result['currency_symbol'];

        $tags = array('<#CustomerName#>',
            '<#OrderId#>',
            '<#OrderInvoice#>',
            '<#Shipper#>',
            '<#TrackingId#>'
        );
        $values = array($data['customer_info']->first_name . ' ' . $data['customer_info']->last_name,
            $data['orderDetails']->order_id,
            $this->getOrderInvoice($data),
            $result['shipper'],
            $result['track_id']
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email->email_subject = str_replace($tags, $values, $email->email_subject);
        $email = $this->parseMerchantContactProfile($merchant_row_id, $email);

        $from = $result['public_email'];
        $from_name = $result['from_name'];
        $to = $data['customer_info']->customer_email;


        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1042);
    }

    function sendShippedConfirmationToCustomersRecurring($ord_ship_id, $merchant_row_id, $data) {
        $email = $this->getMail($merchant_row_id, 1042);

        //Get all data
        $sql = "SELECT rosi.shipper,
                     rosi.track_id,
                     mer.public_email,
                     CONCAT(mer.first_name,' ',mer.last_name) as from_name,
                     cart.currency_symbol
               FROM tbl_recurring_order_shipping_info rosi
               INNER JOIN tbl_merchant mer ON mer.merchant_row_id=rosi.merchant_row_id
               INNER JOIN tbl_cart_basic cart ON cart.merchant_row_id=mer.merchant_row_id
               WHERE rosi.ord_ship_id=" . $this->db->escape($ord_ship_id) . " AND rosi.merchant_row_id=" . $this->db->escape($merchant_row_id);
        $query = $this->db->query($sql);
        $result = $query->row_array();
        $data['currency_symbol'] = $result['currency_symbol'];

        $tags = array('<#CustomerName#>',
            '<#OrderId#>',
            '<#OrderInvoice#>',
            '<#Shipper#>',
            '<#TrackingId#>'
        );
        $values = array($data['customer_info']->first_name . ' ' . $data['customer_info']->last_name,
            $data['orderDetails']->order_id,
            $this->getOrderInvoice($data),
            $result['shipper'],
            $result['track_id']
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email->email_subject = str_replace($tags, $values, $email->email_subject);
        $email = $this->parseMerchantContactProfile($merchant_row_id, $email);

        $from = $result['public_email'];
        $from_name = $result['from_name'];
        $to = $data['customer_info']->customer_email;

        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1042);
    }

    function sendFulfillmentUserCredentials($merchant_row_id, $data) {
        $email = $this->getMail($merchant_row_id, 1043);

        //Get Merchant Info
        $sql = "SELECT mer.public_email as merchant_email,
                     CONCAT(mer.first_name,' ',mer.last_name) as merchant_full_name
              FROM tbl_merchant mer
              WHERE mer.merchant_row_id=" . $this->db->escape($merchant_row_id);
        $query = $this->db->query($sql);
        $merchant_info = $query->row();

        $tags = array('<#UserFullName#>',
            '<#LoginUrl#>',
            '<#UserName#>',
            '<#Password#>'
        );
        $values = array($data['name'],
            base_url() . "shipLogin/" . md5($merchant_row_id) . ".html",
            trim($data['username']),
            trim($data['password'])
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email->email_subject = str_replace($tags, $values, $email->email_subject);
        $email = $this->parseMerchantContactProfile($merchant_row_id, $email);

        $from = $merchant_info->merchant_email;
        $from_name = $merchant_info->merchant_full_name;
        $to = $data['email'];

        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1043);
        return 1;
    }

    function sendLowInventoryAlert($merchantRowId, $fromEmail, $fromName, $to, $data, $emailCode) {
        $email = $this->getAdminMail($emailCode);

        $email->email_body = str_replace('<#ProductName#>', $data['product_name'], $email->email_body);

        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $this->sendMail($fromEmail, $fromName, $to, $email->email_subject, $email->email_body, '', '', '', $emailCode);
    }

    function sendOrderPendingMail($merchantRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1001);

        $tags = array('<#CustomerName#>',
            '<#OrderInvoice#>',
            '<#OrderId#>'
        );
        $values = array($data['customer_info']->first_name . ' ' . $data['customer_info']->last_name,
            $this->getOrderInvoice($data),
            $data['orderDetails']->order_id
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1001);
    }

    function sendAffiliateConfirmationEmail($merchantRowId, $affiliateRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1012);

        $tags = array('<#TotalFirstLevelCommission#>',
            '<#SalesValue#>'
        );
        $values = array($data['total_first_level_commission'],
            $_SESSION['currency_symbol'] . ' ' . $data['sales_value']
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email = $this->parseAffiliateManagerProfile($merchantRowId, $email);
        $email = $this->parseAffiliateInformation($affiliateRowId, $email);
        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1012);
    }

    function sendAffiliateCommissionConfirmationEmail($merchantRowId, $affiliateRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1013);
        $sql = "SELECT currency_symbol FROM tbl_cart_basic WHERE merchant_row_id=" . $this->db->escape($merchantRowId);
        $query = $this->db->query($sql);
        $currency = $query->row();
        $paidTotalCommission = $currency->currency_symbol . ' ' . $data['paidTotalcommission'];

        $tags = array('<#PayOutDate#>',
            '<#PayOutAmount#>'
        );
        $values = array(getCurrentDateTimeForDB(),
            $paidTotalCommission
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email = $this->parseAffiliateManagerProfile($merchantRowId, $email);
        $email = $this->parseAffiliateInformation($affiliateRowId, $email);

        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1013);
    }

    function sendAffiliateWelcomeLetterEmail($merchantRowId, $affiliateRowId, $from, $to) {
        $email = $this->getMail($merchantRowId, 1014);
        $email = $this->parseAffiliateManagerProfile($merchantRowId, $email);
        $email = $this->parseAffiliateInformation($affiliateRowId, $email);
        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1014);
    }

    function sendAffiliateApplicationReceivedEmail($merchantRowId, $affiliateRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1015);
        $email = $this->parseAffiliateManagerProfile($merchantRowId, $email);
        $email = $this->parseAffiliateInformation($affiliateRowId, $email);
        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1015);
    }

    function sendDeclineAffiliateApplicationLetterEmail($merchantRowId, $affiliateRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1016);
        $email = $this->parseAffiliateManagerProfile($merchantRowId, $email);
        $email = $this->parseAffiliateInformation($affiliateRowId, $email);

        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1016);
    }

    function sendOptInEmailToCustomer($merchantRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1034);

        $tags = array(
            '<#VerificationLink#>'
        );
        $values = array(
            $data['emailVerificationLink']
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $email = $this->parseAffiliateManagerProfile($merchantRowId, $email);

        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1034);
    }

    function sendDigitalDownloadLinkEmail($merchantRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1009);

        $tags = array('<#ProductDescription#>',
            '<#DownloadPageLink#>',
            '<#CustomerName#>'
        );
        $values = array($data['product_description'],
            $data['download_page_link'],
            $data['customer_name']
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email = $this->parseMerchantContactProfile($merchantRowId, $email);
        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1009);
    }

    function sendDigitalProductLicenseEmail($merchantRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1010);

        $tags = array('<#CustomerName#>',
            '<#ProductDescription#>',
            '<#LicenseKey#>',
            '<#OrderId#>'
        );
        $values = array($data['customer_name'],
            $data['product_description'],
            $data['licenseKey'],
            $data['order_id']
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email->email_subject = str_replace('<#ProductDescription#>', $data['product_description'], $email->email_subject);
        $email = $this->parseMerchantContactProfile($merchantRowId, $email);

        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1010);
    }

    function sendDigitalProductRunningOutEmail($merchantRowId, $from, $to, $data) {
        $email = $this->getMail($merchantRowId, 1011);

        $tags = array('<#CustomerName#>',
            '<#OrderId#>',
            '<#ProductDescription#>',
            '<#DownloadPageLink#>'
        );
        $values = array($data['customer_name'],
            $data['order_id'],
            $data['product_description'],
            $data['DownloadPageLink']
        );
        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email = $this->parseMerchantContactProfile($merchantRowId, $email);

        $subjectTags = array('<#ProductId#>', '<#ProductDescription#>');
        $subjectValues = array($data['product_id'], $data['product_description']);

        $email->email_subject = str_replace($subjectTags, $subjectValues, $email->email_subject);
        $this->sendMail($from, $email->from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1011);
    }

    function notifyMerchantOnOrderSuccess($data) {
        $this->getAdminContactProfile();
        $emailCode = 1023;
        $email = $this->getAdminMail($emailCode);

        $tags = array('<#MerchantFirstName#>',
            '<#MerchantLastName#>',
            '<#MerchantCompanyUrl#>',
            '<#MerchantCompanyName#>',
            '<#ProjectName#>',
            '<#OrderInvoice#>',
            '<#AdminFooterText#>'
        );
        $values = array($data['first_name'],
            $data['last_name'],
            $data['merchant_company_url'],
            $data['merchant_company'],
            $this->config->item('project_name'),
            $this->getOrderInvoice($data),
            $this->adminContactProfile['footer_text']
        );

        $email->email_subject = str_replace($tags, $values, $email->email_subject);
        $email->email_body = str_replace($tags, $values, $email->email_body);
        $this->sendMail($this->adminContactProfile['email_address'], $this->adminContactProfile['full_name'], $data['to_address'], $email->email_subject, $email->email_body, $data['cc_address'], $this->adminContactProfile['email_address'], $this->adminContactProfile['full_name'], $emailCode);
    }

    function copyMailsForNewMerchant($merchantRowId) {
        if ($merchantRowId) {
            $mailCodes = '1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1024, 1034, 1035, 1036, 1037, 1038, 1040, 1041, 1042, 1043, 1045, 1047, 1048';

            $sql = 'INSERT INTO tbl_email_manager (merchant_row_id,
                                                    purpose,
                                                    email_subject,
                                                    email_body,
                                                    modified_on,
                                                    customer_email_number)
                    SELECT ' . $merchantRowId . ',
                            purpose,
                            email_subject,
                            email_body,
                            \'' . getCurrentDateTimeForDB() . '\',
                            email_code
                    FROM tbl_admin_email_manager
                    WHERE email_code IN (' . $mailCodes . ')';
            $this->db->query($sql);
        } else {
            log_email('Mail copy for new merchants is not working properly. Merchant row ID is missing.');
        }
    }

    function sendDeclineNotificationToMerchant($aRecurring, $merchantBasicInfo, $merchantDetails, $customerInfo, $attemptNo = 0) {
        $this->db->select('product_description');
        $this->db->from('tbl_product');
        $this->db->where('product_row_id', $aRecurring->product_row_id);
        $recordSet = $this->db->get();
        $product = $recordSet->row();

        $this->getAdminContactProfile();
        $emailCode = 1046;
        $email = $this->getAdminMail($emailCode);

        $tags = array('<#CustomerName#>',
            '<#RecurringCycle#>',
            '<#RecurringPrice#>',
            '<#RecurringProductDes#>',
            '<#MerchantFirstName#>',
            '<#MerchantLastName#>',
            '<#AdminFooterText#>'
        );

        $values = array($customerInfo->first_name . ' ' . $customerInfo->last_name,
            $aRecurring->recurring_cycle,
            $merchantBasicInfo->currency_symbol . $aRecurring->recurring_price,
            $product->product_description,
            $merchantDetails->first_name,
            $merchantDetails->last_name,
            $this->adminContactProfile['footer_text']
        );

        $email->email_subject = str_replace($tags, $values, $email->email_subject);
        $email->email_body = str_replace($tags, $values, $email->email_body);
        //print_r ($email->email_body);
        //log_general($email->email_body);
        $this->sendMail($this->adminContactProfile['email_address'], $this->adminContactProfile['full_name'], $merchantBasicInfo->primary_destination, $email->email_subject, $email->email_body, $merchantBasicInfo->secondary_destination, $this->adminContactProfile['email_address'], $this->adminContactProfile['full_name'], $emailCode);
    }

    function sendCpSignupLink($merchant_row_id, $data) {
        $email = $this->getMail($merchant_row_id, 1047);

        //Get Merchant Info
        $sql = "SELECT mer.public_email as merchant_email,
                     mer.first_name,
                     mer.last_name,
                     mer.merchant_contact_phone,
                     mer.company_name,
                     mer.website_url,
                     mer.email_from_name
              FROM tbl_merchant mer
              WHERE mer.merchant_row_id=" . $this->db->escape($merchant_row_id);

        $query = $this->db->query($sql);
        $merchant_info = $query->row();

        $tags = array('<#CustomerName#>',
            '<#Username#>',
            '<#Password#>',
            '<#CustomerPortalLoginLink#>',
            '<#MerchantFirstName#>',
            '<#MerchantLastName#>',
            '<#MerchantPublicEmail#>',
            '<#MerchantContactPhone#>',
            '<#MerchantCompanyName#>',
            '<#MerchantWebsiteUrl#>'
        );


        $values = array(trim($data['first_name']),
            trim($data['user_name']),
            trim($data['new_password']),
            trim($data['retrievalLink']),
            $merchant_info->first_name,
            $merchant_info->last_name,
            $merchant_info->merchant_email,
            $merchant_info->merchant_contact_phone,
            $merchant_info->company_name,
            $merchant_info->website_url
        );

        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email->email_subject = str_replace($tags, $values, $email->email_subject);
        $email = $this->parseMerchantContactProfile($merchant_row_id, $email);
        $from = $merchant_info->merchant_email;
        $from_name = $merchant_info->email_from_name;
        $to = trim($data['user_name']);

        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1047);
        return 1;
    }

    function sendCpRetrievePasswordLink($merchant_row_id, $data) {
        $email = $this->getMail($merchant_row_id, 1048);


        //Get Merchant Info
        $sql = "SELECT mer.public_email as merchant_email,
                     mer.first_name,
                     mer.last_name,
                     mer.merchant_contact_phone,
                     mer.company_name,
                     mer.website_url,
                     mer.email_from_name
              FROM tbl_merchant mer
              WHERE mer.merchant_row_id=" . $this->db->escape($merchant_row_id);

        $query = $this->db->query($sql);
        $merchant_info = $query->row();

        $tags = array('<#CustomerFirstName#>',
            '<#UserName#>',
            '<#Password#>',
            '<#NewPasswordActivationLink#>',
            '<#MerchantFirstName#>',
            '<#MerchantLastName#>',
            '<#MerchantEmailFromName#>',
            '<#MerchantContactPhone#>',
            '<#MerchantCompanyName#>',
            '<#MerchantWebsiteUrl#>'
        );



        $values = array(trim($data['first_name']),
            trim($data['user_name']),
            trim($data['new_password']),
            trim($data['retrievalLink']),
            $merchant_info->first_name,
            $merchant_info->last_name,
            $merchant_info->merchant_email,
            $merchant_info->merchant_contact_phone,
            $merchant_info->company_name,
            $merchant_info->website_url
        );

        $email->email_body = str_replace($tags, $values, $email->email_body);
        $email->email_subject = str_replace($tags, $values, $email->email_subject);
        $email = $this->parseMerchantContactProfile($merchant_row_id, $email);
        $from = $merchant_info->merchant_email;
        $from_name = $merchant_info->email_from_name;
        $to = trim($data['user_name']);

        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1048);
        return 1;
    }

    function sendRecurringCommissionMailToAffiliate($mailData) {
        $email = $this->getMail($mailData['merchant_row_id'], 1024);

        $tags = array();
        $values = array();

        $tags[] = '<#OrderID#>';
        $values[] = !empty($mailData['order_row_id']) ? $mailData['order_row_id'] : '';

        $tags[] = '<#SalesValue#>';
        $values[] = !empty($mailData['sales_value']) ? $mailData['currency_symbol'] . $mailData['sales_value'] : '';

        $tags[] = '<#FirstLevelCommission#>';
        $values[] = !empty($mailData['total_first_level_commission']) ? $mailData['currency_symbol'] . $mailData['total_first_level_commission'] : '';

        $tags[] = '<#MerchantFooterText#>';
        $values[] = !empty($mailData['footer_text']) ? $mailData['footer_text'] : '';

        $tags[] = '<#AdminFooterText#>';
        $values[] = !empty($mailData['contact_profile_admin']['footer_text']) ? $mailData['contact_profile_admin']['footer_text'] : '';

        $tags[] = '<#MerchantCompanyUrl#>';
        $values[] = !empty($mailData['from_companyorurl']) ? $mailData['from_companyorurl'] : '';

        $email->email_body = str_replace($tags, $values, $email->email_body);

        $email->email_subject = str_replace('<#MerchantCompanyUrl#>', $mailData['from_companyorurl'], $email->email_subject);

        $email = $this->parseAffiliateManagerProfile($mailData['merchant_row_id'], $email);
        $email = $this->parseAffiliateInformation($mailData['affiliate_row_id'], $email);

        $this->sendMail($mailData['from_address'], $mailData['full_name'], $mailData['to_address'], $email->email_subject, $email->email_body, '', '', '', 1024);
    }

    function sendCoachLoginUrl($merchant_row_id, $mailData) {
        //Get Merchant Info
        $sql = "SELECT mer.public_email as merchant_email,
                     mer.first_name,
                     mer.last_name,
                     mer.merchant_contact_phone,
                     mer.company_name,
                     mer.website_url,
                     mer.email_from_name
              FROM tbl_merchant mer
              WHERE mer.merchant_row_id=" . $this->db->escape($merchant_row_id);

        $query = $this->db->query($sql);
        $merchant_info = $query->row();

        $email->email_body = '<div>Dear ' . $mailData ['first_name'] . '<div>' .
                '<div>Your account has been successfully created.</div>
                                     <div><br />Here are your access details:</div>' .
                '<div>User Name: ' . $mailData['user_name'] . '</div>' .
                '<div>Password: ' . $mailData ['password'] . '</div>' .
                '<div><br />The login Url is provided below: </div>' .
                '<div>' . $mailData ['loginUrl'] . '</div>' .
                '<div><br />For further assistance, please contact us at the following: </div>' .
                '<div>' . $merchant_info->merchant_email . '</div>' .
                '<div>' . $merchant_info->merchant_contact_phone . '</div>' .
                '<div><br />Regards </div>' .
                '<div>' . $merchant_info->first_name . ' ' . $merchant_info->last_name . '</div>' .
                '<div>' . $merchant_info->company_name . '</div>' .
                '<div>' . $merchant_info->website_url . '</div>' .
                $email->email_subject = 'New Account Information';

        $from = $merchant_info->merchant_email;
        $from_name = $merchant_info->email_from_name;
        $to = trim($mailData['user_name']);

        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1049);
        return 1;
    }

    function sendCoachRetrievePasswordLink($merchant_row_id, $mailData) {
        //Get Merchant Info
        $sql = "SELECT mer.public_email as merchant_email,
                     mer.first_name,
                     mer.last_name,
                     mer.merchant_contact_phone,
                     mer.company_name,
                     mer.website_url,
                     mer.email_from_name
              FROM tbl_merchant mer
              WHERE mer.merchant_row_id=" . $this->db->escape($merchant_row_id);

        $query = $this->db->query($sql);
        $merchant_info = $query->row();

        $email->email_body = '<div>Dear ' . $mailData ['first_name'] . '<div>' .
                '<div><br />Your New Login Credential is given below:</div>' .
                '<div>User Name: ' . $mailData['user_name'] . '</div>' .
                '<div>New Password: ' . $mailData ['password'] . '</div>' .
                '<div><br />You must click the link below to activate your new password: </div>' .
                '<div>' . $mailData ['retrievalLink'] . '</div>' .
                '<div><br />For further assistance, please contact us at the following: </div>' .
                '<div>' . $merchant_info->merchant_email . '</div>' .
                '<div>' . $merchant_info->merchant_contact_phone . '</div>' .
                '<div><br />Regards </div>' .
                '<div>' . $merchant_info->first_name . ' ' . $merchant_info->last_name . '</div>' .
                '<div>' . $merchant_info->company_name . '</div>' .
                '<div>' . $merchant_info->website_url . '</div>' .
                $email->email_subject = 'Password Retrieval';

        $from = $merchant_info->merchant_email;
        $from_name = $merchant_info->email_from_name;
        $to = trim($mailData['user_name']);
        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1050);
        return 1;
    }

    function sendCpSignupLinkAddedFromCRM($merchant_row_id, $mailData) {
        //Get Merchant Info
        $sql = "SELECT mer.public_email as merchant_email,
                     mer.first_name,
                     mer.last_name,
                     mer.merchant_contact_phone,
                     mer.company_name,
                     mer.website_url,
                     mer.email_from_name
              FROM tbl_merchant mer
              WHERE mer.merchant_row_id=" . $this->db->escape($merchant_row_id);

        $query = $this->db->query($sql);
        $merchant_info = $query->row();

        $email->email_body = '<div>Dear ' . $mailData ['first_name'] . '<div>' .
                '<div> Your new Customer Portal account has been successfully created.<br />Your Login Credential is given below:</div>' .
                '<div>User Name: ' . $mailData['user_name'] . '</div>' .
                '<div>Password: ' . $mailData ['customer_password'] . '</div>' .
                '<div><br />Login Url: ' . $mailData ['loginUrl'] . '</div>' .
                '<div><br />For further assistance, please contact us at the following: </div>' .
                '<div>' . $merchant_info->merchant_email . '</div>' .
                '<div>' . $merchant_info->merchant_contact_phone . '</div>' .
                '<div><br />Regards </div>' .
                '<div>' . $merchant_info->first_name . ' ' . $merchant_info->last_name . '</div>' .
                '<div>' . $merchant_info->company_name . '</div>' .
                $email->email_subject = 'New Account Information';
        $from = $merchant_info->merchant_email;
        $from_name = $merchant_info->email_from_name;
        $to = trim($mailData['user_name']);
        $this->sendMail($from, $from_name, $to, $email->email_subject, $email->email_body, '', '', '', 1051);
        return 1;
    }

    function sendBookingInfo($data, $cusotmerToCoach = false, $newBooking = true) {
        $this->db->select('customer_email, first_name, last_name');
        $customerQ = $this->db->get_where('tbl_customer', array(
            'customer_id' => $data['customerId']
                ));
        if ($customerQ->num_rows() == 0) {
            return false;
        }
        $customerInfo = $customerQ->row_array();
        
        $sql = "SELECT m.first_name, m.last_name, m.email_address, m.public_email, m.time_zone,"
                . " p.contact_phone, p.contact_email,"
                . " s.description "
                . " FROM tbl_merchant m JOIN tbl_coach_service s ON m.merchant_row_id = s.coach_row_id"
                . " LEFT JOIN tbl_coach_profile p ON m.merchant_row_id = p.coach_row_id"
                . " WHERE m.merchant_row_id = " . $data['coachId'] . " AND s.service_row_id = " . $data['serviceId'];
        
        $coachQ = $this->db->query($sql);
        
        if ($coachQ->num_rows() == 0) {
            return false;
        }
        $coachInfo = $coachQ->row_array();

        $startTimeH = intval($data['booking_start_time']);
        $startTimeM = round(($data['booking_start_time'] - $startTimeH), 2) * 100;
        $endTimeH = intval($data['booking_end_time']);
        $endTimeM = round(($data['booking_end_time'] - $endTimeH), 2) * 100;

        $startWithFormating = date('h:i A', mktime($startTimeH, $startTimeM, 0, $data['month'], $data['date'], $data['year']));
        $endWithFormating = date('h:i A', mktime($endTimeH, $endTimeM, 0, $data['month'], $data['date'], $data['year']));

        //email content
        $coachName = $coachInfo['first_name'] . ' ' . $coachInfo['last_name'];
        $customerName = $customerInfo['first_name'] . $customerInfo['last_name'];
        
        $coachEmail = $coachInfo['contact_email'] == '' || $coachInfo['contact_email'] == ' ' ? $coachInfo['email_address'] : $coachInfo['contact_email'];

        $emailBody = '<p>Dear ' . $customerInfo['first_name'] . ' ' . $customerInfo['last_name'] . '</p>';
        $emailBody .= '<p>This message is to confirm your Appointment / Event as follows: </p> <p>With: ' . $coachName . '</p> <p>Description: ' . $coachInfo['description'] . '</p> <p>Date: ' . date('d M Y', mktime(0, 0, 0, $data['month'], $data['date'], $data['year'])) . '</p>';
        $emailBody .= '<p>Start Time: ' . $startWithFormating . '</p><p>End Time: ' . $endWithFormating . '</p>';
        $emailBody .= '<p>Time Zone: ' . $coachInfo['time_zone'] . '</p>' ;
        $emailBody .= '<p>If you need to change or cancel for any reason, please make sure you contact ' . $coachName . ' directly to see if other accommodations can be made. Please note, it may not always be possible to cancel or reschedule.</p>';        
        $emailBody .= '<p>Regards</p>';
        $emailBody .= '<p>' . $coachName . '</p>';
        $emailBody .= '<p>' . $coachInfo['contact_phone'] . '</p>';
        $emailBody .= '<p>' . $coachEmail . '</p>';        
        if ($cusotmerToCoach) {
            $emailBody = '<p>Dear ' . $coachName . '</p>';
            $emailBody .= '<p>This is a notification that ' . $customerName . ' has booked ' . $data['service_name'] . ' on ' . date('d M y', mktime(0, 0, 0, $data['month'], $data['date'], $data['year']));
            $emailBody .= ' from ' . $startWithFormating . ' to ' . $endWithFormating;
            $emailBody .= '<br /><br /></p><p>Regards,</p><br />';
            $emailBody .= '<p>' . $coachInfo['company_name'] . '</p>';            
        }
        //sending email       
       $fromAddress = $cusotmerToCoach ? $customerInfo['customer_email'] : $coachEmail;
       $fromName = $cusotmerToCoach ? $customerName : $coachName;
       $toAddress = $cusotmerToCoach ? $coachEmail : $customerInfo['customer_email'];
       $typeBooking = $newBooking ? 'New' : 'Updated';
       $subject = 'Your ' . $typeBooking  . ' Booking Details';             
       //Stop this email on merchant request
       $this->sendMail($fromAddress, $fromName, $toAddress, $subject, $emailBody);
    }

    /**
     * @description send notification email when booking is canceled
     * @author sifat
     * @param array $toData
     * $toData[0]['first_name']
     * $toData[0]['last_name']
     * $toData[0]['email']
     * @param array $fromData
     * $fromData['email']
     * $fromData['first_name']
     * $fromData['last_name']
     * @param array $bookingInfo
     * $bookingData['service_name']
     * $bookingData['booking_start_time']
     * $bookingData['booking_end_time']
     * @return void
     */
    function sendDeleteNotification($toData, $fromData, $bookingInfo) {
        $subject = 'Booking Cancel Notification';
        foreach ($toData as $toDatum) {
            $emailBody = '<div>Dear ' . $toDatum['first_name'] . '</div><br />';
            $emailBody .= '<div>Your booking on ' . $bookingInfo['service_name'];
            if (isset($bookingInfo['year']) && isset($bookingInfo['month']) && isset($bookingInfo['date'])) {
                $emailBody .= ' at ' . date('dS M Y', mktime(0, 0, 0, $bookingInfo['month'], $bookingInfo['date'], $bookingInfo['year']));
            }
            if (isset($bookingInfo['booking_start_time']) && isset($bookingInfo['booking_end_time'])) {
                $emailBody .= ' From ' . $bookingInfo['booking_start_time'] . ' to ' . $bookingInfo['booking_end_time'] . '';
            }

            $emailBody .= ' with ' . $fromData['first_name'] . ' ' . $fromData['last_name'];
            $emailBody .= ' has been cancelled.<br />';  
            $emailBody .= ' Regrads<br />' . $fromData['first_name'] . ' ' .  $fromData['last_name'] . '</div>';  
                      
            $this->sendMail($fromData['email'], $fromData['first_name'] . ' ' . $fromData['last_name'], $toDatum['email'], $subject, $emailBody);
        }
    }

}