<?php
/*
  $Id: modules_shipping.php $
  TomatoCart Open Source Shopping Cart Solutions
  http://www.tomatocart.com

  Copyright (c) 2009 Wuxi Elootec Technology Co., Ltd

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License v2 (1991)
  as published by the Free Software Foundation.
*/
  include('includes/classes/shipping.php');
  include('includes/classes/china_shipping.php');

  class toC_Json_Modules_Shipping {

    function listShippingModules() {
      global $toC_Json, $osC_Language;
      
      $osC_DirectoryListing = new osC_DirectoryListing('includes/modules/shipping');
      $osC_DirectoryListing->setIncludeDirectories(false);
      $files = $osC_DirectoryListing->getFiles();
      
  	  $modules = array();
  	  foreach ( $files as $file ) {
  	    include('includes/modules/shipping/' . $file['name']);

  	    $class = substr($file['name'], 0, strrpos($file['name'], '.'));
        
  	    if ( class_exists('osC_Shipping_' . $class) ) {
  	      $osC_Language->injectDefinitions('modules/shipping/' . $class . '.xml');
  	
  	      $module = 'osC_Shipping_' . $class;
  	      $module = new $module();

  	      $action = array();
          if ($module->isInstalled()) {
            $action[] = array('class' => 'icon-edit-record', 'qtip' => $osC_Language->get('icon_edit'));
            $action[] = array('class' => 'icon-uninstall-record', 'qtip' => $osC_Language->get('icon_uninstall'));
          } else {
            $action[] = array('class' => 'icon-edit-gray-record', 'qtip' => $osC_Language->get('icon_edit'));
            $action[] = array('class' => 'icon-install-record', 'qtip' => $osC_Language->get('icon_install'));
          }
          
          if ($module instanceof toC_China_Shipping_Admin) {
            $parent = '中文运输方式';
            
            if ($module->isInstalled()) {
              $action[] = array_unshift($action, array('class' => 'icon-advanced-record', 'qtip' => $osC_Language->get('icon_advanced')));
            } else {
              $action[] = array_unshift($action, array('class' => 'icon-advanced-gray-record', 'qtip' => $osC_Language->get('icon_advanced')));
            }
          } else {
            $parent = '默认运输方式';
          }

  	      $modules[] = array(
  	        'parent' => $parent,
  	        'code' => $module->getCode(),
  	        'title' => $module->getTitle(),
  	        'sort_order' => $module->getSortOrder(),
            'action' => $action
  	      );
  	    }
      }

      $response[EXT_JSON_READER_ROOT] = $modules;
      
      echo $toC_Json->encode($response);
    }
      
    function install() {
      global $toC_Json, $osC_Language;

      $code = $_REQUEST['module_code'];
      
      if ( file_exists('includes/modules/shipping/' . $code . '.php') ) {
        $osC_Language->injectDefinitions('modules/shipping/' . $code . '.xml');

        include('includes/modules/shipping/' . $code . '.php');
        
        $module = 'osC_Shipping_' . $code;
        $module = new $module();

        $module->install();

        osC_Cache::clear('modules-shipping');
        osC_Cache::clear('configuration');
      
        $response['success'] = true;
        $response['feedback'] = $osC_Language->get('ms_success_action_performed');
      } else {
        $response['success'] = false;  
        $response['feedback'] = $osC_Language->get('ms_error_action_not_performed');
      }
      
      echo $toC_Json->encode($response);
    }
      
    function uninstall() {
      global $toC_Json, $osC_Language;

      $code = $_REQUEST['module_code'];

      if ( file_exists('includes/modules/shipping/' . $code . '.php') ) {
        $osC_Language->injectDefinitions('modules/shipping/' . $code . '.xml');

        include('includes/modules/shipping/' . $code . '.php');

        $module = 'osC_Shipping_' . $code;
        $module = new $module();

        $module->remove();

        osC_Cache::clear('modules-shipping');
        osC_Cache::clear('configuration');

        $response['success'] = true;
        $response['feedback'] = $osC_Language->get('ms_success_action_performed');
      }else{
        $response['success'] = false;  
        $response['feedback'] = $osC_Language->get('ms_error_action_not_performed');
      }
      
      echo $toC_Json->encode($response);
    }
    
    function getConfigurationOptions() {
      global $osC_Language, $osC_Database, $toC_Json;
      
      include('includes/modules/shipping/' . $_REQUEST['code'] . '.php');
    
      $osC_Language->injectDefinitions('modules/shipping/' . $_REQUEST['code'] . '.xml');
    
      $module = 'osC_Shipping_' . $_REQUEST['code'];
      $module = new $module();
    
      $keys = array();
      foreach ($module->getKeys() as $key) {
        $Qkey = $osC_Database->query('select configuration_id, configuration_key, configuration_title, configuration_value, configuration_description, use_function, set_function from :table_configuration where configuration_key = :configuration_key');
        $Qkey->bindTable(':table_configuration', TABLE_CONFIGURATION);
        $Qkey->bindValue(':configuration_key', $key);
        $Qkey->execute();

        $cfgValue = $Qkey->value('configuration_value');
        if ( !osc_empty($Qkey->value('use_function')) ) {
          $cfgValue = osc_call_user_func($Qkey->value('use_function'), $Qkey->value('configuration_value'));
        }        
        
        $control = array();
        if ( !osc_empty($Qkey->value('set_function')) ) {
          $control = osc_call_user_func($Qkey->value('set_function'), $Qkey->value('configuration_value'), $key);
          $field['title'] = $Qkey->value('configuration_title');
        } else {
          $control['type'] = 'textfield';
          $control['name'] = 'configuration[' . $key . ']';
        }
        $control['id'] = $Qkey->value('configuration_id');
        $control['title'] = $Qkey->value('configuration_title');
        $control['value'] = $Qkey->value('configuration_value');
        $control['description'] = $Qkey->value('configuration_description');
        
        $keys[] = $control;
      }
      
      echo $toC_Json->encode($keys);
    }
        
    function save() {
      global $toC_Json, $osC_Database, $osC_Language;

      $error = false;

      $osC_Database->startTransaction();

      $data = array('configuration' => $_POST['configuration']);
      foreach ( $data['configuration'] as $key => $value ) {
        $Qupdate = $osC_Database->query('update :table_configuration set configuration_value = :configuration_value where configuration_key = :configuration_key');
        $Qupdate->bindTable(':table_configuration', TABLE_CONFIGURATION);
        $Qupdate->bindValue(':configuration_value', is_array($data['configuration'][$key]) ? implode(',', $data['configuration'][$key]) : $value);
        $Qupdate->bindValue(':configuration_key', $key);
        $Qupdate->setLogging($_SESSION['module']);
        $Qupdate->execute();

        if ( $osC_Database->isError() ) {
          $error = true;
          break;
        }
      }

      if ( $error === false ) {
        $osC_Database->commitTransaction();
        
        osC_Cache::clear('configuration');
        
        $response['success'] = true;
        $response['feedback'] = $osC_Language->get('ms_success_action_performed');
      } else {
        $osC_Database->rollbackTransaction();

        $response['success'] = false;  
        $response['feedback'] = $osC_Language->get('ms_error_action_not_performed');
      }

      echo $toC_Json->encode($response);
    }
    
    function listChineseShippingArea() {
      global $toC_Json, $osC_Database, $osC_Language;
      
      $Qareas = $osC_Database->query('select china_shipping_area_id, china_shipping_area_name, configure from :table_china_shipping_area where china_shipping_code = :china_shipping_code');
      $Qareas->bindTable(':table_china_shipping_area', TABLE_CHINA_SHIPPING_AREA);
      $Qareas->bindValue(':china_shipping_code', $_REQUEST['code']);
      $Qareas->execute();
      
      $records = array();
      while( $Qareas->next() ) {
        $Qregions = $osC_Database->query('select cr.region_name, cr.china_region_id, cr.region_type from :table_china_region cr, :table_china_area_to_region catr where catr.china_shipping_area_id = :china_shipping_area_id and catr.china_region_id = cr.china_region_id order by cr.china_region_id');
        $Qregions->bindTable(':table_china_area_to_region', TABLE_CHINA_AREA_TO_REGION);
        $Qregions->bindTable(':table_china_region', TABLE_CHINA_REGION);
        $Qregions->bindInt(':china_shipping_area_id', $Qareas->valueInt('china_shipping_area_id'));
        $Qregions->execute();

        $names = array();
        $regions = array();
        while ( $Qregions->next() ) {
          $names[] = $Qregions->value('region_name');
          $regions[] = $Qregions->valueInt('china_region_id') . '-' . $Qregions->value('region_name') . '-' . $Qregions->valueInt('region_type');
        }
        
        $records[] = array('shipping_area_id' => $Qareas->valueInt('china_shipping_area_id'),
                           'shipping_area_name' => $Qareas->value('china_shipping_area_name'),
                           'region_names' => implode(',', $names),
                           'region_data' => implode(';', $regions));
      }
      
      $response = array(EXT_JSON_READER_ROOT => $records);

      echo $toC_Json->encode($response);
    }
    
    function getChinaProvinces() {
      global $toC_Json, $osC_Language, $osC_Database;
      
      $region_id = isset($_REQUEST['region_id']) ? $_REQUEST['region_id'] : null;
      $provinces = self::getRegions($region_id);
      $response = array(EXT_JSON_READER_ROOT => $provinces);    

      echo $toC_Json->encode($response);
    }
      
    function getChinaCities() {
      global $toC_Json, $osC_Language, $osC_Database;
      
      $region_id = isset($_REQUEST['region_id']) ? $_REQUEST['region_id'] : null;
      $provinces = self::getRegions($region_id);
      $response = array(EXT_JSON_READER_ROOT => $provinces);    

      echo $toC_Json->encode($response);
    }
        
    function getChinaDistricts() {
      global $toC_Json, $osC_Language, $osC_Database;
      
      $region_id = isset($_REQUEST['region_id']) ? $_REQUEST['region_id'] : null;
      $provinces = self::getRegions($region_id);
      $response = array(EXT_JSON_READER_ROOT => $provinces);    

      echo $toC_Json->encode($response);
    }
    
    function getRegions($region_id = 0) {
      global $osC_Database;
      
      $Qregions = $osC_Database->query('select china_region_id, region_name, region_type from :table_china_region where parent_id = :parent_id');
      $Qregions->bindTable(':table_china_region', TABLE_CHINA_REGION);
      $Qregions->bindInt(':parent_id', $region_id);
      $Qregions->execute();
      
      $regions = array();
      while ( $Qregions->next() ) {
        $region_type = $Qregions->valueInt('region_type');
        
        $regions[] = array('region_id' => $Qregions->valueInt('china_region_id'),
                           'region_name' => $Qregions->value('region_name'),
                           'region_type' => $Qregions->valueInt('region_type'));
      }
      
      if (!empty($regions)) {
        array_unshift($regions, array('region_id' => 0,
                                      'region_name' => '--全部--',
                                      'region_type' => $region_type));
      }
      
      return $regions;
    }
    
    function getAreaParameters() {
      global $osC_Language, $osC_Database, $toC_Json;
      
      $osC_Language->injectDefinitions('modules/shipping/' . $_REQUEST['code'] . '.xml');
      
      if (isset($_REQUEST['shipping_area_id']) && $_REQUEST['shipping_area_id'] > 0) {
        $data = toC_China_Shipping_Admin::getShippingAreas($_REQUEST['shipping_area_id']);
        $zone_params = $data['configure'];
        $shipping_area_name = $data['shipping_area_name'];
      } else {
        include('includes/modules/shipping/' . $_REQUEST['code'] . '.php');
    
        $module = 'osC_Shipping_' . $_REQUEST['code'];
        $module = new $module();
      
        $zone_params = $module->_zone_params;
        $shipping_area_name = '';
      }
      
      $controls = array(array('title' => '区域名称',
                              'name' => 'shipping_area_name',
                              'value' => $shipping_area_name));
      
      foreach ($zone_params as $key => $value) {
        $controls[] = array('title' => $osC_Language->get($key), 
                            'name' => $key,
                            'value' => $value);
      }

      echo $toC_Json->encode($controls);
    }
    
    function saveShippingArea() {
      global $toC_Json, $osC_Database, $osC_Language;
      
      if (isset($_REQUEST['shipping_area_id']) && $_REQUEST['shipping_area_id'] > 0) {
        $data = toC_China_Shipping_Admin::getShippingAreas($_REQUEST['shipping_area_id']);
        $params = $data['configure'];
      } else {
        include('includes/modules/shipping/' . $_REQUEST['code'] . '.php');
        
        $module = 'osC_Shipping_' . $_REQUEST['code'];
        $module = new $module();
        
        $params = $module->getZoneParams();
      }
      
      $regions = explode(';', $_REQUEST['region']);
      for($i = 0; $i < sizeof($regions); $i++) {
        $region = explode(',', $regions[$i]);
        
        $region_ids[] = array('id' => $region[0],
                              'type' => $region[1]);
      }
      
      $configure = array();
      foreach ($params as $key => $value) {
        $configure[$key] = $_REQUEST[$key];
      }
      
      $data = array('shipping_area_name' => $_REQUEST['shipping_area_name'],
                    'shipping_code' => $_REQUEST['code'],
                    'configure' => $configure,
                    'region_ids' => $region_ids);
      
      if (toC_China_Shipping_Admin::saveShippingArea((isset($_REQUEST['shipping_area_id']) ? $_REQUEST['shipping_area_id'] : null), $data)) {
        $response = array('success' => true, 'feedback' => $osC_Language->get('ms_success_action_performed'));
      } else {
        $response = array('success' => false, 'feedback' => $osC_Language->get('ms_error_action_not_performed'));
      }
      
      echo $toC_Json->encode($response);
    }
      
    function deleteShippingArea() {
      global $toC_Json, $osC_Database, $osC_Language;

      if (toC_China_Shipping_Admin::deleteShippingArea($_REQUEST['shipping_area_id'])) {
        $response = array('success' => true, 'feedback' => $osC_Language->get('ms_success_action_performed'));
      } else {
        $response = array('success' => false, 'feedback' => $osC_Language->get('ms_error_action_not_performed'));
      }
      
      echo $toC_Json->encode($response);
    }
    
    function deleteShippingAreas() {
      global $toC_Json, $osC_Database, $osC_Language;
      
      $error = false;
      
      $batch = explode(',', $_REQUEST['batch']);
      foreach($batch as $shipping_area_id) {
        if (!toC_China_Shipping_Admin::deleteShippingArea($shipping_area_id)) {
          $error = true;
          break;
        }
      }
    
      if ($error === false) {      
        $response = array('success' => true, 'feedback' => $osC_Language->get('ms_success_action_performed'));
      } else {
        $response = array('success' => false, 'feedback' => $osC_Language->get('ms_error_action_not_performed'));
      }
      
      echo $toC_Json->encode($response);
    }
  }
?>
