<?php
/*
  MODULOOM Package Tracking Service version 4.1
  This module has been adapted to fit in OpenCart 1.5.x.

  @package shippingMethod
  @copyright Copyright © 2012,2013 Philippe BLAIN <pblain@NOSPAMfree.fr>.

  ------------------------------------------------------------------------------
*/
define('EXTENSION_NAME', 'Package Tracking Service');
define('EXTENSION_VERSION', '20130823');
define('EXTENSION_TYPE', 'vQmod');
define('EXTENSION_COMPATIBILITY', 'OpenCart 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5 and 1.5.5.1');
define('EXTENSION_URL', 'http://www.opencart.com/index.php?route=extension/extension/info&extension_id=4433');
define('EXTENSION_FORUM', 'http://forum.opencart.com/viewtopic.php?t=49609');
define('EXTENSION_SUPPORT', 'pblain@free.fr');
define('EXTENSION_COPYRIGHT', 'Copyright &copy; 2011-'.date('Y').' Philippe BLAIN');

class ControllerModulePackageTracking extends Controller {
  private $error = array();
  private $defaults = array(
    'pts_show_images'              => 1,
    'pts_last_tracking'            => 0,
    'pts_history_on_invoice'       => 1,
    'pts_only_notified_on_invoice' => 1,
    'pts_remove_sql_changes'       => 0
  );

  public function index() {
    $this->load->language('module/package_tracking');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->model('module/package_tracking');

    $this->getList();
  }

  public function insert() {
    $this->load->language('module/package_tracking');

    $this->document->setTitle($this->language->get('heading_title'));

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->load->model('module/package_tracking');

      $this->model_module_package_tracking->addTracker($this->request->post);

      $this->session->data['success'] = $this->language->get('text_success');

      // URL GET parameters
      $url = '';

      if (isset($this->request->get['sort'])) {
        $url .= '&sort=' . $this->request->get['sort'];
      }

      if (isset($this->request->get['order'])) {
        $url .= '&order=' . $this->request->get['order'];
      }

      if (isset($this->request->get['page'])) {
        $url .= '&page=' . $this->request->get['page'];
      }

      $this->redirect($this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getForm();
  }

  public function update() {
    $this->load->language('module/package_tracking');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->model('module/package_tracking');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
      $this->model_module_package_tracking->editTracker($this->request->get['tracker_id'], $this->request->post);

      $this->session->data['success'] = $this->language->get('text_success');

      // URL GET parameters
      $url = '';

      if (isset($this->request->get['sort'])) {
        $url .= '&sort=' . $this->request->get['sort'];
      }

      if (isset($this->request->get['order'])) {
        $url .= '&order=' . $this->request->get['order'];
      }

      if (isset($this->request->get['page'])) {
        $url .= '&page=' . $this->request->get['page'];
      }

      $this->redirect($this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getForm();
  }

  public function delete() {
    $this->load->language('module/package_tracking');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->model('module/package_tracking');

    if (isset($this->request->post['selected']) && $this->validateDelete()) {
      foreach ($this->request->post['selected'] as $tracker_id) {
        $this->model_module_package_tracking->deleteTracker($tracker_id);
      }

      $this->session->data['success'] = $this->language->get('text_success');

      // URL GET parameters
      $url = '';

      if (isset($this->request->get['sort'])) {
        $url .= '&sort=' . $this->request->get['sort'];
      }

      if (isset($this->request->get['order'])) {
        $url .= '&order=' . $this->request->get['order'];
      }

      if (isset($this->request->get['page'])) {
        $url .= '&page=' . $this->request->get['page'];
      }

      $this->redirect($this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getList();
  }

  public function save() {
    $this->load->language('module/package_tracking');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->model('module/package_tracking');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateSave()) {
      $this->load->model('setting/setting');

      $this->model_setting_setting->editSetting('package_tracking', $this->request->post);

      $this->session->data['success'] = $this->language->get('text_success');

      // URL GET parameters
      $url = '';

      if (isset($this->request->get['sort'])) {
        $url .= '&sort=' . $this->request->get['sort'];
      }

      if (isset($this->request->get['order'])) {
        $url .= '&order=' . $this->request->get['order'];
      }

      if (isset($this->request->get['page'])) {
        $url .= '&page=' . $this->request->get['page'];
      }

      $this->redirect($this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . $url, 'SSL'));
    }

    $this->getList();
  }

  private function getList() {
    // Language texts
    $this->data['heading_title']                  = $this->language->get('heading_title');

    $this->data['text_enabled']                   = $this->language->get('text_enabled');
    $this->data['text_disabled']                  = $this->language->get('text_disabled');
    $this->data['text_no_results']                = $this->language->get('text_no_results');
    $this->data['text_image_manager']             = $this->language->get('text_image_manager');
    $this->data['text_delete_confirm']            = $this->language->get('text_delete_confirm');

    $this->data['tab_general']                    = $this->language->get('tab_general');
    $this->data['tab_settings']                   = $this->language->get('tab_settings');
    $this->data['tab_about']                      = $this->language->get('tab_about');

    $this->data['button_back']                    = $this->language->get('button_back');
    $this->data['button_insert']                  = $this->language->get('button_insert');
    $this->data['button_delete']                  = $this->language->get('button_delete');
    $this->data['button_save']                    = $this->language->get('button_save');

    $this->data['column_tracker_carrier_name']    = $this->language->get('column_tracker_carrier_name');
    $this->data['column_tracker_carrier_link']    = $this->language->get('column_tracker_carrier_link');
    $this->data['column_tracker_status']          = $this->language->get('column_tracker_status');
    $this->data['column_tracker_image']           = $this->language->get('column_tracker_image');
    $this->data['column_action']                  = $this->language->get('column_action');

    $this->data['entry_show_images']              = $this->language->get('entry_show_images');
    $this->data['entry_last_tracking']            = $this->language->get('entry_last_tracking');
    $this->data['entry_history_on_invoice']       = $this->language->get('entry_history_on_invoice');
    $this->data['entry_only_notified_on_invoice'] = $this->language->get('entry_only_notified_on_invoice');
    $this->data['entry_remove_sql_changes']       = $this->language->get('entry_remove_sql_changes');

    $this->data['entry_extension_name']           = $this->language->get('entry_extension_name');
    $this->data['entry_extension_desc']           = $this->language->get('entry_extension_desc');
    $this->data['entry_extension_version']        = $this->language->get('entry_extension_version');
    $this->data['entry_extension_compatibility']  = $this->language->get('entry_extension_compatibility');
    $this->data['entry_extension_url']            = $this->language->get('entry_extension_url');
    $this->data['entry_extension_support']        = $this->language->get('entry_extension_support');
    $this->data['entry_extension_forum']          = $this->language->get('entry_extension_forum');
    $this->data['entry_extension_help_asking']    = $this->language->get('entry_extension_help_asking');
    $this->data['entry_extension_help_request']   = $this->language->get('entry_extension_help_request');
    $this->data['entry_extension_legal']          = $this->language->get('entry_extension_legal');
    $this->data['entry_extension_terms']          = $this->language->get('entry_extension_terms');

    $this->data['extension_name']                 = EXTENSION_NAME;
    $this->data['extension_desc']                 = $this->language->get('extension_desc');
    $this->data['extension_version']              = EXTENSION_VERSION;
    $this->data['extension_type']                 = EXTENSION_TYPE;
    $this->data['extension_compatibility']        = EXTENSION_COMPATIBILITY;
    $this->data['extension_url']                  = EXTENSION_URL;
    $this->data['extension_forum']                = EXTENSION_FORUM;
    $this->data['extension_support']              = EXTENSION_SUPPORT;
    $this->data['extension_subject']              = sprintf($this->language->get('extension_subject'), EXTENSION_NAME);
    $this->data['extension_copyright']            = EXTENSION_COPYRIGHT;

    // Sort, order and page
    if (isset($this->request->get['sort'])) {
      $sort = $this->request->get['sort'];
    } else {
      $sort = 'tracker_carrier_name';
    }

    if (isset($this->request->get['order'])) {
      $order = $this->request->get['order'];
    } else {
      $order = 'ASC';
    }

    if (isset($this->request->get['page'])) {
      $page = $this->request->get['page'];
    } else {
      $page = 1;
    }

    $this->data['sort'] = $sort;
    $this->data['order'] = $order;

    // URL GET parameters
    $url = '';

    if (isset($this->request->get['sort'])) {
      $url .= '&sort=' . $this->request->get['sort'];
    }

    if (isset($this->request->get['order'])) {
      $url .= '&order=' . $this->request->get['order'];
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    // Breadcrumbs
    $this->data['breadcrumbs'] = $this->populateBreadcrumbs($this->session->data['token'], $url);

    // Action buttons
    $this->data['back']   = $this->url->link('extension/module', 'token='.$this->session->data['token'], 'SSL');
    $this->data['action'] = $this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . $url, 'SSL');
    $this->data['insert'] = $this->url->link('module/package_tracking'.'/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
    $this->data['delete'] = $this->url->link('module/package_tracking'.'/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');
    $this->data['save']   = $this->url->link('module/package_tracking'.'/save', 'token=' . $this->session->data['token'] . $url, 'SSL');

    // Trackers list
    $this->data['trackers'] = array();

    $data = array(
      'sort'  => $sort,
      'order' => $order,
      'start' => ($page - 1) * $this->config->get('config_admin_limit'),
      'limit' => $this->config->get('config_admin_limit')
    );

    $this->load->model('tool/image');

    $tracker_total = $this->model_module_package_tracking->getTotalTrackers();

    $results = $this->model_module_package_tracking->getTrackers($data);

    foreach ($results as $result) {
      $action = array();

      $action[] = array(
        'text' => $this->language->get('text_edit'),
        'href' => $this->url->link('module/package_tracking'.'/update', 'token=' . $this->session->data['token'] . '&tracker_id=' . $result['tracker_id'] . $url, 'SSL')
      );

      if ($result['tracker_image'] && file_exists(DIR_IMAGE.$result['tracker_image'])) {
        $image = $this->model_tool_image->resize($result['tracker_image'], 40, 40);
      } else {
        $image = $this->model_tool_image->resize('no_image.jpg', 40, 40);
      }

      $this->data['trackers'][] = array(
        'tracker_id'           => $result['tracker_id'],
        'tracker_carrier_name' => $result['tracker_carrier_name'] . (($result['tracker_id'] == $this->config->get('config_tracker_id')) ? $this->language->get('text_default') : null),
        'tracker_carrier_link' => $result['tracker_carrier_link'],
        'tracker_status'       => ($result['tracker_status']) ? $this->language->get('text_enabled') : $this->language->get('text_disabled'),
        'tracker_image'        => $image,
        'last_modified'        => $result['last_modified'],
        'date_added'           => $result['date_added'],
        'selected'             => isset($this->request->post['selected']) && in_array($result['tracker_id'], $this->request->post['selected']),
        'action'               => $action
      );
    }

    // Post or config setting values
    foreach (array_keys($this->defaults) as $setting) {
      if (isset($this->request->post[$setting])) {
        $this->data[$setting] = $this->request->post[$setting];
      } else {
        $this->data[$setting] = $this->config->get($setting);
      }
    }

    if (!class_exists('VQMod')) {
      $this->error['warning'] = $this->language->get('error_vqmod');
    }

    // Errors
    if (isset($this->error['warning'])) {
      $this->data['error_warning'] = $this->error['warning'];
    } else {
      $this->data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $this->data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $this->data['success'] = '';
    }

    // Columns sorting
    $url = '';

    if ($order == 'ASC') {
      $url .= '&order=DESC';
    } else {
      $url .= '&order=ASC';
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    $this->data['sort_tracker_carrier_name'] = $this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . '&sort=tracker_carrier_name' . $url, 'SSL');
    $this->data['sort_tracker_carrier_link'] = $this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . '&sort=tracker_carrier_link' . $url, 'SSL');

    // Pagination
    $url = '';

    if (isset($this->request->get['sort'])) {
      $url .= '&sort=' . $this->request->get['sort'];
    }

    if (isset($this->request->get['order'])) {
      $url .= '&order=' . $this->request->get['order'];
    }

    $pagination = new Pagination();
    $pagination->total = $tracker_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_admin_limit');
    $pagination->text = $this->language->get('text_pagination');
    $pagination->url = $this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

    $this->data['pagination'] = $pagination->render();

    // Template
    $this->template = 'module/package_tracking_list.tpl';
    $this->children = array(
      'common/header',
      'common/footer'
    );

    $this->response->setOutput($this->render());
  }

  private function getForm() {
    // Language texts
    $this->data['heading_title']              = $this->language->get('heading_title');

    $this->data['text_enabled']               = $this->language->get('text_enabled');
    $this->data['text_disabled']              = $this->language->get('text_disabled');
    $this->data['text_image_manager']         = $this->language->get('text_image_manager');
    $this->data['text_browse']                = $this->language->get('text_browse');
    $this->data['text_clear']                 = $this->language->get('text_clear');

    $this->data['entry_tracker_carrier_name'] = $this->language->get('entry_tracker_carrier_name');
    $this->data['entry_tracker_carrier_link'] = $this->language->get('entry_tracker_carrier_link');
    $this->data['entry_tracker_image']        = $this->language->get('entry_tracker_image');
    $this->data['entry_tracker_status']       = $this->language->get('entry_tracker_status');
    $this->data['entry_last_modified']        = $this->language->get('entry_last_modified');
    $this->data['entry_date_added']           = $this->language->get('entry_date_added');

    // Action buttons
    $this->data['button_save']   = $this->language->get('button_save');
    $this->data['button_cancel'] = $this->language->get('button_cancel');

    // Errors
    if (isset($this->error['warning'])) {
      $this->data['error_warning'] = $this->error['warning'];
    } else {
      $this->data['error_warning'] = '';
    }

    if (isset($this->error['tracker_carrier_name'])) {
      $this->data['error_tracker_carrier_name'] = $this->error['tracker_carrier_name'];
    } else {
      $this->data['error_tracker_carrier_name'] = '';
    }

    if (isset($this->error['tracker_carrier_link'])) {
      $this->data['error_tracker_carrier_link'] = $this->error['tracker_carrier_link'];
    } else {
      $this->data['error_tracker_carrier_link'] = '';
    }

    // URL GET parameters
    $url = '';

    if (isset($this->request->get['sort'])) {
      $url .= '&sort=' . $this->request->get['sort'];
    }

    if (isset($this->request->get['order'])) {
      $url .= '&order=' . $this->request->get['order'];
    }

    if (isset($this->request->get['page'])) {
      $url .= '&page=' . $this->request->get['page'];
    }

    // Breadcrumbs
    $this->data['breadcrumbs'] = $this->populateBreadcrumbs($this->session->data['token'], $url);

    // Action buttons
    $this->data['cancel']   = $this->url->link('module/package_tracking', 'token=' . $this->session->data['token'] . $url, 'SSL');
    if (!isset($this->request->get['tracker_id'])) {
      $this->data['action'] = $this->url->link('module/package_tracking'.'/insert', 'token=' . $this->session->data['token'] . $url, 'SSL');
    } else {
      $this->data['action'] = $this->url->link('module/package_tracking'.'/update', 'token=' . $this->session->data['token'] . '&tracker_id=' . $this->request->get['tracker_id'] . $url, 'SSL');
    }

    // Security key for filemanager
    $this->data['token'] = $this->session->data['token'];

    if (isset($this->request->get['tracker_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
      $tracker_info = $this->model_module_package_tracking->getTracker($this->request->get['tracker_id']);
    }

    // View datas
    if (isset($this->request->post['tracker_carrier_name'])) {
      $this->data['tracker_carrier_name'] = $this->request->post['tracker_carrier_name'];
    } elseif (isset($tracker_info)) {
      $this->data['tracker_carrier_name'] = $tracker_info['tracker_carrier_name'];
    } else {
      $this->data['tracker_carrier_name'] = '';
    }

    if (isset($this->request->post['tracker_carrier_link'])) {
      $this->data['tracker_carrier_link'] = $this->request->post['tracker_carrier_link'];
    } elseif (isset($tracker_info)) {
      $this->data['tracker_carrier_link'] = $tracker_info['tracker_carrier_link'];
    } else {
      $this->data['tracker_carrier_link'] = '';
    }

    if (isset($this->request->post['tracker_status'])) {
      $this->data['tracker_status'] = $this->request->post['tracker_status'];
    } elseif (isset($tracker_info)) {
      $this->data['tracker_status'] = $tracker_info['tracker_status'];
    } else {
      $this->data['tracker_status'] = 1;
    }

    if (isset($this->request->post['tracker_image'])) {
      $this->data['tracker_image'] = $this->request->post['tracker_image'];
    } elseif (isset($tracker_info)) {
      $this->data['tracker_image'] = $tracker_info['tracker_image'];
    } else {
      $this->data['tracker_image'] = '';
    }

    $this->load->model('tool/image');

    if (isset($this->request->post['tracker_image']) && file_exists(DIR_IMAGE . $this->request->post['tracker_image'])) {
      $this->data['thumb'] = $this->model_tool_image->resize($this->request->post['tracker_image'], 210, 70);
    } elseif (!empty($tracker_info) && $tracker_info['tracker_image'] && file_exists(DIR_IMAGE . $tracker_info['tracker_image'])) {
      $this->data['thumb'] = $this->model_tool_image->resize($tracker_info['tracker_image'], 210, 70);
    } else {
      $this->data['thumb'] = $this->model_tool_image->resize('no_image.jpg', 210, 70);
    }

    $this->data['no_image'] = $this->model_tool_image->resize('no_image.jpg', 210, 70);

    if (isset($this->request->post['date_added'])) {
      $this->data['date_added'] = $this->request->post['date_added'];
    } elseif (isset($tracker_info)) {
      $this->data['date_added'] = $tracker_info['date_added'];
    } else {
      $this->data['date_added'] = '';
    }

    if (isset($this->request->post['last_modified'])) {
      $this->data['last_modified'] = $this->request->post['last_modified'];
    } elseif (isset($tracker_info)) {
      $this->data['last_modified'] = $tracker_info['last_modified'];
    } else {
      $this->data['last_modified'] = '';
    }

    // Template
    $this->template = 'module/package_tracking_form.tpl';
    $this->children = array(
      'common/header',
      'common/footer'
    );

    $this->response->setOutput($this->render());
  }

  private function validateForm() {
    if (!$this->user->hasPermission('modify', 'module/package_tracking')) {
      $this->error['warning'] = $this->language->get('error_permission');
      return false;
    }

    // utf8_strlen() introduced in 1.5.1.3.1
    if ((strlen(utf8_decode($this->request->post['tracker_carrier_name'])) < 3) || (strlen(utf8_decode($this->request->post['tracker_carrier_name'])) > 64)) {
      $this->error['tracker_carrier_name'] = $this->language->get('error_tracker_carrier_name');
    }

    if (strlen(utf8_decode($this->request->post['tracker_carrier_link'])) < 2) {
      $this->error['tracker_carrier_link'] = $this->language->get('error_tracker_carrier_link');
    }

    if ($this->error) {
      return false;
    } else {
      return true;
    }
  }

  private function validateDelete() {
    if (!$this->user->hasPermission('modify', 'module/package_tracking')) {
      $this->error['warning'] = $this->language->get('error_permission');
      return false;
    }

    $this->load->model('setting/store');
    $this->load->model('sale/order');
    $this->load->model('sale/return');

    foreach ($this->request->post['selected'] as $tracker_id) {
      $tracker_info = $this->model_module_package_tracking->getTracker($tracker_id);
      if ($tracker_info) {
        if ($this->config->get('config_tracker_id') == $tracker_info['tracker_id']) {
          $this->error['warning'] = $this->language->get('error_tracker_default');
          break;
        }
      }

      $order_history_total = $this->model_sale_order->getTotalOrderHistoriesByTrackerId($tracker_id);
      if ($order_history_total) {
        $this->error['warning'] = sprintf($this->language->get('error_order_history'), $order_history_total);
        break;
      }

      $return_history_total = $this->model_sale_return->getTotalReturnHistoriesByTrackerId($tracker_id);
      if ($return_history_total) {
        $this->error['warning'] = sprintf($this->language->get('error_order_history'), $return_history_total);
        break;
      }
    }

    if ($this->error) {
      return false;
    } else {
      return true;
    }
  }

  private function validateSave() {
    if (!$this->user->hasPermission('modify', 'module/package_tracking')) {
      $this->error['warning'] = $this->language->get('error_permission');
      return false;
    }

    if ($this->error) {
      return false;
    } else {
      return true;
    }
  }

  private function populateBreadcrumbs($token, $url) {
    $bc = array();

    $bc[] = array(
      'text'      => $this->language->get('text_home'),
      'href'      => $this->url->link('common/home', 'token=' . $token, 'SSL'),
      'separator' => false
    );

    $bc[] = array(
      'text'      => $this->language->get('text_module'),
      'href'      => $this->url->link('extension/module', 'token=' . $token, 'SSL'),
      'separator' => ' :: '
    );

    $bc[] = array(
      'text'      => $this->language->get('heading_title'),
      'href'      => $this->url->link('module/package_tracking', 'token=' . $token . $url, 'SSL'),
      'separator' => ' :: '
    );

    return $bc;
  }

  public function install() {
    $this->load->language('module/package_tracking');

    // Tables
    $table_exists = $this->db->query("SHOW TABLES LIKE '" . DB_PREFIX . "trackers'");
    if (!$table_exists->num_rows) {

      $this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "trackers` (
        `tracker_id` int(11) NOT NULL AUTO_INCREMENT,
        `tracker_carrier_name` varchar(64) NOT NULL DEFAULT '',
        `tracker_carrier_link` text NOT NULL DEFAULT '',
        `tracker_status` tinyint(1) NOT NULL DEFAULT '0',
        `tracker_image` varchar(255) DEFAULT NULL,
        `date_added` datetime NOT NULL DEFAULT '0001-01-01 00:00:00',
        `last_modified` datetime DEFAULT NULL,
        PRIMARY KEY (tracker_id)
      ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci");

      $this->db->query("INSERT INTO `" . DB_PREFIX . "trackers` VALUES
        (NULL, 'ABF Freight System', 'http://www.abfs.com/trace/abftrace.asp?blnBOL=TRUE&blnPO=TRUE&blnShipper=TRUE&blnConsignee=TRUE&blnABFGraphic=TRUE&blnOrigin=TRUE&blnDestination=TRUE&RefType=a&bhcp=1&Ref=%s', '1', 'data/trackers/abf_01.png', now(), now()),
        (NULL, 'ACS Courier', 'http://www1.acscourier.gr/podSearch.aspx?podString=%s', '1', 'data/trackers/acs_courier_01.jpg', now(), now()),
        (NULL, 'Aramex', 'http://www.aramex.com/express/track_results_multiple.aspx?ShipmentNumber=%s', '1', 'data/trackers/aramex_01.jpg', now(), now()),
        (NULL, 'Australia Post', 'http://auspost.com.au/track/track.html?id=%s', '1', 'data/trackers/australia_post_01.gif', now(), now()),
        (NULL, 'Belgium Post', 'http://track.bpost.be/etr/light/showSearchPage.do?itemCodes=%s', '1', 'data/trackers/bpost_01.gif', now(), now()),
        (NULL, 'British Airways', 'http://www.baworldcargo.com/tracking/results.jsp?AWBprefix=125&AWBnumber=%s', '1', 'data/trackers/british_airways_01.jpg', now(), now()),
        (NULL, 'Canada Post', 'http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=%s&LOCALE=fr', '1', 'data/trackers/canada_post_01.jpg', now(), now()),
        (NULL, 'China Post', 'http://intmail.183.com.cn/item/itemStatusQuery.do?lan=0&itemNo=%s', '1', 'data/trackers/china_post_01.gif', now(), now()),
        (NULL, 'Chronopost', 'http://www.chronopost.fr/expedier/inputLTNumbersNoJahia.do?listeNumeros=%s', '1', 'data/trackers/chronopost_01.gif', now(), now()),
        (NULL, 'ColiPoste', 'http://www.coliposte.net/particulier/suivi_particulier.jsp?colispart=%s', '1', 'data/trackers/coliposte_01.jpg', now(), now()),
        (NULL, 'Correios Brazil', 'http://websro.correios.com.br/sro_bin/txect01$.QueryList?P_LINGUA=001&P_TIPO=001&P_COD_UNI=%s', '1', 'data/trackers/correios_01.jpg', now(), now()),
        (NULL, 'Correos Espana', 'http://correos.es/comun/localizador/track.asp?accion=LocalizaUno&numero=%s', '1', 'data/trackers/correos_01.jpg', now(), now()),
        (NULL, 'CourierPost', 'http://trackandtrace.courierpost.co.nz/search/%s', '1', 'data/trackers/courier_post_01.jpg', now(), now()),
        (NULL, 'DHL Deutschland', 'http://nolp.dhl.de/nextt-online-public/track.do?idc=%s&lang=de', '1', 'data/trackers/dhl_02.jpg', now(), now()),
        (NULL, 'DHL', 'http://www.dhl.com/content/g0/en/express/tracking.shtml?brand=DHL&AWB=%s', '1', 'data/trackers/dhl_01.jpg', now(), now()),
        (NULL, 'DPD', 'http://www.dpd.de/cgi-bin/delistrack?typ=1&lang=de&pknr=%s', '1', 'data/trackers/dpd_01.jpg', now(), now()),
        (NULL, 'Danmark Post', 'http://www.postdanmark.dk/da/Sider/TrackTrace.aspx?search=%s', '1', 'data/trackers/dk_post_01.png', now(), now()),
        (NULL, 'ELTA Courier', 'http://www.elta-courier.gr/webservice_client.php?br=%s', '1', 'data/trackers/elta_courier_01.jpg', now(), now()),
        (NULL, 'EMS', 'http://www.ems-tracking.net/single-ems-tracking.php?number=%s', '1', 'data/trackers/ems_01.jpg', now(), now()),
        (NULL, 'FastWay', 'http://www.fastway.com.au/courier-services/track-your-parcel?l=%s', '1', 'data/trackers/fastway_01.gif', now(), now()),
        (NULL, 'FedEx', 'http://www.fedex.com/Tracking?action=track&tracknumbers=%s', '1', 'data/trackers/fedex_01.gif', now(), now()),
        (NULL, 'Finland Post', 'http://www.posti.fi/itemtracking/posti/search_by_shipment_id?lang=en&ShipmentId=%s', '1', 'data/trackers/posti_fi_01.gif', now(), now()),
        (NULL, 'GLS Deutschland', 'http://www.gls-germany.com/de/online/paketstatus.php3?datatype=paketnr&filter=all&paketliste[0]=%s&search_x=1', '1', 'data/trackers/gls_01.jpg', now(), now()),
        (NULL, 'GLS Europe', 'http://www.gls-group.eu/276-I-PORTAL-WEB/content/GLS/FR01/FR/5004.htm?txtRefNo=%s&txtAction=71000', '1', 'data/trackers/gls_02.jpg', now(), now()),
        (NULL, 'Geniki Taxydromiki', 'http://www.taxydromiki.gr/Tracktrace.aspx?track=%s', '1', 'data/trackers/geniki_01.jpg', now(), now()),
        (NULL, 'Hermes', 'http://tracking.hlg.de/Tracking.jsp?TrackID=%s', '1', 'data/trackers/hermes_01.gif', now(), now()),
        (NULL, 'Hong Kong Post', 'http://app3.hongkongpost.com/CGI/mt/genresult.jsp?tracknbr=%s', '1', 'data/trackers/hongkong_post_01.png', now(), now()),
        (NULL, 'India Post', 'http://services.ptcmysore.gov.in/Speednettracking/Track.aspx?articlenumber=%s', '1', 'data/trackers/india_post_01.png', now(), now()),
        (NULL, 'KLM Cargo', 'http://www.klmcargo.com/cargo/etracking/action/statusRequest.do?&awbPrefix=074&awbNum=%s', '1', 'data/trackers/klm_02.jpg', now(), now()),
        (NULL, 'La Poste Courrier', 'http://www.csuivi.courrier.laposte.fr/default.asp?EZ_ACTION=rechercheRapide&tousObj=&numObjet=%s', '1', 'data/trackers/laposte_02.png', now(), now()),
        (NULL, 'New Zealand Post', 'http://www.nzpost.co.nz/tools/tracking?trackid=%s', '1', 'data/trackers/nz_post_01.png', now(), now()),
        (NULL, 'NewPenn', 'http://www.newpenn.com/npweb/tracking.txt/process?p_input_typ=1&p_trak_1=%s', '1', 'data/trackers/newpenn_01.png', now(), now()),
        (NULL, 'Old Dominion', 'http://www.odfl.com/trace/Trace.jsp?Type=P&pronum=%s', '1', 'data/trackers/old_dominion_01.gif', now(), now()),
        (NULL, 'Parcelforce', 'http://www.parcelforce.com/portal/pw/track?trackNumber=%s', '1', 'data/trackers/parcelforce_01.png', now(), now()),
        (NULL, 'Pos Malaysia', 'http://www.pos.com.my/emstrack/search.asp?ParcelNo=%s', '1', 'data/trackers/pos_malaysia_01.gif', now(), now()),
        (NULL, 'Purolator', 'https://eshiponline.purolator.com/ShipOnline/Public/Track/TrackingStatus.aspx?lang=E&pin=%s', '1', 'data/trackers/purolator_01.gif', now(), now()),
        (NULL, 'Royal Mail', 'http://track2.royalmail.com/portal/rm/track?trackNumber=%s', '1', 'data/trackers/royal_mail_01.jpg', now(), now()),
        (NULL, 'Singapore Cargo', 'http://www.siacargo.com/eservice_siatrk.aspx?awbnum=618%s', '1', 'data/trackers/singapore_airlines_01.jpg', now(), now()),
        (NULL, 'SingPost', 'http://www.singpost.com/index.php?track_items=%s', '1', 'data/trackers/singpost_01.jpg', now(), now()),
        (NULL, 'SpeedEx', 'http://www.speedex.gr/pelates/isapohi.asp?voucher_code=%s', '1', 'data/trackers/speedex_01.jpg', now(), now()),
        (NULL, 'StarTrack', 'http://www2.startrackexpress.com.au/scripts/webtracktrace.dll/conget?connote=%s', '1', 'data/trackers/startrack_01.png', now(), now()),
        (NULL, 'TNT', 'http://www.tnt.com/webtracker/tracking.do?requestType=GEN&searchType=CON&respLang=en&respCountry=GENERIC&sourceID=1&sourceCountry=ww&cons=%s&navigation=1', '1', 'data/trackers/tnt_01.jpg', now(), now()),
        (NULL, 'UPS', 'http://wwwapps.ups.com/WebTracking/track?track=yes&loc=us_US&trackNums=%s',  '1', 'data/trackers/ups_01.gif', now(), now()),
        (NULL, 'USPS', 'http://trkcnfrm1.smi.usps.com/PTSInternetWeb/InterLabelInquiry.do?origTrackNum=%s', '1', 'data/trackers/usps_02.jpg', now(), now());
      ");
    }

    $table_exists = $this->db->query("SHOW TABLES LIKE '" . DB_PREFIX . "order_history'");
    if ($table_exists->num_rows) {
      $query = $this->db->query("DESC " . DB_PREFIX . "order_history tracker_id");
      if (!$query->num_rows) {
        $this->db->query("ALTER TABLE `" . DB_PREFIX . "order_history` ADD `tracker_id` int(11) UNSIGNED DEFAULT 0;");
      }

      $query = $this->db->query("DESC " . DB_PREFIX . "order_history tracking_numbers");
      if (!$query->num_rows) {
        $this->db->query("ALTER TABLE `" . DB_PREFIX . "order_history` ADD `tracking_numbers` text DEFAULT NULL;");
      }
    } else {
      $this->session->data['error'] = sprintf($this->language->get('error_missing_table'), DB_PREFIX . 'order_history');
    }

    $table_exists = $this->db->query("SHOW TABLES LIKE '" . DB_PREFIX . "return_history'");
    if ($table_exists->num_rows) {
      $query = $this->db->query("DESC " . DB_PREFIX . "return_history tracker_id");
      if (!$query->num_rows) {
        $this->db->query("ALTER TABLE `" . DB_PREFIX . "return_history` ADD `tracker_id` int(11) UNSIGNED DEFAULT 0;");
      }

      $query = $this->db->query("DESC " . DB_PREFIX . "return_history tracking_numbers");
      if (!$query->num_rows) {
        $this->db->query("ALTER TABLE `" . DB_PREFIX . "return_history` ADD `tracking_numbers` text DEFAULT NULL;");
      }
    } else {
      $this->session->data['error'] = sprintf($this->language->get('error_missing_table'), DB_PREFIX . 'return_history');
    }

    $this->load->model('setting/setting');
    $this->model_setting_setting->editSetting('package_tracking', $this->defaults);

    if (!class_exists('VQMod')) {
    	$this->session->data['error'] = $this->language->get('error_vqmod');
    } else {
      // Vqmods
      $vqmod_path = $this->config->get('vqmod_path');
      if (is_null($vqmod_path) || strlen($vqmod_path) < 1 || !is_dir($vqmod_path)) {
        // Attempts to autodetect vqmod path
        $path = substr_replace(DIR_SYSTEM, '', -7);
        if (is_dir($path . 'vqmod/')) $vqmod_path = $path . 'vqmod/';
      }
      $path = $vqmod_path . 'xml/';

      $vqmods = glob($path . '*package_tracking*xml_');
      if (!empty($vqmods)) {
        foreach ($vqmods as $vqmod) {
          $vqname = basename($vqmod, '.xml_');
          if (file_exists($path . $vqname . '.xml')) {
            @unlink($path . $vqname . '.xml_'); // For upgrade
          } else {
            rename($path . $vqname . '.xml_', $path . $vqname . '.xml');
          }
        }
      }

      if (!file_exists($path . 'emailtemplate.xml') and file_exists($path . 'emailtemplate_package_tracking.xml')) {
        @unlink($path . 'emailtemplate_package_tracking.xml');
      }

      if (!file_exists(DIR_LANGUAGE . 'french/french.php') and file_exists($path . 'moduloom_package_tracking_french.xml')) {
        @unlink($path . 'moduloom_package_tracking_french.xml');
      }

      // Clear vqcache
      $files = glob($this->config->get('vqmod_path') . 'vqcache/' . 'vq*');
      if ($files) {
        foreach ($files as $file) {
          if (file_exists($file)) {
            @unlink($file);
            clearstatcache();
          }
        }
      }

      $this->session->data['success'] = $this->language->get('text_success_install');
    }
  }

  public function uninstall() {
    $this->load->language('module/package_tracking');

    // Vqmods
    $vqmod_path = $this->config->get('vqmod_path');
    if (is_null($vqmod_path) || strlen($vqmod_path) < 1 || !is_dir($vqmod_path)) {
      // Attempts to autodetect vqmod path
      $path = substr_replace(DIR_SYSTEM, '', -7);
      if (is_dir($path . 'vqmod/')) $vqmod_path = $path . 'vqmod/';
    }
    $path = $vqmod_path . 'xml/';
    $vqmods = glob($path . '*package_tracking*xml');
    if (!empty($vqmods)) {
      foreach ($vqmods as $vqmod) {
        $vqname = basename($vqmod, '.xml');
        if (file_exists($path . $vqname . '.xml')) {
          rename($path . $vqname . '.xml', $path . $vqname . '.xml_');
        }
      }
    }

    // Clear vqcache
    $files = glob($this->config->get('vqmod_path') . 'vqcache/' . 'vq*');
    if ($files) {
      foreach ($files as $file) {
        if (file_exists($file)) {
          @unlink($file);
          clearstatcache();
        }
      }
    }

    // Tables
    if ($this->config->get("pts_remove_sql_changes")) {
      $this->load->model('setting/setting');
      $this->model_setting_setting->deleteSetting('package_tracking_service');

      $this->db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "trackers`");
      $this->db->query("ALTER TABLE `" . DB_PREFIX . "order_history` DROP COLUMN `tracker_id`, DROP COLUMN `tracking_numbers`");
      $this->db->query("ALTER TABLE `" . DB_PREFIX . "return_history` DROP COLUMN `tracker_id`, DROP COLUMN `tracking_numbers`");
    }

    $this->session->data['success'] = $this->language->get('text_success_uninstall');
  }
}
?>