<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
// +----------------------------------------------------------------------+
// | Common database model class. It use for common functions             |
// | File name : postads.php                                               |
// | PHP version >= 5.2                                                   |
// | Created On 4 January 2012                                                   |
// +----------------------------------------------------------------------+
// | Author: Meena Suasn Joseph <meena.s@armiasystems.com>              |
// +----------------------------------------------------------------------+
// | Copyrights Armia Systems ? 2010                                      |
// | All rights reserved                                                  |
// +------------------------------------------------------


class ModelPostads extends BaseModel
{

    public function __construct()
    {
		parent::__construct();
        $this->_common = new ModelCommon();
        $this->_libEmailSend = new LibEmailsend();

    } // End Function


    public function convertVideo($file_name='',$source_directory='',$destination_directory='')
    {

	$return_array = array();
	$value_return = "";
	$file_name_split = explode('.',$file_name);
	$source = $source_directory.$file_name;
	//$destination = $destination_directory."flv/".$file_name_split[0].".flv";
        $destination = $destination_directory.$file_name_split[0].".flv";
	exec("ffmpeg -i $source -ar 22050 -ab 32 -f flv -s 600x329 $destination");
	//exec("ffmpeg -i $destination -an -ss 00:00:03 -an -r 1 -vframes 1 -y -s 106x106 $destination_directory/images/%d_$file_name_split[0].jpg");
	//exec("ffmpeg -i $destination -an -ss 00:00:03 -an -r 1 -vframes 1 -y -s 80x54 -f mjpeg $destination_directory/thumb/$file_name_split[0].jpg",$return_array,$value_return);
        //exec("ffmpeg -i $destination -an -ss 00:00:03 -an -r 1 -vframes 1 -y -s 80x54 -f mjpeg $videoThumbPath",$return_array,$value_return);
        exec("ffmpeg -i $destination -an -ss 00:00:03 -an -r 1 -vframes 1 -y -s 80x54 -f mjpeg $destination_directory.$file_name_split[0].jpg",$return_array,$value_return);
	//@unlink($source);

        return $value_return;
    } // End Function

    public function sendPostNotificationToAdmin($adminEmail)
    {
          //Admin Notification for new add

        $SSsettings = $this->_common->selectResult('settings','*');

        foreach($SSsettings as $field ) {
            $SSsettings[$field->settingfield]= $field->value;
        }


            if($SSsettings['userApproval']=='admin' || $SSsettings['userApproval']=='email')
           {
               $extramsg = " and is waiting for your approval";
           }else{
               $extramsg = "";
           }


        $msgAdmin = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
        //$messageAdmin .= $chkdUser['mailcontentadmin'];
        $msgAdmin .= "Dear Administrator,<br><br>
        New Ad has been posted in {SITE_NAME} $extramsg <br> 
        {SITE_NAME} | {SITE_URL}";
        $msgBodyAdmin = str_replace("{SITE_NAME}", SITE_NAME, $msgAdmin); // Replace the Site Name
        $msgBodyAdmin = str_replace("{SITE_URL}", ConfigUrl::base('default').'admin', $msgBodyAdmin); // Replace the Site Url
        //$msgBodyAdmin = str_replace("{USER_EMAIL}", $email, $msgBodyAdmin); // Replace the User Email

        //echo $messageAdmin;exit;
        $subject_admin = 'New Ad Posted';
        $adminNotif = array();
        $adminNotif['from']=$adminEmail;
        $adminNotif['subject']= $subject_admin;
        $adminNotif['message']= $msgBodyAdmin;
        $adminNotif['to']     = $adminEmail;
        $this->_libEmailSend->email_senderNow($adminNotif);

    } // End Function

    public function sendUserEmail($nUserid,$userApproval,$adminEmail)
    {
        $userData = $this->_common->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","nUserId ='".$nUserid."'");
          //Activation Key
            $email = $userData->vEmail;
            $emailSplit = explode("@", $email);
            $username = $emailSplit[0];
            //$password = 'EI'.date('Y');
            $password = $_SESSION['userdetail'];
            $activationKeyContent = $username.'##'.$nUserid;
            $activationKey = base64_encode($activationKeyContent);

              $SSsettings = $this->_common->selectResult('settings','*');

        foreach($SSsettings as $field ) {
            $SSsettings[$field->settingfield]= $field->value;
        }


            if($SSsettings['userApproval']=='admin')
           {
               $extramsg = "Once Admin approve your Account, ";
               $extramsg1 = "Your current posting is pending for approval.";

           }else{
               $extramsg = "";

               $extramsg1 = "";
           }

                // User Notification
                $mainContent = '<html>Dear {MEMBER_NAME},<br><br>
                            {MESSAGE_BODY}</html>';

                $msg = '<table class="maintext2" cellpadding="4" cellspacing="1" width="100%" border="0">
                                <tbody>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" class="maintext2" align="left">Welcome to {SITE_NAME}.<br/><br/> As a member, '.$extramsg.'you will have the capability to post ads on our site and the access to view ads already posted by members of {SITE_NAME}. Please do not hesitate to contact us at {SITE_EMAIL} with any questions, comments, or suggestions about our unique services. <br/>Once again, thanks for joining our community and enjoy your experience at {SITE_URL}. <br /><br/>'.$extramsg1.'<b><u><br /><br/>Your account details as follows :</u></b></td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td width="14%" align="left">User Name</td>
                                        <td width="86%">{LoginName}</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td align="left">Password</td>
                                        <td>{Password}</td>
                                    </tr>';

               if($userApproval=='email') {
                  $msg .= '<tr bgcolor="#ffffff">
                                <td colspan="2" align="left"><b><u>Click the following link to activate your account :</u></b></td> </tr> <tr bgcolor="#ffffff">
                                <td colspan="2" align="left">{activate_link}<br /></td>
                            </tr>';
               } // Email Activation
               $msg .='<tr><td>&nbsp;</td></tr>';
               $msg .= '<tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">Welcome Aboard!</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">Thank You,</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">{SITE_NAME} | {SITE_URL}<br /></td>
                                    </tr>
                                </tbody>
                            </table> ';

                $activate_link = ConfigUrl::base('default').'login/activation/'.$activationKey;

                $msgBody = str_replace("{MESSAGE_BODY}", $msg, $mainContent); // Replace the Message Body
                $msgBody = str_replace("{MEMBER_NAME}", $username, $msgBody); // Replace the Member Name
                $msgBody = str_replace("{SITE_NAME}", SITE_NAME, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{SITE_URL}", ConfigUrl::base('default'), $msgBody); // Replace the Site Url
                $msgBody = str_replace("{LoginName}", $username, $msgBody); // Replace the Login Name
                $msgBody = str_replace("{Password}", $password, $msgBody); // Replace the Login Password
                //
                if($userApproval=='email') {
                    $msgBody = str_replace("{activate_link}", $activate_link, $msgBody); // Replace the Activation Link
                }
                // Admin Notification
                $msgAdmin = 'Dear Administrator,<br><br>
                            New user has been registered with {SITE_NAME}<br>
                            User Email : {USER_EMAIL}<br><br>
                            {SITE_NAME} | {SITE_URL}';

                $msgBodyAdmin = str_replace("{SITE_NAME}", SITE_NAME, $msgAdmin); // Replace the Site Name
                $msgBodyAdmin = str_replace("{SITE_URL}", ConfigUrl::base('default').'/admin', $msgBodyAdmin); // Replace the Site Url
                $msgBodyAdmin = str_replace("{USER_EMAIL}", $email, $msgBodyAdmin); // Replace the User Email

                $data['user'] = $userData;
                $data['mailcontentuser'] = $msgBody;
                $data['mailcontentadmin'] = $msgBodyAdmin;
                $data['autoregister'] = $autoregister;

                $subject = SITE_NAME.'Thank You For Registering With Us!';
                $message = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
                $message .= $data['mailcontentuser'];
                $message = str_replace("{SITE_EMAIL}", $adminEmail, $message);
                $userNotif = array();
                $userNotif['from']    = $adminEmail;
                $userNotif['subject'] = $subject;
                $userNotif['message'] = $message;
                $userNotif['to']      = $email;
                $this->_libEmailSend->email_senderNow($userNotif);
                //mail('smitha.m@armiasystems.com','Test mail ', 'test mail body');

                //Admin Notification
                $messageAdmin = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
                $messageAdmin .= $data['mailcontentadmin'];
                //echo $messageAdmin;exit;
                $subject_admin = 'New User Registration';
                $adminNotif = array();
                $adminNotif['from']    = $adminEmail;
                $adminNotif['subject'] = $subject_admin;
                $adminNotif['message'] = $messageAdmin;
                $adminNotif['to']      = $adminEmail;
                $this->_libEmailSend->email_senderNow($adminNotif);
                $_SESSION['userdetail'] = '';

    } // End Function

    public function checkUser($email='', $userId='', $userApproval=''){
        $USERID = '';
        if(empty($email) && !empty($userId)) { // If User Id is present
            $user = $this->_common->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","nUserId ='".$userId."'");
            if(!empty($user)) {
                $USERID = $user->nUserId;
            }
        } else if(!empty($email) && empty($userId)) { // If Email is present
            $user = $this->_common->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","vEmail ='".$email."'");
            if(!empty($user)) {
                $USERID = $user->nUserId;
            }
        }

        $userData = array();
        $msgBody = $msgBodyAdmin = '';
        $autoregister = 0;
        $data = array();

        if(empty($USERID)) {
            // Create Default User with Default Data
            $emailSplit = explode("@", $email);
            $username = $emailSplit[0];
            $password = 'EI'.date('Y');
            $arrUser = array();
            $arrUser['vLoginName'] = $username;
            $arrUser['vPassword'] = md5($password);
            $arrUser['vFirstName'] = $username;
            $arrUser['vEmail'] = $email;
            $arrUser['dDateReg'] = 'NOW()';
            $arrUser['vAlertStatus'] = 'Y';
            $arrUser['vNLStatus'] = 'N';
            $arrUser['vStatus'] = ($userApproval=='automatic') ? '1' : '0'; // User Approval Status - automatic , email , admin

            /*
             $userApproval=='email';
             */

            $newUser = $this->_common->addFields("users",$arrUser);

            $query="INSERT INTO `users`
                                 (`username`,`password`,`email`,`fname`,`lname`,`reggedOn`)
                                 VALUES
                                 (
                                 '".$arrUser['vLoginName']."',
                                 '".$arrUser['vPassword']."',
                                 '".$arrUser['vEmail']."',
                                 '".$arrUser['vFirstName']."',
                                 '".$arrUser['vLastName']."',
                                 '".time()."'
                                 )";

            $this->_common->execute($query);

            //Activation Key
            $activationKeyContent = $username.'##'.$newUser;
            $activationKey = base64_encode($activationKeyContent);

            $SSsettings = $this->_common->selectResult('settings','*');

        foreach($SSsettings as $field ) {
            $SSsettings[$field->settingfield]= $field->value;
        }


            if($SSsettings['userApproval']=='admin')
           {
               $extramsg = "Once Admin approve your Account, ";
           }else{
               $extramsg = "";
           }



            if(!empty($newUser)) { // Auto Registration
                $newUserData = $this->_common->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","nUserId ='".$newUser."'");

                // User Notification
                $mainContent = '<html>Dear {MEMBER_NAME},<br><br>
                            {MESSAGE_BODY}</html>';

                $msg = '<table class="maintext2" cellpadding="4" cellspacing="1" width="100%" border="0">
                                <tbody>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" class="maintext2" align="left">Welcome to {SITE_NAME}.<br/><br/> As a member, '.$extramsg.'you will have the capability to post ads on our site and the access to view ads already posted by members of {SITE_NAME}. Please do not hesitate to contact us at {SITE_EMAIL} with any questions, comments, or suggestions about our unique services. <br/>Once again, thanks for joining our community and enjoy your experience at {SITE_URL}. <br /><br/><b><u><br /><br/>Your account details as follows :</u></b></td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td width="14%" align="left">User Name</td>
                                        <td width="86%">{LoginName}</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td align="left">Password</td>
                                        <td>{Password}</td>
                                    </tr>';

               if($userApproval=='email') {
                  $msg .= '<tr bgcolor="#ffffff">
                                <td colspan="2" align="left"><b><u>Click the following link to activate your account :</u></b></td> </tr> <tr bgcolor="#ffffff">
                                <td colspan="2" align="left">{activate_link}<br /></td>
                            </tr>';
               } // Email Activation
               $msg .='<tr><td>&nbsp;</td></tr>';
               $msg .= '<tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">Welcome Aboard!</td>
                                    </tr>                                    
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">Thank You,</td>
                                    </tr>
                                    <tr bgcolor="#ffffff">
                                        <td colspan="2" align="left">{SITE_NAME} | {SITE_URL}<br /></td>
                                    </tr>
                                </tbody>
                            </table> ';

                $activate_link = ConfigUrl::base('default').'login/activation/'.$activationKey;

                $msgBody = str_replace("{MESSAGE_BODY}", $msg, $mainContent); // Replace the Message Body
                $msgBody = str_replace("{MEMBER_NAME}", $username, $msgBody); // Replace the Member Name
                $msgBody = str_replace("{SITE_NAME}", SITE_NAME, $msgBody); // Replace the Site Name
                $msgBody = str_replace("{SITE_URL}", ConfigUrl::base('default').'/', $msgBody); // Replace the Site Url
                $msgBody = str_replace("{LoginName}", $username, $msgBody); // Replace the Login Name
                $msgBody = str_replace("{Password}", $password, $msgBody); // Replace the Login Password
                //
                if($userApproval=='email') {
                    $msgBody = str_replace("{activate_link}", $activate_link, $msgBody); // Replace the Activation Link
                }
                // Admin Notification
                $msgAdmin = 'Dear Administrator,<br><br>
                            New user has been registered with {SITE_NAME}<br>
                            User Email : {USER_EMAIL}<br><br>
                            {SITE_NAME} | {SITE_URL}';

                $msgBodyAdmin = str_replace("{SITE_NAME}", SITE_NAME, $msgAdmin); // Replace the Site Name
                $msgBodyAdmin = str_replace("{SITE_URL}", ConfigUrl::base('default').'/admin', $msgBodyAdmin); // Replace the Site Url
                $msgBodyAdmin = str_replace("{USER_EMAIL}", $email, $msgBodyAdmin); // Replace the User Email

            } // Auto Registration End

            $userData = $newUserData;
            $autoregister =1;

        } else {
            // Existing User Data
            $userData = $user;
        }
        $data['user'] = $userData;
        $_SESSION['userdetail'] = $password;
        $data['mailcontentuser'] = $msgBody;
        $data['mailcontentadmin'] = $msgBodyAdmin;
        $data['autoregister'] = $autoregister;
//echo $msgBody;exit;
       //echo"<pre>";print_r($data);echo"</pre>";
        return  $data;
    } // End Function

} // End Class
?>