<?php

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


class ModelIndex extends BaseModel
{   
    protected $modelCommon;
    protected $_libEmailSend;
    public function __construct() {   
        $this->modelCommon = new ModelCommon();    
        $this->_libEmailSend = new LibEmailsend();
        parent::__construct();
    }
 /*
  * Function to check the login details
  */
 public function ckeckLogin($table,$field,$where='')
 {
        if($where!='')
        $where = ' WHERE '.$where;
    	$query = "SELECT ".$field."
    	            FROM ".$this->tablePrefix .$table.$where ;
//        die;
        $res = $this->execute($query);
    	return $this->fetchOne($res);
 }

 /*
  * Function to fetch the site traffic
  */

 public function getSiteTraffic($table,$field,$where='')
 {
     if($where!='')
     $where= ' WHERE '.$where;
     $query = "SELECT ".$field."
                 FROM ".$this->tablePrefix .$table.$where ;
     $res = $this->execute($query);
     return $this->fetchAll($res);
 }

 public function getListFields($table,$field,$order='',$where='')
 {
     if($order!='')
        $order= ''.$order;
     if($where!='')
        $where= ' WHERE '.$where;
     $query = "SELECT ".$field."
                 FROM ".$this->tablePrefix .$table.' '.$where.' '.$order ;
//     echo $query;
     $res = $this->execute($query);
     return $this->fetchAll($res);
 }
 public function getTopList($table,$field,$order='',$where='')
 {
     if($order!='')
     $order= ''.$order;
     $query = "SELECT ".$field."
                 FROM ".$this->tablePrefix .$table.$where.$order ; 
     
     $res = $this->execute($query);
     return $this->fetchAll($res);
 }

 public function getTopCategory($table,$field,$order='',$where='')
 {
     if($order!='')
     $order= ''.$order;
     $query = "SELECT ".$field."
                 FROM ".$this->tablePrefix .$table.$where.$order ;
     //echo $query;exit;
     $res = $this->execute($query);
     return $this->fetchAll($res);
 }
 
 public function sendApprovemail($ID)
 {
      $Product = $this->modelCommon->selectRecord("product","*","nBusId ='".$ID."'");
      
      $title = $Product->Title;
      $userId = $Product->nUserId;
       
            $user = $this->modelCommon->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","nUserId ='".$userId."'");
            
            $userEmail = $user->vEmail;
        
            $username = $user->vFirstName.' '.$user->vLastName;
     
      $SSsettings = $this->modelCommon->selectResult('settings','*', 'settingfield = \'adminEmail\'');

        foreach($SSsettings as $field ) {
            $SSsettings[$field->settingfield]= $field->value;
        }
        
        
          $msgAdmin = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
        //$messageAdmin .= $chkdUser['mailcontentadmin'];
        $msgAdmin .= "Dear $username,<br><br>
        Your Post <b>$title</b> in {SITE_NAME}  is approved by admin<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'), $msgBodyAdmin); // Replace the Site Url
        //$msgBodyAdmin = str_replace("{USER_EMAIL}", $email, $msgBodyAdmin); // Replace the User Email

        //echo $messageAdmin;exit;
        $subject_admin = 'Your post has been approved';
        $adminNotif = array();
        $adminNotif['from']=$SSsettings['adminEmail'];
        $adminNotif['subject']= $subject_admin;
        $adminNotif['message']= $msgBodyAdmin;
        $adminNotif['to']     = $userEmail;
     $this->_libEmailSend->email_senderNow($adminNotif);
     
     
 }
 
  public function senduserapprovalmail($ID)
 {
     
      $userId = $ID;
       
            $user = $this->modelCommon->selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","nUserId ='".$userId."'");
            
            $userEmail = $user->vEmail;
        
            $username = $user->vFirstName.' '.$user->vLastName;
     
      $SSsettings = $this->modelCommon->selectResult('settings','*');

        foreach($SSsettings as $field ) {
            $SSsettings[$field->settingfield]= $field->value;
        }
        
        
          $msgAdmin = "<p><img src=".BASE_URL."/public/images/default/mainlogo_disp.png /></p>";
        //$messageAdmin .= $chkdUser['mailcontentadmin'];
        $msgAdmin .= "Dear $username,<br><br>
        Your Account  in {SITE_NAME}  has been activated  by admin<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'), $msgBodyAdmin); // Replace the Site Url
        //$msgBodyAdmin = str_replace("{USER_EMAIL}", $email, $msgBodyAdmin); // Replace the User Email

        //echo $messageAdmin;exit;
        $subject_admin = 'Account Activation';
        $adminNotif = array();
        $adminNotif['from']=$SSsettings['adminEmail'];
        $adminNotif['subject']= $subject_admin;
        $adminNotif['message']= $msgBodyAdmin;
        $adminNotif['to']     = $userEmail;
     $this->_libEmailSend->email_senderNow($adminNotif);
     
     
 }
 
  public function checkUser($email='', $userId='', $userApproval=''){
        $USERID = $userId;
        //$user = ModelCommon::selectRecord("users","nUserId,vLoginName,vEmail,vFirstName,vLastName,vStatus,nSocialUserId","vEmail ='".$email."'");
//        if(empty($email) && !empty($userId)) { // If User Id is present
//            $user = ModelCommon::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 = ModelCommon::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->modelCommon->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()."'
//                                 )";
//
//            ModelCommon::execute($query);

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

//            if(!empty($newUser)) { // Auto Registration
//                $newUserData = ModelCommon::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} As a member, 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. Once again, thanks for joining our community and enjoy your experience at {SITE_URL}. <br />Your current posting is pending for approval.<b><u><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 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'), $msgBodyAdmin); // Replace the Site Url
//                $msgBodyAdmin = str_replace("{USER_EMAIL}", $email, $msgBodyAdmin); // Replace the User Email
//                
//                $autoregister =1;
//            } // Auto Registration End
            
            //$userData = $newUserData;

        } else {
            // Existing User Data
            $userData = $user;
        }
        $data['user'] = $userData;       
        $data['mailcontentuser'] = $msgBody;
        $data['mailcontentadmin'] = $msgBodyAdmin;
        $data['autoregister'] = $autoregister;

        return  $data;
    } // 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


}
?>
