<?php
class ControllerModuleNotifyWhenArrives extends Controller {

    public function index() {
        if ($this->config->get('notify_when_arrives_status')) {
            
            $this->language->load('module/notify_when_arrives');

            $this->load->model('catalog/product');
      
            $this->data['heading_title'] = $this->language->get('heading_title');

            $this->data['show_as_module'] = $this->config->get('notify_when_arrives_show_mode');
            
            $this->data['text_description'] = $this->language->get('text_description');
            
            $this->data['button_register'] = $this->language->get('button_register');
               
            $store_name =  $this->config->get('config_name');

            $products = $this->model_catalog_product->getProducts();

            $requests = $this->loadData();
            
            file_put_contents('product', print_r($products,1));
    
            foreach ($products as $product_id => $product) {
                
                if (isset($requests[$product_id])){
                    
                    $prod_info  = &$requests[$product_id];
                    
                    if (($prod_info['requested'] > $prod_info['notified']) && (int)$product['quantity'] > 0){

                        $this->warnThatArrives($store_name,$product,$prod_info);

                    }
                
                }
            }
            
            if (isset($this->request->get['product_id'])){
                if (isset($products[$this->request->get['product_id']]['quantity'])){
                    
                    $qtd = $products[$this->request->get['product_id']]['quantity'];
                
                }else{
                    
                     $qtd =1; 
                }
            }else{
                $qtd =1; 
            }
            if ((int)$qtd > 0){
                
                  $this->data['out_stock'] = false;
            }else{
                  $this->data['out_stock'] = true;
            }
            
            $this->saveData($requests);

            if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/notify_when_arrives.tpl')) {

                $this->template = $this->config->get('config_template') . '/template/module/notify_when_arrives.tpl';
            } else {

                $this->template = 'default/template/module/notify_when_arrives.tpl';
            }

            $this->render();

        }
    }
    public function register() {
        
        $this->language->load('module/notify_when_arrives');

        if (isset($this->request->post['notify_email']) && isset($this->request->post['notify_product_id'])){
            
            $email = $this->request->post['notify_email'];
            $product_id = $this->request->post['notify_product_id'];
            $key = null;
            
            if (preg_match('/^[A-Za-z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}$/', $email)){

                $requests = $this->loadData();
                
                $key = substr(md5($email), 0,8);
  
                if (isset($requests[$product_id])){
                
                    if (!isset($requests[$product_id]['mails'][$key])){
                    
                       $requests[$product_id]['mails'][$key] = $email;
                       $requests[$product_id]['requested']++;
                   
                    }
                    
                }else{
                    
                    $requests[$product_id] = 
                    array('requested'=>1,
                          'notified' =>0,
                          'mails'    => array($key => $email)
                        );
          

                }
                $json =array('sucess'=>true,'msg'=>$this->language->get('text_success'));
                
                $this->saveData($requests);

                
            }else{
                
                $json = array('sucess'=>false,'msg'=>$this->language->get('text_error_mail'));
            }

        }else{
            
            $json =  array('sucess'=>false,'msg'=>$this->language->get('text_error_data')) ;
        }
        
         $this->response->setOutput(json_encode($json));
    }

   
    private function saveData($data) {
        
        $group = 'nwa_cfg';
        
        $data = array($group =>json_encode($data));
        
            $this->db->query("DELETE FROM " . DB_PREFIX . "setting WHERE `group` = '" . $this->db->escape($group) . "'");

            foreach ($data as $key => $value) {
                    $this->db->query("INSERT INTO " . DB_PREFIX . "setting SET `group` = '" . $this->db->escape($group) . "', `key` = '" . $this->db->escape($key) . "', `value` = '" . $this->db->escape($value) . "'");
            }
    }
    
    private function loadData() {
        
          $group = 'nwa_cfg';
          
            $data = array(); 

            $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "setting WHERE `group` = '" . $this->db->escape($group) . "'");

            foreach ($query->rows as $result) {
                    $data[$result['key']] = $result['value'];
            }
            
            if (isset($data[$group])){
            return json_decode($data[$group],1);
            
            }else{
                
                return array();
            }
    }

    private function warnThatArrives($store,$product,&$req_data) {
        
        $this->language->load('module/notify_when_arrives');

        $id =  $product['product_id'];
        
        $name = $product['name'];
        
        $mails = &$req_data['mails'];
        $notified = &$req_data['notified'];
        
        $link = $this->url->link('product/product',"product_id=$id");
        
        $subject  = str_replace(array('{store_name}','{product_name}','{product_link}'), array($store,$name,$link),$this->language->get('mail_subject'));
        


        $message = str_replace(array('{store_name}','{product_name}','{product_link}'), array($store,$name,$link),$this->language->get('mail_message'));

            foreach ($mails as $email_id => $email) {
            
                $this->sendEmail($email,$subject, $message);

                unset($mails[$email_id]);
                $notified++;
                     
            }
        
        $admin_address = $this->config->get('config_email');
        $admin_subject = str_replace(array('{store_name}','{product_name}','{product_link}'), array($store,$name,$link), $this->language->get('mail_admin_subject'));
        $admin_message = str_replace(array('{store_name}','{product_name}','{product_link}'), array($store,$name,$link), $this->language->get('mail_admin_message'));
        
        $this->sendEmail($admin_address,$admin_subject, $admin_message);
        
    }
    
    private function sendEmail($address,$subject,$message) {


        
        if (!isset($this->notify_mail)){
        
            $this->notify_mail = new Mail(); 
            $this->notify_mail->protocol = $this->config->get('config_mail_protocol');
            $this->notify_mail->parameter = $this->config->get('config_mail_parameter');
            $this->notify_mail->hostname = $this->config->get('config_smtp_host');
            $this->notify_mail->username = $this->config->get('config_smtp_username');
            $this->notify_mail->password = $this->config->get('config_smtp_password');
            $this->notify_mail->port = $this->config->get('config_smtp_port');
            $this->notify_mail->timeout = $this->config->get('config_smtp_timeout');
            $this->notify_mail->setFrom($this->config->get('config_email'));
            $this->notify_mail->setSender($this->config->get('config_name'));
            
        }
            $this->notify_mail->setTo($address);
            $this->notify_mail->setSubject($subject);
            $this->notify_mail->setHtml($message);
            #$this->notify_mail->setText(html_entity_decode($text, ENT_QUOTES, 'UTF-8'));
            #$this->notify_mail->setSender($order_info['store_name']);
            #$this->notify_mail->addAttachment(DIR_IMAGE . $this->config->get('config_logo'), md5(basename($this->config->get('config_logo'))));
           
            $this->notify_mail->send();
        
    }
    

}
?>