<?php

/* CLASS FILE
----------------------------------*/

class products extends db {

  public $dt;
  public $settings;
  public $sys;

  public function add($fm) {
    db::db_query("INSERT INTO `" . DB_PREFIX . "products` (
    `ts`,
    `name`,
    `url`,
    `link`,
    `info`,
    `en`
    ) VALUES (
    '" . $this->dt->ts() . "',
    '" . db::db_escape($fm['name']) . "',
    '" . db::db_escape(($fm['url'] ? $fm['uprotocol'] . '://' . str_replace(array('http://','https://'),[],$this->sys->paths($fm['url'], 'file')) : '')) . "',
    '" . db::db_escape(($fm['link'] ? $fm['lprotocol'] . '://' . str_replace(array('http://','https://'),[],$this->sys->paths($fm['link'], 'file')) : '')) . "',
    '" . db::db_escape($fm['info']) . "',
    '{$fm['en']}'
    )");
    $ID = db::db_last_insert_id();
    products::promo($fm, $ID);
    products::file($fm, $ID);
    return $ID;
  }

  public function update($fm) {
    db::db_query("UPDATE `" . DB_PREFIX . "products` SET
    `name`    = '" . db::db_escape($fm['name']) . "',
    `url`     = '" . db::db_escape(($fm['url'] ? $fm['uprotocol'] . '://' . str_replace(array('http://','https://'),[],$this->sys->paths($fm['url'], 'file')) : '')) . "',
    `link`    = '" . db::db_escape(($fm['link'] ? $fm['lprotocol'] . '://' . str_replace(array('http://','https://'),[],$this->sys->paths($fm['link'], 'file')) : '')) . "',
    `info`    = '" . db::db_escape($fm['info']) . "',
    `en`      = '{$fm['en']}'
    WHERE `id` = '{$fm['id']}'
    ");
    products::promo($fm, $fm['id']);
    products::file($fm, $fm['id']);
  }

  private function promo($fm, $id) {
    if ($fm['id'] > 0) {
      db::db_query("UPDATE `" . DB_PREFIX . "products_promo` SET
      `info`    = '" . db::db_escape($fm['p_info']) . "'
      WHERE `product` = '{$id}'
      ");
    } else {
      db::db_query("INSERT INTO `" . DB_PREFIX . "products_promo` (
      `product`,
      `info`
      ) VALUES (
      '{$id}',
      '" . db::db_escape($fm['p_info']) . "'
      )");
    }
  }

  public function extCheck($name) {
    $allowed = array_map('trim', explode(',', strtolower(ALLOWED_PRODUCT_PROMO_EXTENSIONS)));
    $ext = substr(strrchr($name, '.'), 1);
    return (empty($allowed) || !in_array($ext, $allowed) ? 'no' : 'ok');
  }

  public function cleanFileName($name) {
    if (!PRODUCT_PROMO_FILE_RENAME) {
      return $name;
    }
    // Get final extension and remove it
    $ext = strrchr($name, '.');
    $name = str_replace($ext, '', strtolower($name));
    // Neutralise anything else and return with original extension
    return preg_replace('/[^0-9a-zA-Z_\-]/', '', $name) . $ext;
  }

  private function file($fm, $id) {
    // Was link included?
    if ($fm['link'] && (substr($fm['link'], 0, 5) == 'http:' || substr($fm['link'], 0, 6) == 'https:')) {
      return false;
    }
    // Does directory exist?
    $base   = GPATH . 'content/';
    $folder = $base . 'promo';
    $temp   = $fm['p_file'];
    $ffldr  = '';
    try {
      if (!is_dir($folder . '/' . $id)) {
        $oldumask = @umask(0);
        mkdir($folder . '/' . $id, 0755);
        @umask($oldumask);
        if (is_dir($folder . '/' . $id)) {
          $folder = $folder . '/' . $id;
          $ffldr  = $id . '/';
        }
      }
    } catch(ErrorException $e) {
      Debugger::log($e->getMessage());
    }
    // Edit only..
    if ($id > 0 && is_dir($folder . '/' . $id)) {
      $folder = $folder . '/' . $id;
      $ffldr  = $id . '/';
    }
    if ($fm['p_file'] && $fm['p_name'] && file_exists($fm['p_file'])) {
      try {
        // For edit, remove existing file..
        if ($fm['zip'] && file_exists($base . 'promo/' . $fm['zip'])) {
          try {
            unlink($base . 'promo/' . $fm['zip']);
          } catch(ErrorException $e) {
            Debugger::log($e->getMessage());
          }
        }
        if (is_uploaded_file($temp)) {
          move_uploaded_file($temp, $folder . '/' . $fm['p_name']);
          if (file_exists($folder . '/' . $fm['p_name'])) {
            chmod($folder . '/' . $fm['p_name'], AFTER_UPLOAD_CHMOD_VALUE);
            include(GPATH . 'control/classes/system/class.download.php');
            $DL = new download();
            $info = array(
              'size' => $fm['p_size'],
              'mime' => ($fm['p_mime'] ? $fm['p_mime'] : $DL->mime($folder . '/' . $fm['p_name']))
            );
            db::db_query("UPDATE `" . DB_PREFIX . "products_promo` SET
            `file_path` = '" . db::db_escape($ffldr . $fm['p_name']) . "',
            `file_info` = '" . db::db_escape(serialize($info)) . "'
            WHERE `id`  = '{$id}'
            ");
          }
          if (file_exists($temp)) {
            try {
              unlink($temp);
            } catch(ErrorException $e) {
              Debugger::log($e->getMessage());
            }
          }
        }
      } catch(ErrorException $e) {
        Debugger::log($e->getMessage());
      }
    }
  }

  public function delPromo($fm) {
    $ID = $fm['id'];
    $Q = db::db_query("SELECT * FROM `" . DB_PREFIX . "products_promo` WHERE `product` = '{$ID}' LIMIT 1");
    $PROMO = db::db_object($Q);
    if (isset($PROMO->file_path) && $PROMO->file_path && file_exists(GPATH . 'content/promo/' . $PROMO->file_path)) {
      try {
        unlink(GPATH . 'content/promo/' . $PROMO->file_path);
        if (is_dir(GPATH . 'content/promo/' . $ID)) {
          rmdir(GPATH . 'content/promo/' . $ID);
        }
      } catch(ErrorException $e) {
        Debugger::log($e->getMessage());
      }
    }
    db::db_query("UPDATE `" . DB_PREFIX . "products_promo` SET `file_path` = '',`file_info` = '' WHERE `product` = '{$ID}'");
  }

  public function delete($fm) {
    // Delete promo material..
    if (!empty($fm['ids'])) {
      foreach ($fm['ids'] AS $ID) {
        $Q = db::db_query("SELECT * FROM `" . DB_PREFIX . "products_promo` WHERE `product` = '{$ID}' LIMIT 1");
        $PROMO = db::db_object($Q);
        if (isset($PROMO->file_path) && $PROMO->file_path && file_exists(GPATH . 'content/promo/' . $PROMO->file_path)) {
          try {
            unlink(GPATH . 'content/promo/' . $PROMO->file_path);
            if (is_dir(GPATH . 'content/promo/' . $ID)) {
              rmdir(GPATH . 'content/promo/' . $ID);
            }
          } catch(ErrorException $e) {
            Debugger::log($e->getMessage());
          }
        }
      }
    }
    db::db_query("DELETE FROM `" . DB_PREFIX . "products` WHERE `id` IN(" . db::db_escape(implode(',', $fm['ids'])) . ")");
    db::db_query("DELETE FROM `" . DB_PREFIX . "products_promo` WHERE `product` IN(" . db::db_escape(implode(',', $fm['ids'])) . ")");
    db::db_query("DELETE FROM `" . DB_PREFIX . "affiliates_commissions` WHERE `product` IN(" . db::db_escape(implode(',', $fm['ids'])) . ")");
    db::db_query("DELETE FROM `" . DB_PREFIX . "affiliates_tracking` WHERE `product` IN(" . db::db_escape(implode(',', $fm['ids'])) . ")");
    db::db_truncate(array('products','products_promo','affiliates_commissions','affiliates_tracking'));
  }

}

?>