<?php

class accounts extends db {

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

  public function totals($data = []) {
    switch($data['area']) {
      case 'commissions':
        $q = db::db_query("SELECT ROUND(SUM(`commtotal`),2) AS `ct` FROM `" . DB_PREFIX . "affiliates_commissions` WHERE `approved` = 'yes' AND `en` = 'yes' AND `affid` = '{$data['id']}'");
        $r = db::db_object($q);
        return mswCRFMT(mswFPCE((isset($r->ct) ? $r->ct : '0.00'), true), $this->settings);
        break;
      case 'payments':
        $q = db::db_query("SELECT ROUND(SUM(`payamount`),2) AS `pa` FROM `" . DB_PREFIX . "affiliates_payments` WHERE `affid` = '{$data['id']}'");
        $r = db::db_object($q);
        return mswCRFMT(mswFPCE((isset($r->pa) ? $r->pa : '0.00'), true), $this->settings);
        break;
      case 'referrals':
        $q = db::db_query("SELECT SUM(`count`) AS `h` FROM `" . DB_PREFIX . "affiliates_tracking` WHERE `affid` = '{$data['id']}'");
        $r = db::db_object($q);
        return mswNFM((isset($r->h) ? $r->h : '0'));
        break;
      case 'uni-referrals':
        $q = db::db_query("SELECT COUNT(DISTINCT(`referrer`)) AS `h` FROM `" . DB_PREFIX . "affiliates_tracking` WHERE `affid` = '{$data['id']}'");
        $r = db::db_object($q);
        return mswNFM((isset($r->h) ? $r->h : '0'));
        break;
      case 'last_payment':
        $q = db::db_query("SELECT * FROM `" . DB_PREFIX . "affiliates_payments` WHERE `affid` = '{$data['id']}' ORDER BY `id` DESC LIMIT 1");
        $r = db::db_object($q);
        return (isset($r->ts) ? $this->dt->datedisplay($this->settings, $r->ts) : '-');
        break;
    }
  }

  public function affcode($aff) {
    return mswAff($this->settings, $aff);
  }

  public function close($id) {
    db::db_query("DELETE FROM `" . DB_PREFIX . "affiliates` WHERE `id` = '{$id}'");
    db::db_query("DELETE FROM `" . DB_PREFIX . "affiliates_commissions` WHERE `affid` = '{$id}'");
    db::db_query("DELETE FROM `" . DB_PREFIX . "affiliates_payments` WHERE `affid` = '{$id}'");
    db::db_query("DELETE FROM `" . DB_PREFIX . "affiliates_tracking` WHERE `affid` = '{$id}'");
    db::db_truncate(array('affiliates','affiliates_commissions','affiliates_payments','affiliates_tracking'));
  }

  public function login() {
    if ($this->ssn->active('aff-' . mswEnc($this->settings->email . SECRET_KEY) . '-key') == 'yes') {
      $keys = explode(',', $this->ssn->get('aff-' . mswEnc($this->settings->email . SECRET_KEY) . '-key'));
      if (isset($keys[0], $keys[1])) {
        if (mswEmVal($keys[0]) == 'yes') {
          $accnt = accounts::account(array(
            '`id` = \'' . (int) $keys[1] . '\'',
            '`email` = \'' . db::db_escape($keys[0]) . '\'',
            '`en` = \'yes\'',
            '`approved` = \'yes\''
          ), 'array');
          if (isset($accnt['id'])) {
            // Update IP if blank..
            if ($accnt['ip'] == '') {
              db::db_query("UPDATE `" . DB_PREFIX . "affiliates` SET `ip` = '" . db::db_escape(mswIP()) . "' WHERE `id` = '{$accnt['id']}'");
            }
            return $accnt;
          }
        }
      }
    }
    return [];
  }

  public function account($data = [], $ret = 'object') {
    $sql = [];
    if (!empty($data)) {
      foreach ($data AS $query) {
        $sql[] = (empty($sql) ? 'WHERE ' : 'AND ') . $query;
      }
      $q = db::db_query("SELECT * FROM `" . DB_PREFIX . "affiliates` " . (!empty($sql) ? implode(mswNL(), $sql) : ''));
      switch($ret) {
        case 'object':
          return db::db_object($q);
          break;
        case 'array':
          return db::db_array($q);
          break;
      }
    }
    return new stdclass();
  }

  public function add($fm, $p, $c) {
    db::db_query("INSERT INTO `" . DB_PREFIX . "affiliates` (
    `ts`,
    `fname`,
    `lname`,
    `email`,
    `pass`,
    `ip`,
    `en`
    ) VALUES (
    '" . $this->dt->ts() . "',
    '" . db::db_escape($fm['first_name']) . "',
    '" . db::db_escape($fm['last_name']) . "',
    '" . db::db_escape($fm['email']) . "',
    '" . mswPassHash(array('type' => 'add', 'pass' => $p)) . "',
    '" . db::db_escape(mswIP()) . "',
    'yes'
    )");
    $ID = db::db_last_insert_id();
    // If not admin approved, visitor must verify by email..
    if ($this->settings->approveaff == 'no') {
      db::db_query("UPDATE `" . DB_PREFIX . "affiliates` SET `sys2` = '" . db::db_escape($c) . "' WHERE `id` = '{$ID}'");
    }
  }

  public function update($data = [], $where = '') {
    $sql = [];
    if (!empty($data) && $where) {
      foreach ($data AS $query) {
        $sql[] = $query;
      }
      db::db_query("UPDATE `" . DB_PREFIX . "affiliates` SET " . (!empty($sql) ? implode(',', $sql) : '') . " WHERE " . $where);
      return db::db_aff_rows();
    }
    return '0';
  }

  public function pass($special = 'yes', $max = 0) {
    $pass = '';
    $a1 = range('A','Z');
    $a2 = range('a','z');
    $a3 = range(0, 9);
    $a4 = ($special == 'yes' ? array('[', ']', '&', '*', '(', ')', '#', '!', '%', '@', '^') : []);
    $sec = array_merge($a1, $a2, $a3, $a4);
    shuffle($sec);
    for ($i = 0; $i < count($sec); $i++) {
      $rand = rand(0, (count($sec) - 1));
      $char = $sec[$rand];
      $pass .= $char;
      if ($max > 0) {
        if ($max == ($i + 1)) {
          return $pass;
        }
      } else {
        if (((int) MIN_AUTO_PASS_LENGTH > 0 ? (int) MIN_AUTO_PASS_LENGTH : 10) == ($i + 1)) {
          return $pass;
        }
      }
    }
    return $pass;
  }

}

?>