<?php

class api extends db {

  public $settings;
  public $dt;
  public $sys;
  public $loglang;
  public $json;
  public $data;
  public $affID;
  public $flag;

  // Use {ts} for timestamp..
  private $logfiles = array(
    'ref' => 'referrer-api-log.log',
    'com' => 'commission-api-log.log',
    'gen' => 'general-api-log.log',
    'data' => 'data-api-log.log'
  );
  
  public function commission($d = []) {
    if (substr($this->affID->commtier, -1) == '%') {
      $d['comm'] = mswNFMDec((substr($this->affID->commtier, 0, -1) * $d['sale']) / 100, 2);
    }
    db::db_query("INSERT INTO `" . DB_PREFIX . "affiliates_commissions` (
    `ts`,
    `affid`,
    `product`,
    `saletotal`,
    `commtotal`,
    `notes`,
    `approved`,
    `en`
    ) VALUES (
    '" . $this->dt->ts() . "',
    '{$this->affID->id}',
    '" . (int) $this->data['commission']['product'] . "',
    '" . db::db_escape($d['sale']) . "',
    '" . db::db_escape($d['comm']) . "',
    '" . (isset($this->data['commission']['notes']) ? db::db_escape($this->data['commission']['notes']) : '') . "',
    '" . ($this->settings->approve == 'yes' ? 'no' : 'yes') . "',
    'yes'
    )");
    $ID = db::db_last_insert_id();
    return array(
      'id' => $ID,
      'calc' => $d['comm']
    );
  }

  public function referral() {
    $ID = 0;
    if ($this->data['referrer']['url'] && $this->data['referrer']['product'] > 0) {
      $Q = db::db_query("SELECT `id` FROM `" . DB_PREFIX . "affiliates_tracking`
           WHERE `affid` = '{$this->affID->id}'
           AND `product` = '" . (int) $this->data['referrer']['product'] . "'
           AND `referrer` = '" . db::db_escape($this->data['referrer']['url']) . "'
           LIMIT 1
           ");
      $R = db::db_object($Q);
      if (isset($R->id)) {
        db::db_query("UPDATE `" . DB_PREFIX . "affiliates_tracking` SET
        `count`    = (`count` + 1)
        WHERE `id` = '{$R->id}'
        ");
        $ID = $R->id;
      } else {
        db::db_query("INSERT INTO `" . DB_PREFIX . "affiliates_tracking` (
        `affid`,
	      `product`,
	      `referrer`,
	      `count`
        ) VALUES (
        '{$this->affID->id}',
        '" . (int) $this->data['referrer']['product'] . "',
        '" . db::db_escape($this->data['referrer']['url']) . "',
        '1'
        )");
        $ID = db::db_last_insert_id();
      }
    }
    return $ID;
  }

  public function stream($c = false) {
    $stream = mswTmp('php://input');
    switch($c) {
      case true:
        return $stream;
        break;
      case false:
        $j = $this->json->decode($stream);
        return (isset($j['apikey'],$j['affiliate']) ? true : false);
        break;
    }
  }

  public function validate($aff) {
    $id  = 0;
    // Check for settings prefix..
    if ($aff && $this->settings->affcode && strtolower(substr($aff, 0, strlen($this->settings->affcode))) != strtolower($this->settings->affcode)) {
      return array(0, 'err-settings', new stdclass());
    }
    // Settings check done, so remove prefix..
    if ($this->settings->affcode) {
      $aff = str_replace($this->settings->affcode, '', $aff);
    }
    // If there is no hyphen, no prefixes are set so it`s just an ID..
    if (strpos($aff, '-') !== false) {
      // Explode into pieces, remembering that hyphen may have been added to prefix, so array could have
      //  more than 1 slot
      $chp = explode('-', $aff);
      // Add the pieces back..
      $aff = '';
      for($i=0; $i<count($chp); $i++) {
        // ID slot we ignore..
        if ($i != count($chp)-1) {
          $aff .= $chp[$i];
        }
      }
      $id  = (int) ltrim($chp[(count($chp)-1)], '0');
    } else {
      $id = (int) ltrim($aff, '0');
      $aff = '';
    }
    if ($id > 0) {
      $Q = db::db_query("SELECT * FROM `" . DB_PREFIX . "affiliates`
           WHERE `id` = '{$id}'
           AND `code` = '" . db::db_escape($aff) . "'
           AND `approved` = 'yes'
           AND `en` = 'yes'
           ");
      $A = db::db_object($Q);
      return (isset($A->id) ? array($A->id, 'ok', $A) : array(0, 'error-lookup', new stdclass()));
    }
    return array(0, 'error', new stdclass());
  }

  public function valprod($id) {
    $id = (int) $id;
    $Q = db::db_query("SELECT * FROM `" . DB_PREFIX . "products`
         WHERE `id` = '{$id}'
         AND `en` = 'yes'
         ");
    $P = db::db_object($Q);
    return (isset($P->id) ? array('ok', $P) : array('err'));
  }
  
  public function getData($d = [], $aff = 0) {
    $arr = [];
    switch($d['data']['op']) {
      case 'commissions':
        $Q = db::db_query("SELECT * FROM `" . DB_PREFIX . "affiliates_commissions`
             WHERE `affid` = '{$aff}'
             AND `approved` = 'yes'
             AND `en` = 'yes'
             " . (isset($d['data']['product']) ? 'AND `product` = \'' . (int) $d['data']['product'] . '\'' : '') . "
             GROUP BY `product`
             ORDER BY `product`
             ");
        while ($CO = db::db_object($Q)) {
          if (!isset($arr[$CO->product])) {
            $arr[$CO->product] = [];
          }
          $last = db::db_table('affiliates_commissions','affid', $aff, 'AND `product` = \'' . $CO->product . '\' AND `approved` = \'yes\' AND `en` = \'yes\' ORDER BY `id` DESC');
          $arr[$CO->product]['commissions'] = db::db_rowcount('affiliates_commissions', 'WHERE `affid` = \'' . $aff . '\' AND `product` = \'' . $CO->product . '\' AND `approved` = \'yes\' AND `en` = \'yes\'', false);
          $arr[$CO->product]['sale_total'] = db::db_sum('affiliates_commissions', 'saletotal', 'WHERE `affid` = \'' . $aff . '\' AND `product` = \'' . $CO->product . '\' AND `approved` = \'yes\' AND `en` = \'yes\'');
          $arr[$CO->product]['commission_total'] = db::db_sum('affiliates_commissions', 'commtotal', 'WHERE `affid` = \'' . $aff . '\' AND `product` = \'' . $CO->product . '\' AND `approved` = \'yes\' AND `en` = \'yes\'');
          $arr[$CO->product]['last_commission'] = (isset($last->ts) ? $last->ts : '0');
        }
        break;
      case 'payments':
        $Q = db::db_query("SELECT * FROM `" . DB_PREFIX . "affiliates_payments`
             WHERE `affid` = '{$aff}'
             GROUP BY `paymethod`
             ORDER BY `paymethod`
             ");
        while ($PY = db::db_object($Q)) {
          if (!isset($arr[$PY->paymethod])) {
            $arr[$PY->paymethod] = [];
          }
          $last = db::db_table('affiliates_payments','affid', $aff, 'AND `paymethod` = \'' . db::db_escape($PY->paymethod) . '\' ORDER BY `id` DESC');
          $arr[$PY->paymethod]['payments'] = db::db_rowcount('affiliates_payments', 'WHERE `affid` = \'' . $aff . '\' AND `paymethod` = \'' . db::db_escape($PY->paymethod) . '\'', false);
          $arr[$PY->paymethod]['payment_total'] = db::db_sum('affiliates_payments', 'payamount', 'WHERE `affid` = \'' . $aff . '\' AND `paymethod` = \'' . db::db_escape($PY->paymethod) . '\'');
          $arr[$PY->paymethod]['last_payment'] = (isset($last->ts) ? $last->ts : '0');
        }
        break;
      case 'referrals';
        $Q = db::db_query("SELECT * FROM `" . DB_PREFIX . "affiliates_tracking`
             WHERE `affid` = '{$aff}'
             " . (isset($d['data']['product']) ? 'AND `product` = \'' . (int) $d['data']['product'] . '\'' : '') . "
             GROUP BY `product`
             ORDER BY `product`
             ");
        while ($RF = db::db_object($Q)) {
          if (!isset($arr[$RF->product])) {
            $arr[$RF->product] = [];
          }
          $links = [];
          $Q2 = db::db_query("SELECT * FROM `" . DB_PREFIX . "affiliates_tracking`
                WHERE `affid` = '{$aff}'
                AND `product` = '{$RF->product}'
                ORDER BY `count` DESC
                ");
          while ($RFD = db::db_object($Q2)) {
            $links[] = array(
              'count' => $RFD->count,
              'link' => $RFD->referrer
            );
          }
          $arr[$RF->product]['referrers'] = $links;
        }
        break;
    }
    return $arr;
  }

  public function log($d = []) {
    if ($this->settings->apilog == 'yes') {
      $log   = [];
      $log[] = $this->loglang[0] . ': ' . date(($this->settings->dateformat ? $this->settings->dateformat : 'j F Y')) . ' @ ' . date(($this->settings->timeformat ? $this->settings->timeformat : 'h:iA'));
      $log[] = $this->loglang[1] . ': ' . mswIP();
      $log[] = $d['info'];
      $log[] = str_repeat('-', 75) . mswNL();
      if (is_dir(PATH . 'logs') && is_writeable(PATH . 'logs')) {
        $logf = $this->logfiles['gen'];
        if (in_array($this->flag, array('ref','com','data'))) {
          $logf = $this->logfiles[$this->flag];
        }
        mswPUT(PATH . 'logs/' . str_replace('{ts}', $this->dt->ts(), $logf), implode(mswNL(), $log));
      }
    }
  }

}

?>