<?php

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

class payments extends db {

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

  public function export($fm) {
    $data = [];
    $csv  = '';
    $file = SYS_TEMP_DIR . 'export-payments-' . ($fm['id'] > 0 ? 'affiliate-' . $fm['id'] . '-' : '') . $this->dt->ts() . '.csv';
    $this->sys->fileclear(PATH . 'backup', '.csv');
    if (isset($_GET['tsf'])) {
      foreach (array('tsf','pf','aff','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 'pf':
            if (isset($_GET[$sK],$_GET['st']) && mswNFM($_GET[$sK]) && mswNFM($_GET['pt']) != '0.00') {
              $search_sql[] = (empty($search_sql) ? 'WHERE (' : 'AND (') . "`payamount` >= " . db::db_escape($_GET[$sK]) . " AND `payamount` <= " . db::db_escape($_GET['pt']) . ")";
            }
            break;
          case 'aff':
            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 {
        // Order by..
        switch((in_array($fm['sort']['def'], array_keys($fm['sort']['options'])) ? $fm['sort']['def'] : 'date_asc')) {
          case 'date_asc': $orderBy = '`ts`'; break;
          case 'date_desc': $orderBy = '`ts` DESC'; break;
          case 'aff_asc': $orderBy = '`affName`'; break;
          case 'aff_desc': $orderBy = '`affName` DESC'; break;
          case 'pay_asc': $orderBy = '`payamount` * 100'; break;
          case 'pay_desc': $orderBy = '`payamount` * 100 DESC'; break;
          case 'method_asc': $orderBy = '`paymethod`'; break;
          case 'method_desc': $orderBy = '`paymethod` DESC'; break;
        }
        $Q  = db::db_query("SELECT *,
              (SELECT CONCAT(`fname`,' ',`lname`) FROM `" . DB_PREFIX . "affiliates` WHERE `" . DB_PREFIX . "affiliates`.`id` = `" . DB_PREFIX . "affiliates_payments`.`affid`) AS `affName`
              FROM `" . DB_PREFIX . "affiliates_payments`
              " . implode(mswNL(), $search_sql) . "
              ORDER BY " . $orderBy
              );
      }
    } else {
      $sql  = ($fm['id'] > 0 ? 'WHERE (`affid` = \'' . $fm['id'] . '\')' : '');
      if ($fm['q']) {
        $sql .= ($SQL ? 'AND ' : 'WHERE ') . "(`payamount` LIKE '%" . db::db_escape($fm['q']) . "%' OR `paymethod` 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_payments`.`affid`) AS `affName`
            FROM `" . DB_PREFIX . "affiliates_payments`
            $sql
            ORDER BY `ts` DESC,`id` DESC
            ");
    }
    while ($PY = db::db_object($Q)) {
      $data[] = mswCSV($PY->affName) . $this->csv_sep .
      mswCSV($this->dt->datedisplay($this->settings, $PY->ts)) . $this->csv_sep .
      mswCSV(mswFPCE($PY->payamount, true)) . $this->csv_sep .
      mswCSV(mswCD($PY->paymethod)) . $this->csv_sep .
      mswCSV($PY->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_payments` (
    `ts`,
    `affid`,
    `payamount`,
    `paymethod`,
    `notes`
    ) VALUES (
    '{$fm['ts']}',
    '{$fm['aff_id']}',
    '" . db::db_escape($fm['payamount']) . "',
    '" . db::db_escape($fm['paymethod']) . "',
    '" . db::db_escape($fm['notes']) . "'
    )");
    $ID = db::db_last_insert_id();
    return $ID;
  }

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

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

}

?>