<?php

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

class commissions extends db {

  public $dt;
  public $settings;
  public $sys;
  private $csv_sep = ',';

  public function export($fm) {
    $data = [];
    $csv  = '';
    $file = SYS_TEMP_DIR . 'export-commissions-' . ($fm['id'] > 0 ? 'affiliate-' . $fm['id'] . '-' : '') . $this->dt->ts() . '.csv';
    $this->sys->fileclear(PATH . 'backup', '.csv');
    if (isset($_GET['sf'])) {
      foreach (array('sf','cf','prod','aff','tsf','notes','sort') AS $sK) {
        switch($sK) {
          case 'tsf':
            if (isset($_GET[$sK],$_GET['tst']) && $this->dt->jstots($_GET[$sK]) > 0 && $this->dt->jstots($_GET['tst']) > 0) {
              $search_sql[] = (empty($search_sql) ? 'WHERE (' : 'AND (') . "DATE(FROM_UNIXTIME(`ts`)) >= '" . date('Y-m-d', $this->dt->jstots($_GET[$sK])) . "' AND DATE(FROM_UNIXTIME(`ts`)) <= '" . date('Y-m-d', $this->dt->jstots($_GET['tst'])) . "')";
            }
            break;
          case 'sf':
          case 'cf':
            if ($sK == 'sf') {
              if (isset($_GET[$sK],$_GET['st']) && mswNFM($_GET[$sK]) && mswNFM($_GET['tst']) != '0.00') {
                $search_sql[] = (empty($search_sql) ? 'WHERE (' : 'AND (') . "`saletotal` >= " . db::db_escape($_GET[$sK]) . " AND `saletotal` <= " . db::db_escape($_GET['st']) . ")";
              }
            } else {
              if (isset($_GET[$sK],$_GET['ct']) && $_GET[$sK] && $_GET['ct'] && mswNFM($_GET['ct']) != '0.00') {
                $search_sql[] = (empty($search_sql) ? 'WHERE (' : 'AND (') . "`commtotal` >= " . db::db_escape($_GET[$sK]) . " AND `commtotal` <= " . db::db_escape($_GET['ct']) . ")";
              }
            }
            break;
          case 'prod':
          case 'aff':
            if ($sK == 'prod') {
              if (!empty($_GET[$sK])) {
                $search_sql[] = (empty($search_sql) ? 'WHERE (' : 'AND (') . "`product` IN(" . db::db_escape(implode(',',$_GET[$sK])) . "))";
              }
            } else {
              if (!empty($_GET[$sK])) {
                $search_sql[] = (empty($search_sql) ? 'WHERE (' : 'AND (') . "`affid` IN(" . db::db_escape(implode(',',$_GET[$sK])) . "))";
              }
            }
            break;
          case 'sort':
            if (isset($_GET[$sK]) && in_array($_GET[$sK], array_keys($fm['sort']['options']))) {
              $fm['sort']['def'] = $_GET[$sK];
            }
            break;
          default:
            if (isset($_GET[$sK]) && $_GET[$sK]) {
              $search_sql[] = (empty($search_sql) ? 'WHERE (' : 'AND (') . "`" . $sK . "` LIKE '%" . db::db_escape($_GET[$sK]) . "%')";
            }
            break;
        }
      }
      if (empty($search_sql)) {
        return array($csv, $file);
      } else {
        $search_sql[] = "AND (`en` = 'yes' AND `approved` = 'yes')";
        // Order by..
        switch((in_array($fm['sort']['def'], array_keys($fm['sort']['options'])) ? $fm['sort']['def'] : 'name_asc')) {
          case 'date_asc': $orderBy = '`ts`'; break;
          case 'date_desc': $orderBy = '`ts` DESC'; break;
          case 'name_asc': $orderBy = '`affName`'; break;
          case 'name_desc': $orderBy = '`affName` DESC'; break;
          case 'product_asc': $orderBy = '`productName`'; break;
          case 'product_desc': $orderBy = '`productName` DESC'; break;
          case 'sale_asc': $orderBy = '`saletotal`  * 100'; break;
          case 'sale_desc': $orderBy = '`saletotal` * 100 DESC'; break;
          case 'comm_asc': $orderBy = '`commtotal` * 100'; break;
          case 'comm_desc': $orderBy = '`commtotal` * 100 DESC'; break;
        }
        $Q  = db::db_query("SELECT *,
              (SELECT CONCAT(`fname`,' ',`lname`) FROM `" . DB_PREFIX . "affiliates` WHERE `" . DB_PREFIX . "affiliates`.`id` = `" . DB_PREFIX . "affiliates_commissions`.`affid`) AS `affName`,
              (SELECT `name` FROM `" . DB_PREFIX . "products` WHERE `" . DB_PREFIX . "products`.`id` = `" . DB_PREFIX . "affiliates_commissions`.`product`) AS `productName`
              FROM `" . DB_PREFIX . "affiliates_commissions`
              " . implode(mswNL(), $search_sql) . "
              ORDER BY " . $orderBy
              );
      }
    } else {
      $sql  = ($fm['id'] > 0 ? 'WHERE (`en` = \'yes\' AND `approved` = \'yes\' AND `affid` = \'' . $fm['id'] . '\') ' : 'WHERE (`en` = \'yes\' AND `approved` = \'yes\') ');
      if ($fm['q']) {
        $sql .= "AND (`saletotal` LIKE '%" . db::db_escape($fm['q']) . "%' OR `commtotal` LIKE '%" . db::db_escape($fm['q']) . "%' OR `notes` LIKE '%" . db::db_escape($fm['q']) . "%')";
      }
      $Q  = db::db_query("SELECT *,
            (SELECT CONCAT(`fname`,' ',`lname`) FROM `" . DB_PREFIX . "affiliates` WHERE `" . DB_PREFIX . "affiliates`.`id` = `" . DB_PREFIX . "affiliates_commissions`.`affid`) AS `affName`,
            (SELECT `name` FROM `" . DB_PREFIX . "products` WHERE `" . DB_PREFIX . "products`.`id` = `" . DB_PREFIX . "affiliates_commissions`.`product`) AS `productName`
            FROM `" . DB_PREFIX . "affiliates_commissions`
            $sql
            ORDER BY `id` DESC"
            );
    }
    while ($CM = db::db_object($Q)) {
      $data[] = mswCSV(mswCD($CM->affName)) . $this->csv_sep .
      mswCSV(mswCD($CM->productName)) . $this->csv_sep .
      mswCSV($this->dt->datedisplay($this->settings, $CM->ts)) . $this->csv_sep .
      mswCSV(mswFPCE($CM->saletotal, true)) . $this->csv_sep .
      mswCSV(mswFPCE($CM->commtotal, true)) . $this->csv_sep .
      mswCSV($CM->notes);
    }
    if (!empty($data)) {
      $csv = $fm['header'] . mswNL() . implode(mswNL(), $data);
      mswPUT($file, $csv);
    }
    return array($csv, $file);
  }

  public function add($fm) {
    db::db_query("INSERT INTO `" . DB_PREFIX . "affiliates_commissions` (
    `ts`,
    `affid`,
    `product`,
    `saletotal`,
    `commtotal`,
    `notes`,
    `approved`,
    `en`
    ) VALUES (
    '{$fm['ts']}',
    '{$fm['aff_id']}',
    '{$fm['product']}',
    '" . db::db_escape($fm['saletotal']) . "',
    '" . db::db_escape($fm['commtotal']) . "',
    '" . db::db_escape($fm['notes']) . "',
    'yes',
    'yes'
    )");
    $ID = db::db_last_insert_id();
    return $ID;
  }

  public function update($fm) {
    db::db_query("UPDATE `" . DB_PREFIX . "affiliates_commissions` SET
    `ts`        = '{$fm['ts']}',
    `affid`     = '{$fm['aff_id']}',
    `product`   = '{$fm['product']}',
    `saletotal` = '" . db::db_escape($fm['saletotal']) . "',
    `commtotal` = '" . db::db_escape($fm['commtotal']) . "',
    `notes`     = '" . db::db_escape($fm['notes']) . "'
    WHERE `id` = '{$fm['id']}'
    ");
  }

  public function activate($fm) {
    if (!empty($fm['ids'])) {
      db::db_query("UPDATE `" . DB_PREFIX . "affiliates_commissions` SET
      `approved` = 'yes',
      `en`       = 'yes'
      WHERE `id` IN(" . db::db_escape(implode(',', $fm['ids'])) . ")
      ");
    }
  }

  public function delete($fm) {
    if (!empty($fm['ids'])) {
      db::db_query("DELETE FROM `" . DB_PREFIX . "affiliates_commissions` WHERE `id` IN(" . db::db_escape(implode(',', $fm['ids'])) . ")");
      db::db_truncate(array('affiliates_commissions'));
    }
  }

}

?>