<?php

/*

Paczkomaty 24/7 osCommerce Module
Revision 1.10.

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

*/

class paczkomaty {

  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 = 'http://media.paczkomaty.pl/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_klienta() {

    global $customer_id, $sendto;

    $account_query = tep_db_query("select
    customers_email_address from 
    " . TABLE_CUSTOMERS . " where customers_id = '" . (int)$customer_id . "'");
    $account = tep_db_fetch_array($account_query);
	  $klient['email']=$account['customers_email_address'];
	
    $account_query = tep_db_query("select
    entry_postcode from 
    " . TABLE_ADDRESS_BOOK . " where address_book_id = '" . (int)$sendto . "'");
    $account = tep_db_fetch_array($account_query);
    $klient['kod']=$account['entry_postcode'];
    
    return $klient;
   
  }
    
    
  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;            
      $machinesArray = split("\n",$machinesContents);
      if (count($machinesArray)) {      
        foreach ($machinesArray as $machine) {
          $machine = split(";",$machine);
          $data[] = $machine;
        }            
        return $data;   
      } 
    }
    
    return 0;
  
  }

  function znajdz_klienta($email) {
    
    $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(";",$machinesContents);
      return $machine;
    }
  
    return 0;
  
  }
       
  function quote($method = '') {
  
	  global $order, $total_weight, $shipping_weight, $shipping_num_boxes, $customer_id, $sendto;

    $klient =$this->pobierz_klienta();

    $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_PACZKOMATY_INVALID_ZONE;
        //return $this->quotes;
        return;
      } 
      
      $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 (tep_not_null($this->icon)) $this->quotes['icon'] = tep_image($this->icon, $this->title);
      
    if ($dest_zone == 0) {   // poza rejonem
      $this->quotes['error'] = MODULE_SHIPPING_PACZKOMATY_INVALID_ZONE;
      //return $this->quotes;
      return;
    } 
        
   	if ($total_weight >12) { // nie pokazuj dla przesylek > 12kg
      $this->quotes['error'] = MODULE_SHIPPING_PACZKOMATY_UNDEFINED_RATE;
	    //return $this->quotes;
        return;
    }	      

    $this->quotes = array('id' => $this->code,
                          'module' => MODULE_SHIPPING_PACZKOMATY_TEXT_TITLE);        
                                                     
    $paczkomaty=$this->pobierz_paczkomaty($klient['kod']);
            
    if (!$paczkomaty) {  
			$this->quotes['error'] = MODULE_SHIPPING_PACZKOMATY_TEXT_MACHINES_NOT_FOUND;
			//return $this->quotes;
            return;
    }	
            
    $paczkomat_domyslny=$this->znajdz_klienta($klient['email']);
      
    if (!$paczkomat_domyslny) {  	
			$this->quotes['error'] = MODULE_SHIPPING_PACZKOMATY_TEXT_USER_NOT_FOUND;
			return $this->quotes;
    }	
      
    $this->quotes['methods'][]=array('id' => $this->code.';1',
                                     'title' => 'Paczkomat domyślny '.$paczkomat_domyslny[0].', '.$paczkomat_domyslny[1],
                                     'cost' => $shipping_cost);
    
    if (count($paczkomaty)) {  
      $licznik = 2;
      foreach ($paczkomaty as $paczkomat) {
        $this->quotes['methods'][]=array('id' => $this->code.';'.$licznik,
                                          'title' => 'Paczkomat '.$paczkomat[0].', '.$paczkomat[1].', ('.$paczkomat[3].'km od '.$klient['kod'].")",
                                          'cost' => $shipping_cost);
        $licznik++;
      }                        
    }                             

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

  function check() {
  
    if (!isset($this->_check)) {
      $check_query = tep_db_query("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_SHIPPING_PACZKOMATY_STATUS'");
      $this->_check = tep_db_num_rows($check_query);
    }
    
    return $this->_check;
    
  }

  function install() {
  
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES ('Włącz wysyłkę do paczkomatów', 'MODULE_SHIPPING_PACZKOMATY_STATUS', 'True', 'Czy chcesz dodać opcję wysyłki do paczkomatów?', '6', '0', 'tep_cfg_select_option(array(\'True\', \'False\'), ', now())");
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Ściezka do api', 'MODULE_SHIPPING_PACZKOMATY_API_URL', 'http://api.paczkomaty.pl', 'Ścieżka do api paczkomaty', '6', '0', now())");	  
    tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sortowanie', 'MODULE_SHIPPING_PACZKOMATY_SORT_ORDER', '1', 'Sortowanie', '6', '0', now())");
    for ($i = 1; $i <= $this->num_zones; $i++) {
      $default_countries = '';
      if ($i == 1) {
        $default_countries = 'PL';
      }
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Dostępne kraje', 'MODULE_SHIPPING_PACZKOMATY_COUNTRIES_" . $i ."', '" . $default_countries . "', 'Wprowadź oznaczenie kraju dla którego usługa jest dostępna (Domyślnie: PL)', '6', '0', now())");
      tep_db_query("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Cena przesyłki', 'MODULE_SHIPPING_PACZKOMATY_COST_" . $i ."', '6.99', 'Domyślny koszt wysyłki', '6', '0', now())");   
    }
    
  }

  function remove() {
  
    tep_db_query("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');
    for ($i=1; $i<=$this->num_zones; $i++) {
      $keys[] = 'MODULE_SHIPPING_PACZKOMATY_COUNTRIES_' . $i;
      $keys[] = 'MODULE_SHIPPING_PACZKOMATY_COST_' . $i;
    }
    
    return $keys;
    
  }

}

?>