<?php
defined('COT_CODE') or die('Wrong URL');

$return = array(
  'success' => false,
  'upd_cnt' => 0,
  'unitpay_tax_sync' => 0,
  'unitpay_massPayment' => 0,
  'unitpay_massPaymentStatus' => 0,
);

if(cot_plugin_active('marketorders')) {
  $return['success'] = true;
  $mk_cache_upd = 10800; //TODO config 3 часа

  $updusrs = $db->query("SELECT * FROM $db_users WHERE user_usergroup=4 AND user_maingrp>3 AND (user_mk_cache_upd=0 OR user_mk_cache_upd<".($sys['now'] - $mk_cache_upd).") LIMIT 10")->fetchAll();
  if(count($updusrs) == 0) $updusrs = $db->query("SELECT * FROM $db_users WHERE user_usergroup=4 AND user_maingrp>3 AND (user_mk_cache_upd=0 OR user_mk_cache_upd<".($sys['now'] - 86400).") ORDER BY user_mk_cache_upd ASC LIMIT 5")->fetchAll();

  if(count($updusrs) > 0) {
    foreach($updusrs as $urr) {
      $anlt_arr = cot_mk_update_analytics(array($urr), 1);
      $ruserupd = $anlt_arr[$urr['user_id']]['ruserupd'];

      if(count($ruserupd) > 0) {
        $db->update($db_users, $ruserupd, 'user_id='.$urr['user_id']);
        $return['upd_cnt']++;
      }
    }
  }
}

if(cot_plugin_active('unitpay') && $cfg['plugin']['unitpay']['unitpay_payouts']) {
  require_once cot_incfile('payments', 'module');
  require_once cot_incfile('unitpay', 'plug');

  $payouts = $db->query("SELECT * FROM $db_payments_outs AS o
  	LEFT JOIN $db_users AS u ON u.user_id=o.out_userid
  	LEFT JOIN $db_payments AS p ON p.pay_code=o.out_id AND p.pay_area='payout'
  	WHERE out_status='process'")->fetchAll();

  foreach($payouts as $payo) {
    $payout_summ = cot_payment_get_payout_summ_withtax($payo['out_summ'], $payo['out_type']);
    $payout_tax = $payo['out_summ'] - $payout_summ;

    $url = 'https://unitpay.ru/api?method=massPayment';
    $paysend = array(
                'params' => array(
                  'transactionId' => $payo['out_id'],
                  'login' => $cfg['plugin']['unitpay']['unitpay_login'],
                  'secretKey' => $cfg['plugin']['unitpay']['unitpay_partnerkey'],
                  'sum' => (float)$payout_summ,
                  'purse' => $payo['out_wallet'],
                  'paymentType' => $payo['out_type'],
                 )
               );

    if($payo['out_unitpay_id'] > 0) {
      $url = 'https://unitpay.ru/api?method=massPaymentStatus';
      $paysend = array(
                  'params' => array(
                    'transactionId' => $payo['out_id'],
                    'login' => $cfg['plugin']['unitpay']['unitpay_login'],
                    'secretKey' => $cfg['plugin']['unitpay']['unitpay_partnerkey'],
                   )
                 );
      $return['unitpay_massPaymentStatus']++;
    } else {
      $return['unitpay_massPayment']++;
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($paysend));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);

    $response = (!empty($response) ? json_decode($response, 1) : array());

    if(is_array($response)) {
      if(is_array($response['result'])) {
        $response = $response['result'];
        if($response['payoutId'] > 0) {
          $rout = array(
            'out_unitpay_id' => $response['payoutId']
          );

          if($response['status'] == 'success') {
            $rout['out_status'] = 'done';
            $rout['out_date'] = $sys['now'];
            $rout['out_tax'] = $payout_tax;
          }

          $db->update($db_payments_outs, $rout, 'out_id='.$payo['out_id']);
        }
      } elseif(is_array($response['error'])) {
        $response = $response['error'];

        $rout = array();
    		$rout['out_date'] = $sys['now'];
    		$rout['out_status'] = 'canceled';
        $rout['out_error'] = $response['message'];

    		if($db->update($db_payments_outs, $rout, "out_id=".$payo['out_id']))
    		{
    			$payinfo['pay_userid'] = $payo['out_userid'];
    			$payinfo['pay_area'] = 'balance';
    			$payinfo['pay_code'] = $payo['out_id'];
    			$payinfo['pay_summ'] = $payo['pay_summ'];
    			$payinfo['pay_cdate'] = $sys['now'];
    			$payinfo['pay_pdate'] = $sys['now'];
    			$payinfo['pay_adate'] = $sys['now'];
    			$payinfo['pay_status'] = 'done';
    			$payinfo['pay_desc'] = $L['payments_balance_payout_cancel_desc'];

    			$db->insert($db_payments, $payinfo);

     			// Отправка уведомления об отмене заявки
    			$subject = $L['payments_balance_payout_cancel_subject'];
    			$body = sprintf($L['payments_balance_payout_cancel_body'], $payo['user_name'], $payo['out_id']);
    			cot_mail($payo['user_email'], $subject, $body);
    		}
      }
    }
  }
}

if(cot_module_active('ds')) {
  require_once cot_incfile('ds', 'module');
  require_once cot_langfile('ds', 'module');

  $sql = $db->query("SELECT COUNT(id) AS messagescount, max(m.id) AS new_last, u.* FROM $db_ds_msg AS m
	 LEFT JOIN $db_users AS u ON u.user_id=m.touser
   WHERE m.status='1' AND m.id > u.user_lastmsg GROUP BY m.touser");

  foreach($sql->fetchAll() as $send_urr)
  {
    $res = TRUE;
	  if (is_array($cot_usersonline))
	  {
		  $res = (in_array($send_urr['user_id'], $cot_usersonline)) ? FALSE : TRUE;
	  }
    if ($res)
    {
      $tags = $send_urr;
      $rbody = cot_rc($L['ds_mail_first'], $tags).cot_declension($send_urr['messagescount'], $L['Privatemessages']).'.';
      cot_mail($send_urr['user_email'], '', $rbody);

      $db->update($db_users, array('user_lastmsg' => $send_urr['new_last']), "user_id=".$send_urr['user_id']);
    }
  }

  if(cot_plugin_active('banlist')) {
    require_once cot_langfile('banlist', 'plug');
    cot::$db->registerTable('banlist');

    $banmsg = 0;
    $banuser = 0;
    $banarr = array(
          			'banlist_ip' => '',
                'banlist_date' => $sys['now'],
          			'banlist_email' => '',
          			'banlist_reason' => '',
          			'banlist_howlong' => 0,
                'banlist_iswarning' => 0,
                'banlist_expire' => 0,
                'banlist_active' => 1,

                'banlist_reason_foruser' => 'Уважаемый пользователь!<br>Ваши услуги временно заблокированны, просьба связаться с тех поддержкой.',
                'banlist_show_support_btn' => 1,

                'banlist_block_ds' => 0,
                'banlist_block_market_buyer' => 0,
                'banlist_block_market_seller' => 1,
                'banlist_block_projects_buyer' => 0,
                'banlist_block_projects_seller' => 0,
        			);

    //$banarr['banlist_email'] = $banurr['user_name'];
    //$banarr['banlist_reason'] = 'Игнорирование на сообщение от пользователя '.$urr['user_name'];

    $blockdialogs = $db->query("SELECT * FROM $db_ds_dialog WHERE fromid>0 AND toid>0 AND lastmsg<".($sys['now'] - $cfg['ds']['waitanswer24hour_time']['time']).' AND lastban<'.($sys['now'] - ($cfg['ds']['waitanswer24hour_time']['time'] / 2)))->fetchAll();
    foreach($blockdialogs as $row) {
      $banmsg = 0;
      $banuser = 0;

      $tourr = ($row['toid'] > 0 ? $db->query("SELECT * FROM $db_users WHERE user_id=".$row['toid']." LIMIT 1")->fetch() : array('user_id' => 0));
      $fromurr = ($row['fromid'] > 0 ? $db->query("SELECT * FROM $db_users WHERE user_id=".$row['fromid']." LIMIT 1")->fetch() : array('user_id' => 0));

      if($tourr['user_id'] > 0 && $fromurr['user_id'] > 0) {
        $dstate_update = array();
        $dstate_needupdate = false;

        $dstate = cot_ds_dstate(0, $row);

        $bannedmsgs = array();

        if(is_array($dstate['waitanswer24hour'])) foreach($dstate['waitanswer24hour'] as $mfastansw) {
          if(!$banmsg && !$mfastansw['lowrtg'] && $mfastansw['date'] < ($sys['now'] - $cfg['ds']['waitanswer24hour_time']['time'])) {
            $banmsg = $mfastansw['mid'];
            if($banmsg > 0) {
              $tmsg = $db->query("SELECT * FROM $db_ds_msg WHERE id=".$banmsg)->fetch();
              if($tmsg['id'] > 0) {
                $banuser = ($tmsg['touser'] == $tourr['user_id'] ? $tourr['user_id'] : $fromurr['user_id']);

                $mfastansw['lowrtg'] = 1;
                $dstate_needupdate = 1;
              } else {
                $banmsg = 0;
              }
            }
          }
          if($mfastansw['mid'] > 0 && $mfastansw['lowrtg']) {
            $bannedmsgs[$mfastansw['uid']] = $mfastansw['mid'];
          }
          $dstate_update[] = $mfastansw;
        }

        /*
        if(!$banmsg) {
          $lastmsg = $db->query("SELECT * FROM $db_ds_msg WHERE dialog=".$row['id'].(count($bannedmsgs) > 0 ? ' AND id>'.max($bannedmsgs) : '').' AND date<'.($sys['now'] - $cfg['ds']['waitanswer24hour_time']['time']).' ORDER BY date DESC LIMIT 1')->fetch();

          if($lastmsg['id'] > 0) {
            if($db->query("SELECT COUNT(*) FROM $db_ds_msg WHERE dialog=".$row['id'].' AND touser='.$tourr['user_id'])->fetchColumn() == 0) {
              $banuser = $fromurr['user_id'];
            } elseif($db->query("SELECT COUNT(*) FROM $db_ds_msg WHERE dialog=".$row['id'].' AND touser='.$fromurr['user_id'])->fetchColumn() == 0) {
              $banuser = $tourr['user_id'];
            } elseif($lastmsg['status'] && $sys['now']-$db->query("SELECT date FROM $db_ds_msg WHERE dialog=".$row['id'].' AND touser!='.$lastmsg['touser'].' ORDER BY date DESC LIMIT 1')->fetchColumn() > 86400*20) {
              $banuser = $lastmsg['touser'];
            }

            if($banuser > 0) {
              $banmsg = $lastmsg['id'];
              $dstate_update[] = array(
                'mid' => $lastmsg['id'],
                'uid' => $lastmsg['fruser'],
                'date' => $lastmsg['date'],
                'lowrtg' => 1,
              );
              $dstate_needupdate = 1;
            }
          }
        }
        */

        if($banmsg > 0) {
          if($dstate_needupdate) {
            $dstate['waitanswer24hour'] = $dstate_update;
            $db->update($db_ds_dialog, array('dstate' => json_encode($dstate)), "id = ".(int)$row['id']."");
          }

          if($banuser == $tourr['user_id']) {
            $banarr['banlist_email'] = $tourr['user_name'];
            $banarr['banlist_reason'] = 'Игнорирование на сообщение (#'.$banmsg.') от пользователя '.$fromurr['user_name'];
          } else {
            $banarr['banlist_email'] = $fromurr['user_name'];
            $banarr['banlist_reason'] = 'Игнорирование на сообщение (#'.$banmsg.') от пользователя '.$tourr['user_name'];
          }

          $db->insert($db_banlist, $banarr);
        }
      }

      if(!$banmsg) $db->update($db_ds_dialog, array('lastban' => $sys['now']), 'id='.$row['id']);
    }
  }
}

?>
