<?php

//-----------------------------
// API HANDLER
//-----------------------------

$api_resp = array(
  'status' => 'error',
  'message' => 'A system error occurred, please contact us'
);

// Only if the aff_api constant is active is it a valid call..
try {
  if (defined('AFF_API') && isset($SETTINGS->sysstatus, $SETTINGS->apikey)) {
    if ($SETTINGS->sysstatus == 'yes') {
      if ($SETTINGS->apikey) {
        $api_inc = $JSON->decode($API->stream(true));
        if (isset($api_inc['apikey'],$api_inc['affiliate']) && $api_inc['apikey'] == $SETTINGS->apikey) {
          mswTO();
          if (!empty($api_inc['referrer'])) {
            $API->flag = 'ref';
          }
          if (!empty($api_inc['commission'])) {
            $API->flag = 'com';
          }
          if (!empty($api_inc['data'])) {
            $API->flag = 'data';
          }
          // Assign second var, so calls aren`t affected..
          $api_inc2 = $api_inc;
          $api_inc2['apikey'] = '******** (Masked for security)';
          $API->log(array(
            'info' => 'API data received: ' . mswNL() . mswNL() . print_r($api_inc2, true)
          ));
          $API->data = $api_inc;
          // Check affiliate..
          if ($api_inc['affiliate']) {
            $affID = $API->validate($api_inc['affiliate']);
            // Is affiliate code valid..
            if (isset($affID[0], $affID[1]) && $affID[0] > 0 && $affID[1] == 'ok' && isset($affID[2]->id)) {
              // Pass affiliate back to class..
              $API->affID = $affID[2];
              // API key not set..
              $api_inc['apikey'] = 'XXXXXX (Masked for security)';
              // Referrer..
              if (!empty($api_inc['referrer'])) {
                $API->flag = 'ref';
                if (isset($api_inc['referrer']['url'],$api_inc['referrer']['ip'],$api_inc['referrer']['product']) && $api_inc['referrer']['url']) {
                  $affProduct = $API->valprod($api_inc['referrer']['product']);
                  if ($affProduct[0] == 'ok') {
                    if ($SETTINGS->ipmatch == 'no' && isset($api_inc['referrer']['ip']) && $affID[2]->ip != '' && $api_inc['referrer']['ip'] == $affID[2]->ip) {
                      $api_resp['message'] = '[API - Referrer Error] Referrer IP address (' . $api_inc['referrer']['ip'] . ') is the same as the affiliate IP address. This is not allowed in your settings. Referral ignored. ';
                      $API->log(array('info' => $api_resp['message']));
                    } else {
                      // Update/add referral..
                      $refID = $API->referral();
                      if ($refID > 0) {
                        // Messages / logs..
                        $api_resp['status'] = 'ok';
                        $api_resp['message'] = '';
                        $api_resp['data'] = array(
                          'referralID' => $refID,
                          'affiliateID' => $affID[2]->id,
                          'productID' => $affProduct[1]->id,
                          'referralUrl' => $api_inc['referrer']['url'],
                          'affiliateName' => $affID[2]->fname . ' ' . $affID[2]->lname,
                          'affiliateEmail' => $affID[2]->email
                        );
                        $API->log(array(
                          'info' => 'Referrer <' . $api_inc['referrer']['url'] . '> updated/added for affiliate ID ' . $affID[0] . ' for product ID ' . $api_inc['referrer']['product']
                        ));
                      } else {
                        $api_resp['message'] = '[API - Referrer Error] Possible database error, check logs for more details.';
                        $API->log(array('info' => $api_resp['message']));
                      }
                    }
                  } else {
                    $api_resp['message'] = '[API - Referrer Error] Product ID (' . $api_inc['referrer']['product'] . ') is invalid or product is disabled.';
                    $API->log(array('info' => $api_resp['message']));
                  }
                } else {
                  $api_resp['message'] = '[API - Referrer Error] Referrer IP, Url or Product are invalid or not set.';
                  $API->log(array('info' => $api_resp['message']));
                }
              // Commission..
              } elseif (!empty($api_inc['commission'])) {
                $API->flag = 'com';
                $saleTotal = (isset($api_inc['commission']['saletotal']) ? mswFPCE($api_inc['commission']['saletotal']) : '0');
                $commTotal = (isset($api_inc['commission']['commtotal']) ? mswFPCE($api_inc['commission']['commtotal']) : '');
                if (isset($api_inc['commission']['product']) && $saleTotal > 0 && filter_var($saleTotal, FILTER_VALIDATE_FLOAT)) {
                  $affProduct = $API->valprod($api_inc['commission']['product']);
                  if ($affProduct[0] == 'ok') {
                    if (($commTotal == '' || $commTotal <= 0) && substr($affID[2]->commtier, -1) != '%') {
                      $api_resp['message'] = '[API - Commission Error] If affiliate override commission tier is blank, commission total must be set and have a value higher than 0';
                      $API->log(array('info' => $api_resp['message']));
                    } else {
                      if ($SETTINGS->ipmatch == 'no' && isset($api_inc['commission']['ip']) && $affID[2]->ip != '' && $api_inc['commission']['ip'] == $affID[2]->ip) {
                        $api_resp['message'] = '[API - Commission Error] Commission IP address (' . $api_inc['commission']['ip'] . ') is the same as the affiliate IP address. This is not allowed in your settings. Commission ignored. ';
                        $API->log(array('info' => $api_resp['message']));
                      } else {
                        // Update/add referral..
                        $data = $API->commission(array(
                          'sale' => $saleTotal,
                          'comm' => $commTotal
                        ));
                        if (isset($data['id']) && $data['id'] > 0) {
                          $api_resp['status'] = 'ok';
                          $api_resp['message'] = '';
                          $api_resp['data'] = array(
                            'commissionID' => $data['id'],
                            'affiliateID' => $affID[2]->id,
                            'productID' => $affProduct[1]->id,
                            'sale' => mswFPCE($saleTotal, true),
                            'commission' => mswFPCE($data['calc'], true),
                            'affiliateName' => $affID[2]->fname . ' ' . $affID[2]->lname,
                            'affiliateEmail' => $affID[2]->email,
                            'affiliateSetCommission' => $affID[2]->commtier
                          );
                          // Send emails..
                          $sendAff = (isset($api_inc['emails']['affiliate']) && in_array(strtolower($api_inc['emails']['affiliate']), array('yes','no')) ? strtolower($api_inc['emails']['affiliate']) : 'yes');
                          $sendAdm = (isset($api_inc['emails']['admin']) && in_array(strtolower($api_inc['emails']['admin']), array('yes','no')) ? strtolower($api_inc['emails']['admin']) : 'yes');
                          if ($sendAff == 'yes' || $sendAdm == 'yes') {
                            include(PATH . 'control/mail-init.php');
                            $MAILR->addTag('{NAME}', $affID[2]->fname . ' ' . $affID[2]->lname);
                            $MAILR->addTag('{FNAME}', $affID[2]->fname);
                            $MAILR->addTag('{LNAME}', $affID[2]->lname);
                            $MAILR->addTag('{EMAIL}', $affID[2]->email);
                            $MAILR->addTag('{AFF_ID}', $affID[2]->id);
                            $MAILR->addTag('{AFF_CODE}', mswAff($SETTINGS, $affID[2]));
                            $MAILR->addTag('{AFF_TIER}', ($affID[2]->commtier ? $affID[2]->commtier : '-'));
                            $MAILR->addTag('{SALE}', mswFPCE($saleTotal, true));
                            $MAILR->addTag('{COMMISSION}', mswFPCE($data['calc'], true));
                            $MAILR->addTag('{PRODUCT}', $affProduct[1]->name);
                            $MAILR->addTag('{PRODUCT_URL}', $affProduct[1]->url);
                            $MAILR->addTag('{CUSTOM}', (!empty($api_inc['custom']) ? print_r($api_inc['custom'], true) : ''));
                            $MAILR->addTag('{CURRENCY}', ($SETTINGS->currency ? $SETTINGS->currency : '-'));
                            $MAILR->addTag('{CURRENCY_NAME}', ($SETTINGS->currency && isset($currencies[$SETTINGS->currency]) ? $currencies[$SETTINGS->currency] : '-'));
                            // Affiliate..
                            if ($sendAff == 'yes') {
                              if ($SETTINGS->approve == 'no') {
                                $msg = mswTmp(MSW_EM_LANG . 'affiliate-commission-accepted.txt', 'yes');
                                $sbj = str_replace('{website}', $SETTINGS->website, $msw_emails8);
                              } else {
                                $msg = mswTmp(MSW_EM_LANG . 'affiliate-commission-approval.txt', 'yes');
                                $sbj = str_replace('{website}', $SETTINGS->website, $msw_emails9);
                              }
                              $MAILR->sendMail(array(
                                'from_email' => ($SETTINGS->smtp_email ? $SETTINGS->smtp_email : $SETTINGS->email),
                                'from_name' => ($SETTINGS->smtp_from ? $SETTINGS->smtp_from : $SETTINGS->website),
                                'to_email' => $affID[2]->email,
                                'to_name' => $affID[2]->fname . ' ' . $affID[2]->lname,
                                'subject' => $sbj,
                                'replyto' => array(
                                  'name' => ($SETTINGS->smtp_rfrom ? $SETTINGS->smtp_rfrom : $SETTINGS->website),
                                  'email' => ($SETTINGS->smtp_remail ? $SETTINGS->smtp_remail : $SETTINGS->email)
                                ),
                                'template' => $msg,
                                'alive' => 'yes',
                                'language' => $SETTINGS->language
                              ));
                              $API->log(array('info' => 'Email sent to ' . $affID[2]->fname . ' ' . $affID[2]->lname . ' <' . $affID[2]->email . '>'));
                            } else {
                              $API->log(array('info' => 'Affiliate email not sent, deactivated via API'));
                            }
                            // Admin..
                            if ($sendAdm == 'yes') {
                              $msg = mswTmp(MSW_EM_LANG . 'webmaster-commission-approval.txt', 'yes');
                              $sbj = str_replace('{website}', $SETTINGS->website, $msw_emails10);
                              $MAILR->sendMail(array(
                                'from_email' => ($SETTINGS->smtp_email ? $SETTINGS->smtp_email : $SETTINGS->email),
                                'from_name' => ($SETTINGS->smtp_from ? $SETTINGS->smtp_from : $SETTINGS->website),
                                'to_email' => $SETTINGS->email,
                                'to_name' => $SETTINGS->website,
                                'subject' => $sbj,
                                'replyto' => array(
                                  'name' => $affID[2]->fname . ' ' . $affID[2]->lname,
                                  'email' => $affID[2]->email
                                ),
                                'template' => $msg,
                                'language' => $SETTINGS->language
                              ));
                              $API->log(array('info' => 'Email sent to ' . $SETTINGS->website . ' <' . $SETTINGS->email . '>'));
                            } else {
                              $API->log(array('info' => 'Admin email not sent, deactivated via API'));
                            }
                            $MAILR->smtpClose();
                          } else {
                            $API->log(array('info' => 'Affiliate & admin emails not sent, deactivated via API'));
                          }
                          if (substr($affID[2]->commtier, -1) == '%') {
                            $API->log(array('info' => '[API - Commission OK] Commission ' . ($SETTINGS->approve == 'yes' ? 'requiring admin approval' : 'logged and accepted') . ' for affiliate ID ' . $affID[0] . ' for product ID ' . $api_inc['commission']['product'] . '. Sale total is ' . $saleTotal . ', Commission is ' . $data['calc'] . ' based on affiliate override commission tier of ' . $affID[2]->commtier));
                          } else {
                            $API->log(array('info' => '[API - Commission OK] Commission ' . ($SETTINGS->approve == 'yes' ? 'requiring admin approval' : 'logged and accepted') . ' for affiliate ID ' . $affID[0] . ' for product ID ' . $api_inc['commission']['product'] . '. Sale total is ' . $saleTotal . ', Commission is ' . $commTotal . ' based on received commission total'));
                          }
                        } else {
                          $api_resp['message'] = '[API - Commission Error] Possible database error, check logs for more details.';
                          $API->log(array('info' => $api_resp['message']));
                        }
                      }
                    }
                  } else {
                    $api_resp['message'] = '[API - Commission Error] Product ID (' . $api_inc['commission']['product'] . ') is invalid or product is disabled.';
                    $API->log(array('info' => $api_resp['message']));
                  }
                } else {
                  $api_resp['message'] = '[API - Commission Error] Sale total and/or product is not set, or sale total is 0';
                  $API->log(array('info' => $api_resp['message']));
                }
              // Data..
              } elseif (!empty($api_inc['data'])) {
                $API->flag = 'data';
                if (isset($api_inc['data']['op'])) {
                  switch(strtolower($api_inc['data']['op'])) {
                    case 'info':
                      $API->flag = 'data';
                      // Remove stuff for security..
                      unset($affID[2]->pass, $affID[2]->sys1, $affID[2]->sys2, $affID[2]->sys3);
                      $api_resp['status'] = 'ok';
                      $api_resp['message'] = '';
                      $api_resp['data'] = $affID[2];
                      $API->log(array('info' => '[API - Data OK] ' . mswNL() . print_r($api_resp, true)));
                      break;
                    case 'commissions':
                    case 'payments': 
                    case 'referrals':
                      $API->flag = 'data';
                      $data = $API->getData($api_inc, $affID[2]->id);
                      $api_resp['status'] = 'ok';
                      $api_resp['message'] = '';
                      $api_resp['data'] = $data;
                      $API->log(array('info' => '[API - Data OK] ' . mswNL() . print_r($api_resp, true)));
                      break;
                    default:
                      $api_resp['message'] = '[API - Error] Invalid "op" value: ' . $api_inc['data']['op'] . '. Please refer to API documentation (docs/api.html).';
                      $API->log(array('info' => $api_resp['message']));
                      break;
                  }
                } else {
                  $api_resp['message'] = '[API - Error] No "op" value set. Please refer to API documentation (docs/api.html).';
                  $API->log(array('info' => $api_resp['message']));
                }
              // Something else..
              } else {
                $api_resp['message'] = '[API - Error] Neither referrer or commission variable(s) are present. Please refer to API documentation (docs/api.html).';
                $API->log(array('info' => $api_resp['message']));
              }
            } else {
              $api_resp['message'] = '[API - Error] Affiliate code (' . $api_inc['affiliate'] . ') is invalid or affiliate is disabled.';
              $API->log(array('info' => $api_resp['message']));
            }
          } else {
            $api_resp['message'] = '[API - Error] Affiliate code is not set.';
            $API->log(array('info' => $api_resp['message']));
          }
        } else {
          // API key not set..
          $api_resp['message'] = '[API - Error] API key not set in code or incorrect. Please refer to API documentation (docs/api.html) and make sure correct API key is set.';
          $API->log(array('info' => $api_resp['message']));
        }
      } else {
        // API key not set..
        $api_resp['message'] = '[API - Error] API key not set, please add API key in settings.';
        $API->log(array('info' => $api_resp['message']));
      }
    } else {
      // Offline..
      $api_resp['message'] = '[API - Error] Affiliate system is offline, API call ignored.';
      $API->log(array('info' => $api_resp['message']));
    }
  }

  if ($api_resp['status'] == 'ok') {
    unset($api_resp['message']);
  }

  $SSN->kill();
  echo $JSON->encode($api_resp);

} catch(ErrorException $e) {
  $api_resp['message'] = $e->getMessage();
  $SSN->kill();
  echo $JSON->encode($api_resp);
}

?>