<?php
/**
* 2007-2016 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Academic Free License (AFL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/afl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
*  @author    PrestaShop SA <contact@prestashop.com>
*  @copyright 2007-2016 PrestaShop SA
*  @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
*  International Registered Trademark & Property of PrestaShop SA
*/

if (!defined('_PS_VERSION_')) {
    exit;
}

 include_once _PS_MODULE_DIR_.'ostatusnotice/classes/OrderStatusNotice.php';

class OstatusNotice extends Module
{
    public function __construct()
    {
          $this->name = 'ostatusnotice';
          $this->tab = 'administration';
          $this->version = '1.0.0';
          $this->author = 'InnovativesLabs';
          $this->need_instance = 0;
          $this->secure_key = Tools::encrypt($this->name);
          $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
          $this->bootstrap = true;

          parent::__construct();

          $this->displayName = $this->l('Order Status Notice');
          $this->description = $this->l('Send an email to the client when order status changed.');

          $this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
    }
   
   
       public function install() {
        $sql = array();
	
        $sql[] = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'order_status_notice` (
                  `id_order_status_notice` int(10) unsigned NOT NULL AUTO_INCREMENT,
                  `id_product` INT( 11 ) UNSIGNED NOT NULL,
                  `url` TEXT NOT NULL,
                  PRIMARY KEY (`id_order_status_notice`),
                  UNIQUE  `ORDER_STATUS_NOTICE_UNIQ` (  `id_product` )
                ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8';
                                
        if (!parent::install() OR 
            !$this->registerHook('displayAdminProductsExtra') OR
            !$this->registerHook('actionProductUpdate') OR
            !$this->registerHook('displayFooterProduct') OR		
			!$this->registerHook('actionPaymentConfirmation') OR            		
            !$this->runSql($sql)
        ) {
            return FALSE;
        }
        
        return TRUE;
    }
    
    public function uninstall() {
        $sql = array();
	
        $sql[] = 'DROP TABLE IF EXISTS `'._DB_PREFIX_.'order_status_notice`';
        if (!parent::uninstall() OR
            !$this->runSql($sql) 
        ) {
            return FALSE;
        }

        return TRUE;
    }
    
    public function runSql($sql) {
        foreach ($sql as $s) {
			if (!Db::getInstance()->Execute($s)){
				return FALSE;
			}
        }
        
        return TRUE;
    }
	
	
	public function getContent()
    {
	$output=null;
	
	
	if(Tools::isSubmit('submitUpdateTemplate')){
	
	Configuration::updateValue('NKA_message_title', Tools::getValue('message_title'));
	Configuration::updateValue('NKA_message_subject', Tools::getValue('message_subject'));	
	
	}
	
	$output.=$this->getTemplate().'<br/>'.$this->innovativesLabs();
	
	 return $output;
	
	}
    
    public function hookDisplayAdminProductsExtra($params) {
        $id_product = Tools::getValue('id_product');
        $sampleObj = OrderStatusNotice::loadByIdProduct($id_product);
		$token=Tools::getAdminTokenLite('AdminProducts');
        if(!empty($sampleObj) && isset($sampleObj->id)){
            $this->context->smarty->assign(array(
                'url' => $sampleObj->url,
				'token'=>$token
            ));
        }
        
        return $this->display(__FILE__, 'sample_admin.tpl');
    }
    
    public function hookActionProductUpdate($params) {
        $id_product = Tools::getValue('id_product');
        $sampleObj = OrderStatusNotice::loadByIdProduct($id_product);
        $sampleObj->url = Tools::getValue('status_notice');
        $sampleObj->id_product = $id_product;
        
        if(!empty($sampleObj) && isset($sampleObj->id)){
            $sampleObj->update();
        } else {
            $sampleObj->add();
        }
    }
    
    public function hookDisplayFooterProduct($params) {
        $id_product = Tools::getValue('id_product');
        $sampleObj = OrderStatusNotice::loadByIdProduct($id_product);
        if(!empty($sampleObj) && isset($sampleObj->id)){
            $this->context->smarty->assign(array(
                'url' => $sampleObj->url,
            ));
        }
        
        return $this->display(__FILE__, 'sample_front.tpl');
    }
	
	
	public function hookActionPaymentConfirmation($params) {
	 
	 //$id_order=(int)Tools::getValue('id_order');
	$id_order=(int)Tools::getValue('id_order');
	$order = new Order((int)$id_order);
	$history = new OrderHistory();
	$history->id_order = (int)$order->id;
	$history->changeIdOrderState(2, (int)$order->id);
	$history->addWithemail();
    //return $this->emailClient();
	
	}
	
	public function getTemplate(){
	
	$this->context->smarty->assign(array(
                'message_title' =>Configuration::get('NKA_message_title'),
				'message_subject' =>Configuration::get('NKA_message_subject')
            ));
	
	return $this->display(__FILE__, 'send_mail.tpl');
	
	}
	
	
	    public function emailClient()
    {
        $id_order=(int)Tools::getValue('id_order');
		$order=new Order($id_order);
		$id_customer=$order->id_customer;
		$customer=new Customer($id_customer);		
	    $lastname=$customer->lastname;	
	    $firstname=$customer->firstname;
		$email=$customer->email;
        //$email="kandiaga@yandex.ru";            
       
          $message_title = Configuration::get('NKA_message_title');
          $message_subject =Configuration::get('NKA_message_subject');

              
              $html=$this->orderProductList();
              $order_name = Order::getUniqReferenceOf($id_order);
              $date = date('d/m/y');
             
              

              return  Mail::Send(
                  $this->context->language->id,
                  'ostatusnotice_conf',
                  Mail::l($message_title, $this->context->language->id),
                  array('{html}' => $html,
                        '{order_name}' => $order_name,
                        '{date}' => $date, 
                        '{message_title}'=>$message_title, 		
                        '{message_subject}'=>$message_subject, 
                        '{first_name}'=>$firstname, 	
                        '{last_name}'=>$lastname, 							

             ),
                  pSQL($email),
                  null,
                  null,
                  null,
                  null,
                  null,
                  dirname(__FILE__).'/mails/',
                  false,
                  $this->context->shop->id
              );
        
    }
	
	public function orderProductList()
    {
	      $id_order=(int)Tools::getValue('id_order');
          $order= new Order($id_order);
          $products=$order->getProducts();
          $this->context->smarty->assign(
              array(
          'list' => $products          
            )
          );

          return $this->display(__FILE__, 'supplier_product_list.tpl');
    }
	
	
	public function innovativesLabs(){
  
  return $this->display(__FILE__, 'innovativeslabs.tpl');
  
  }


  
}
