<?php

/*

Paczkomaty 24/7 osCommerce Module
Revision 1.10.

Copyright (c) 2009 InPost Sp. z o.o.

*/

class paczkomaty extends base {

  var $code, $title, $description, $enabled, $num_zones;

  function paczkomaty() {

  	global $order, $total_weight;

    $this->code = 'paczkomaty';
    $this->title = MODULE_SHIPPING_PACZKOMATY_TEXT_TITLE;
    $this->description = MODULE_SHIPPING_PACZKOMATY_TEXT_DESCRIPTION;
    $this->sort_order = MODULE_SHIPPING_PACZKOMATY_SORT_ORDER;
    $this->icon = DIR_WS_IMAGES.'/paczkomaty/pieczatka.gif'; 
    $this->tax_class = MODULE_SHIPPING_PACZKOMATY_TAX_CLASS;
    $this->enabled = ((MODULE_SHIPPING_PACZKOMATY_STATUS == 'True') ? true : false);
    $this->num_zones = 1;
								 	
  }

  function pobierz_paczkomaty($postcode) {

    $inpost_api_url = constant('MODULE_SHIPPING_PACZKOMATY_API_URL');
  
    if ($machinesContents = @file_get_contents("$inpost_api_url/?do=findnearestmachines_csv&postcode=$postcode")) {
      if ($machinesContents=='Error') return 0;  
      if(MODULE_SHIPPING_PACZKOMATY_KODOWANIE != 'UTF-8') {
      	$machinesContents = iconv("UTF-8", MODULE_SHIPPING_PACZKOMATY_KODOWANIE, $machinesContents);
      }          
      $machinesArray = explode("\n", $machinesContents);
      if (count($machinesArray)) {      
        foreach ($machinesArray as $machine) {
          $machine = explode(";",$machine);
          $data[] = $machine;
        }            
        return $data;   
      } 
    }
    
    return 0;
  
  }

  function znajdz_klienta($email) {
    
    if (MODULE_SHIPPING_PACZKOMATY_TEST == 'Tak') {
    	$email = 'test@testowy.pl';    	
    }
    
    $inpost_api_url = constant('MODULE_SHIPPING_PACZKOMATY_API_URL');
  
    if ($machinesContents = @file_get_contents("$inpost_api_url/?do=findcustomer_csv&email=$email")) {
      if ($machinesContents=='Error') return 0;      
      $machine = split(";",iconv("UTF-8", MODULE_SHIPPING_PACZKOMATY_KODOWANIE, $machinesContents));
      return $machine;
    }
  
    return 0;
  
  }
       
  function quote($method = '') {
  
	  global $order, $total_weight, $shipping_weight, $shipping_num_boxes, $customer_id, $sendto;

    $dest_country = $order->delivery['country']['iso_code_2'];
    $dest_zone = 0;
    $error = false;
	  	
    if ($order->delivery['country']['iso_code_2'] == 'PL')  {  // tylko na terenie Polski
	  	
      for ($i=1; $i<=$this->num_zones; $i++) {
        $countries_table = constant('MODULE_SHIPPING_PACZKOMATY_COUNTRIES_' . $i);
        $country_zones = split("[,]", $countries_table);
        if (in_array($dest_country, $country_zones)) {
          $dest_zone = $i;
          break;
        }
      }
 		
      if ($dest_zone == 0) {
        $this->quotes['error'] = MODULE_SHIPPING_ZONES_INVALID_ZONE;
        return $this->quotes;
      } 
      
      $shipping_method = MODULE_SHIPPING_PACZKOMATY_TEXT_WAY . ' : ' . $shipping_weight . ' ' . MODULE_SHIPPING_PACZKOMATY_TEXT_UNITS . ' ' . MODULE_SHIPPING_PACZKOMATY_DELIVERY_TIMES; 
      $shipping_cost = constant('MODULE_SHIPPING_PACZKOMATY_COST_' . $dest_zone)* $shipping_num_boxes;
        
    }
      
    if (zen_not_null($this->icon)) $this->quotes['icon'] = zen_image($this->icon, $this->title);
      
    if ($dest_zone == 0) {   // poza rejonem
      $this->quotes['error'] = MODULE_SHIPPING_ZONES_INVALID_ZONE;
      return $this->quotes;
    } 
        
   	if ($total_weight >12) { // nie pokazuj dla przesylek > 12kg
      $this->quotes['error'] = MODULE_SHIPPING_PACZKOMATY_UNDEFINED_RATE;
	    return $this->quotes;
    }	      

    $this->quotes = array('id' => $this->code,
                          'module' => MODULE_SHIPPING_PACZKOMATY_TEXT_TITLE);        
                                                     
    $paczkomaty=$this->pobierz_paczkomaty($order->delivery['postcode']);
            
    if (!$paczkomaty) {  
			$this->quotes['error'] = MODULE_SHIPPING_PACZKOMATY_TEXT_MACHINES_NOT_FOUND;
			return $this->quotes;
    }	
            
    $paczkomat_domyslny=$this->znajdz_klienta($order->customer['email_address']);
      
    if (!$paczkomat_domyslny) {  	
			$this->quotes['error'] = MODULE_SHIPPING_PACZKOMATY_TEXT_USER_NOT_FOUND;
			return $this->quotes;
    }	
      
	if (zen_not_null($method)) {
		if ($paczkomat_domyslny[0]==$method) {
		    $this->quotes['methods'][]=array('id' => $paczkomat_domyslny[0],
		                                     'title' => MODULE_SHIPPING_PACZKOMATY_TEXT_011.$paczkomat_domyslny[0].', '.$paczkomat_domyslny[1],
		                                     'cost' => $shipping_cost);
		}
		elseif (count($paczkomaty)) {
	      foreach ($paczkomaty as $paczkomat) {
			if ($paczkomat[0]==$method) {
		        $this->quotes['methods'][]=array('id' => $paczkomat[0],
	    	                                      'title' => MODULE_SHIPPING_PACZKOMATY_TEXT_013.' '.$paczkomat[0].', '.$paczkomat[1].', ('.$paczkomat[3].MODULE_SHIPPING_PACZKOMATY_TEXT_012.$order->delivery['postcode'].")",
	        	                                  'cost' => $shipping_cost);
			}
	      }                        
		}
	}
	else {
	    $this->quotes['methods'][]=array('id' => $paczkomat_domyslny[0],
	                                     'title' => MODULE_SHIPPING_PACZKOMATY_TEXT_011.$paczkomat_domyslny[0].', '.$paczkomat_domyslny[1],
	                                     'cost' => $shipping_cost);
	    if (count($paczkomaty)) {  
	      foreach ($paczkomaty as $paczkomat) {
	        $this->quotes['methods'][]=array('id' => $paczkomat[0],
	                                          'title' => MODULE_SHIPPING_PACZKOMATY_TEXT_013.' '.$paczkomat[0].', '.$paczkomat[1].', ('.$paczkomat[3].MODULE_SHIPPING_PACZKOMATY_TEXT_012.$order->delivery['postcode'].")",
	                                          'cost' => $shipping_cost);
	      }                        
	    }                             
	}

    if (zen_not_null($this->icon)) $this->quotes['icon'] = zen_image($this->icon, $this->title);
                                                     
    return $this->quotes;
      
	}
	

  function check() {
  
  	global $db;
  
    if (!isset($this->_check)) {
      $check  = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_PACZKOMATY_STATUS'");
      $this->_check = $check->RecordCount();
    }
    
    return $this->_check;
    
  }

  function install() {
  
  	global $db;
  	
  	$sort=880;
  
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('".MODULE_SHIPPING_PACZKOMATY_TEXT_001."', 'MODULE_SHIPPING_PACZKOMATY_STATUS', 'True', '".MODULE_SHIPPING_PACZKOMATY_TEXT_002."', '6', '".strval(++$sort)."', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('".MODULE_SHIPPING_PACZKOMATY_TEXT_003."', 'MODULE_SHIPPING_PACZKOMATY_API_URL', 'https://api.paczkomaty.pl', '".MODULE_SHIPPING_PACZKOMATY_TEXT_004."', '6', '".strval(++$sort)."', now())");	  
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('".MODULE_SHIPPING_PACZKOMATY_TEXT_005."', 'MODULE_SHIPPING_PACZKOMATY_SORT_ORDER', '1', '".MODULE_SHIPPING_PACZKOMATY_TEXT_006."', '6', '".strval(++$sort)."', now())");
    for ($i = 1; $i <= $this->num_zones; $i++) {
      $default_countries = '';
      if ($i == 1) {
        $default_countries = 'PL';
      }
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('".MODULE_SHIPPING_PACZKOMATY_TEXT_007."', 'MODULE_SHIPPING_PACZKOMATY_COUNTRIES_" . $i ."', '" . $default_countries . "', '".MODULE_SHIPPING_PACZKOMATY_TEXT_008."', '6', '".strval(++$sort)."', now())");
      $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('".MODULE_SHIPPING_PACZKOMATY_TEXT_009."', 'MODULE_SHIPPING_PACZKOMATY_COST_" . $i ."', '6.99', '".MODULE_SHIPPING_PACZKOMATY_TEXT_010."', '6', '".strval(++$sort)."', now())");   
    }
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('".MODULE_SHIPPING_PACZKOMATY_TEXT_014."', 'MODULE_SHIPPING_PACZKOMATY_TEST', 'Nie', '".MODULE_SHIPPING_PACZKOMATY_TEXT_015."', '6', '".strval(++$sort)."', 'zen_cfg_select_option(array(\'Tak\', \'Nie\'), ', now())");
    
  }

  function remove() {
  
  	global $db;

    $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key in ('" . implode("', '", $this->keys()) . "')");
    
  }

  function keys() {
  
    $keys = array('MODULE_SHIPPING_PACZKOMATY_STATUS', 'MODULE_SHIPPING_PACZKOMATY_API_URL', 'MODULE_SHIPPING_PACZKOMATY_SORT_ORDER', 'MODULE_SHIPPING_PACZKOMATY_TEST');
    for ($i=1; $i<=$this->num_zones; $i++) {
      $keys[] = 'MODULE_SHIPPING_PACZKOMATY_COUNTRIES_' . $i;
      $keys[] = 'MODULE_SHIPPING_PACZKOMATY_COST_' . $i;
    }
    
    return $keys;
    
  }

}

