<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/ //
//$Id: AgreementsController.php, v 1.0 2012/12/07 20:52:11
//
class AgreementsController extends Controller {
    //ProductController index action
    public function indexAction() {
        $this->agreeAction();
    }
    public function agreeAction() {
        $languageIDs  = $this->ObjView->languageIDs;
        $businessID   = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $ObjSig       = new SignatureModel();
        $getSignature = $ObjSig->getSignature($businessID, 'business');
        if ($getSignature['agreeID'] > 0) {
            $this->ObjView->assign('agrement', $getSignature['agreement']);
        } else {
            $ObjBusiness = new BusinessModel();
            $resBusiness = $ObjBusiness->getBusinessDetails($businessID, $languageIDs);
            if ($resBusiness['businessAgreement'] != '')
                $this->ObjView->assign('agrement', html_entity_decode($resBusiness['businessAgreement']));
            else {
                $ObjContent = new ContentModel();
                $agrement   = $ObjContent->getContentDetails($languageIDs, '', '', 'business-agreement', 'publish', '', 'yes');
                $this->ObjView->assign('agrement', $agrement['content']);
            }
        }
        $this->ObjView->assign('signature', $getSignature['agreeSign']);
        $this->ObjView->assign('action', 'business');
        $this->ObjView->assign('id', $businessID);
        $this->ObjView->assign('name', $getSignature['agreePersonName']);
        $this->ObjView->assign('date', $getSignature['agreeDate']);
        $this->ObjView->display('BusinessAgreement.tpl');
    }
    public function signatureAction() {
        $ObjContent    = new ContentModel();
        $ObjBusiness   = new BusinessModel();
        $ObjSig        = new SignatureModel();
        $languageIDs   = $this->ObjView->languageIDs;
        $businessID    = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $businessName  = $this->ObjSession->getSession("BUSINESS_NAME");
        $businessKey   = strtolower(preg_replace(array(
            '/\&/',
            '/\|/',
            '/\//'
        ), "", $businessName));
        $businessKey   = strtolower(preg_replace("![^a-z0-9]+!i", "", $businessKey));
        $data          = $_POST['data'];
        $signImageName = $businessKey . "_" . $businessID . ".png";
        $_POST['name'] = $_POST['agreePersonName'];
        if ($_POST['imgType'] == 'file') {
            if ($_POST["sign_file_temp"] != '') {
                $ObjImageModel = new ImageModel();
                copy($_POST["sign_file_temp"], __CORE_PUBLIC_PATH . "/uploads/sign/" . $signImageName);
                $ObjImageModel->resizeImage(__CORE_PUBLIC_PATH . "/uploads/sign/" . $signImageName, '', 500, 100);
                $data = $signImageName;
            }
        } else {
            $imgdata = str_replace('image/png;base64,', '', $data);
            $data    = str_replace(' ', '+', $data);
            file_put_contents(__CORE_PUBLIC_PATH . "/uploads/sign/" . $signImageName, base64_decode(str_replace(' ', '+', $imgdata)));
            $data = $signImageName;
        }
        $savesig = $ObjSig->saveSignature($data, $languageIDs);
        if ($savesig) {
            $languageIDsCustom            = $languageIDs;
            $languageIDsCustom['Current'] = $languageIDs['Default'];
            $busDetails                   = $ObjBusiness->getBusinessBasic($businessID, $languageIDsCustom, 'basic');
            $ObjEmailtemplate             = new EmailtemplateModel();
            $siteName                     = $this->getSettingValue('site_settings', 'site_name');
            $siteUrl                      = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/") . '/';
            $href                         = $siteUrl . "manage/agreements/index/key/" . urlencode($busDetails['businessName']) . "/";
            $companyLogo                  = $this->getSettingValue('company_information', 'company_logo');
            //$this->ObjView->assign('companyLogo',$companyLogo);			
            // business agreement mail
            $emailbody                    = $ObjEmailtemplate->getEmailTemlateDetails($languageIDsCustom, '', 'business-agreement-recieved');
            $from                         = array(
                $emailbody['emailFromEmail'],
                $emailbody['emailFromName']
            );
            $subject                      = $emailbody['emailSubject'];
            //email body					
            $bodytag                      = str_replace('{$bname}', $busDetails['businessName'], $emailbody['emailHtml']);
            $bodytag                      = str_replace('{$companyLogo}', $companyLogo, $bodytag);
            $bodytag                      = str_replace('{$agreelink}', $href, $bodytag);
            $this->ObjView->assign('emailbody', $bodytag);
            $this->ObjView->assign('siteUrl', $siteUrl);
            $this->ObjView->assign('siteName', $siteName);
            $this->ObjView->assign('companyLogo', $companyLogo);
            $emailID                       = $this->getSettingValue('site_settings', 'global_notification_email');
            $body                          = $this->ObjCommon->fetch($this->ObjView, 'email_templates/Layout.tpl', $languageIDsCustom);
            $mailSettings                  = $this->getSettingValue('mail_settings');
            $mailSettings['smtp_password'] = $this->encryptDecrypt("decrypt", $mailSettings['smtp_password']);
            $ObjMail                       = new Mail($mailSettings);
            $ObjMail->IsHTML();
            $ObjMail->sendMail($from, $emailID, $subject, $body);
            if ($ObjMail->Send()) {
            }
            $this->setMessage("language.msgUpdatedSign", 3);
            $this->setRedirect("agreements/agree/");
        }
    }
    public function downloadAction() {
        $agreementFile = 'agreement.pdf';
        $businessID    = $this->ObjSession->getSession("BUSINESS_USER_ID");
        $content       = $this->generateMailContent($businessID, '');
        $stream        = isset($stream) ? $stream : '';
        return $this->createpdfAction($content, $agreementFile, $stream, true);
    }
    //CREATE PDF FUNCTION
    public function createpdfAction($content, $fileName = 'agreementFile.pdf', $stream = true, $attachment = false) {
        //echo $content;exit;
        $pdfLib = new Pdf();
        ob_end_clean();
        $pdf = new TCPDF('L', PDF_UNIT, 'A4', true, 'UTF-8', false);
        $pdf->SetCreator(PDF_CREATOR);
        $pdf->SetAuthor('');
        $pdf->SetTitle('');
        $pdf->SetSubject('');
        $pdf->SetKeywords('');
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        //set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, 10, PDF_MARGIN_RIGHT);
        $l = isset($l) ? $l : '';
        $pdf->setLanguageArray($l);
        // add a page
        $pdf->AddPage();
        $pdf->SetFont('dejavusans', '', 10);
        // output the HTML content			
        $pdf->WriteHTML('<style> h1{font:bold 15pt Arial, Helvetica, sans-serif;color: #333333;margin:0;}</style>' . $content);
        $pdf->Output($fileName, 'D');
        exit;
    }
    //END OF FUNCTION
    public function generateMailContent($businessID, $productID = 0) {
        //Create a compatible HTML document		
        $ObjContent    = new ContentModel();
        $ObjSig        = new SignatureModel();
        $ObjSettings   = new SettingsModel();
        $languageIDs   = $this->ObjView->languageIDs;
        $siteUrl       = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/") . '/';
        $getSignature  = $ObjSig->getSignature($businessID, 'business');
        $signImageName = $getSignature['agreeSign'];
        $bgImage       = str_replace("http://", "", $siteUrl) . __DIR_PUBLIC . '/uploads/sign/' . $signImageName;
        $content       = '<h1>' . $this->getLanguageValue("lblAgreement") . '</h1>';
        $content .= '<div id="testDiv">
                                       <p>{$agrement}</p>
                                       <p>' . $this->getLanguageValue("lblSignedBy") . ' <strong>' . $getSignature['agreePersonName'] . '</strong> 
                                           ' . $this->getLanguageValue("lblSignedOn") . ' <strong>' . $ObjSettings->getFormattedDate($getSignature['agreeDate'], 'yes') . '</strong></p>
                                       <div id="oldsignature"><img src="' . $bgImage . '" /></div>
                                    </div>';
        $content = str_replace('{$agrement}', $getSignature['agreement'], $content);
        return $content;
    }
}