<?php

/**
 * [BEGIN_COT_EXT]
 * Hooks=global
 * [END_COT_EXT]
 */

/**
 * marketorders plugin
 *
 * @package marketorders
 * @version 1.0.0
 * @author CMSWorks Team
 * @copyright Copyright (c) CMSWorks.ru
 * @license BSD
 */

defined('COT_CODE') or die('Wrong URL.');

require_once cot_incfile('marketorders', 'plug');
require_once cot_incfile('market', 'module');
require_once cot_incfile('payments', 'module');

if ($marketpays = cot_payments_getallpays('market_payorder', 'paid'))
{
	foreach ($marketpays as $pay)
	{
		if ($pay['pay_code'] > 0)
		{
  		$marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
  			WHERE order_id=".$pay['pay_code'])->fetch();

      if($marketorder['order_id'] > 0) {
        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
          if($marketorder['order_cid'] > 0) $db->delete($db_market_citems, 'ci_id='.$marketorder['order_cid']);
    			$db->update($db_market_orders,  array('order_paid' => (int)$sys['now'], 'order_status' => 'paid', 'order_tax' => $market_crt), "order_id=".(int)$marketorder['order_id']);

    			$seller = $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_seller'])->fetch();
    			if($marketorder['order_userid'] > 0)
    			{
    				$customer = $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_userid'])->fetch();
    			}
    			else
    			{
    				$customer['user_name'] = $marketorder['order_email'];
    				$customer['user_email'] = $marketorder['order_email'];
    			}

          $indodji = 0;
          $summdodji = 0;
    			$summ = $marketorder['order_cost'] - $marketorder['order_cost']*($market_crt/100);
          if($marketorder['order_cost_dodji'] > 0) {
            $indodji = 1;
      			$summdodji = $marketorder['order_cost_dodji'] - $marketorder['order_cost_dodji']*($market_crt/100);
          }

    			// Уведопляем продавца о совершении покупки его товара
    			$rsubject = cot_rc($L['marketorders_paid_mail_toseller_header'], array('order_id' => $marketorder['order_id'], 'product_title' => $marketorder['item_title']));
    			$rbody = cot_rc($L['marketorders_paid_mail_toseller_body'], array(
    				'user_name' => $customer['user_name'],
    				'product_id' => $marketorder['item_id'],
    				'product_title' => $marketorder['item_title'],
    				'order_id' => $marketorder['order_id'],
    				'summ' => ($indodji ? $summdodji.' '.$cfg['payments']['valutadodji'] : $summ.' '.$cfg['payments']['valuta']),
    				'tax' => $market_crt,
    				'warranty' => $cfg['plugin']['marketorders']['warranty'],
    				'sitename' => $cfg['maintitle'],
    				'link' => COT_ABSOLUTE_URL . cot_url('marketorders', "id=" . $marketorder['order_id'], '', true)
    			));
    			cot_mail($seller['user_email'], $rsubject, $rbody);

    			// Уведопляем покупателя о совершении покупки

    			$rsubject = cot_rc($L['marketorders_paid_mail_tocustomer_header'], array('order_id' => $marketorder['order_id'], 'product_title' => $marketorder['item_title']));
    			$rbody = cot_rc($L['marketorders_paid_mail_tocustomer_body'], array(
    				'user_name' => $customer['user_name'],
    				'product_id' => $marketorder['item_id'],
    				'product_title' => $marketorder['item_title'],
    				'order_id' => $marketorder['order_id'],
    				'cost' => ($indodji ? $marketorder['order_cost_dodji'].' '.$cfg['payments']['valutadodji'] : $marketorder['order_cost'].' '.$cfg['payments']['valuta']),
    				'tax' => $market_crt,
    				'warranty' => $cfg['plugin']['marketorders']['warranty'],
    				'sitename' => $cfg['maintitle'],
    				'link' => COT_ABSOLUTE_URL . cot_url('marketorders', "id=" . $marketorder['order_id'], '', true)
    			));
    			cot_mail ($customer['user_email'], $rsubject, $rbody);

    			/* === Hook === */
    			foreach (cot_getextplugins('marketorders.order.paid') as $pl)
    			{
    				include $pl;
    			}
    			/* ===== */

          $tid_to = cot_mk_addtrack($marketorder['order_id'], 'order_paid', 0, $marketorder['order_userid'], array());
          $tid = cot_mk_addtrack($marketorder['order_id'], 'order_paid', 0, $marketorder['order_seller'], array(), 0, $tid_to);

          cot_mk_reset_analytics($marketorder['order_seller']);
        }
      } else {
        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
  				$payinfo['pay_userid'] = $pay['pay_userid'];
  				$payinfo['pay_area'] = 'balance';
  				$payinfo['pay_code'] = 'market_reftocust_emptyitem:'.$pay['pay_code'];
  				$payinfo['pay_summ'] = $pay['pay_summ'];
          $payinfo['pay_paydodji'] = $pay['pay_paydodji'];
      	  $payinfo['pay_dodji'] = $pay['pay_dodji'];
  				$payinfo['pay_cdate'] = $sys['now'];
  				$payinfo['pay_pdate'] = $sys['now'];
  				$payinfo['pay_adate'] = $sys['now'];
  				$payinfo['pay_status'] = 'done';
  				$payinfo['pay_desc'] = $pay['pay_desc'];

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

if ($marketpays = cot_payments_getallpays('market_paycart', 'paid'))
{
	foreach ($marketpays as $pay)
	{
		if ($pay['pay_code'] > 0)
		{
      $mcart = $db->query("SELECT cart_id FROM $db_market_cart WHERE cart_status='inpay' AND cart_id=".$pay['pay_code'].' LIMIT 1')->fetchColumn();
      if($mcart > 0) {
        $citems = $db->query("SELECT * FROM $db_market_citems WHERE ci_cid=".$mcart)->fetchAll();
        $cartcost = 0;
        foreach($citems as $citem) {
          $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$citem['ci_pid'].' AND item_state=0 LIMIT 1')->fetch();
          if($item['item_id'] > 0) $cartcost += $citem['ci_cost'];

          $db->delete($db_market_citems, 'ci_id='.$citem['ci_id']);
        }
        $db->delete($db_market_cart, 'cart_id='.$mcart);

        if($pay['pay_summ'] == $cartcost) {
          foreach($citems as $citem) {
            $marketorder = $db->query("SELECT * FROM $db_market_orders AS o
        			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
        			WHERE order_paid=0 AND order_pid=".$citem['ci_pid']." AND order_userid=".$pay['pay_userid'])->fetch();

            if($marketorder['order_id'] > 0) {
              $db->update($db_market_orders,  array('order_paid' => (int)$sys['now'], 'order_status' => 'paid', 'order_tax' => $market_crt), "order_id=".(int)$marketorder['order_id']);

          		$seller = $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_seller'])->fetch();
          		if($marketorder['order_userid'] > 0)
          		{
          			$customer = $db->query("SELECT * FROM $db_users WHERE user_id=".$marketorder['order_userid'])->fetch();
          		}
          		else
          		{
          			$customer['user_name'] = $marketorder['order_email'];
          			$customer['user_email'] = $marketorder['order_email'];
          		}

          		$summ = $marketorder['order_cost'] - $marketorder['order_cost']*$market_crt/100;

          		// Уведопляем продавца о совершении покупки его товара
          		$rsubject = cot_rc($L['marketorders_paid_mail_toseller_header'], array('order_id' => $marketorder['order_id'], 'product_title' => $marketorder['item_title']));
          		$rbody = cot_rc($L['marketorders_paid_mail_toseller_body'], array(
          			'user_name' => $customer['user_name'],
          			'product_id' => $marketorder['item_id'],
          			'product_title' => $marketorder['item_title'],
          			'order_id' => $marketorder['order_id'],
          			'summ' => $summ.' '.$cfg['payments']['valuta'],
          			'tax' => $market_crt,
          			'warranty' => $cfg['plugin']['marketorders']['warranty'],
          			'sitename' => $cfg['maintitle'],
          			'link' => COT_ABSOLUTE_URL . cot_url('marketorders', "id=" . $marketorder['order_id'], '', true)
          		));
          		cot_mail($seller['user_email'], $rsubject, $rbody);

          		// Уведопляем покупателя о совершении покупки

          		$rsubject = cot_rc($L['marketorders_paid_mail_tocustomer_header'], array('order_id' => $marketorder['order_id'], 'product_title' => $marketorder['item_title']));
          		$rbody = cot_rc($L['marketorders_paid_mail_tocustomer_body'], array(
          			'user_name' => $customer['user_name'],
          			'product_id' => $marketorder['item_id'],
          			'product_title' => $marketorder['item_title'],
          			'order_id' => $marketorder['order_id'],
          			'cost' => $marketorder['order_cost'].' '.$cfg['payments']['valuta'],
          			'tax' => $market_crt,
          			'warranty' => $cfg['plugin']['marketorders']['warranty'],
          			'sitename' => $cfg['maintitle'],
          			'link' => COT_ABSOLUTE_URL . cot_url('marketorders', "id=" . $marketorder['order_id'], '', true)
          		));
          		cot_mail ($customer['user_email'], $rsubject, $rbody);

          		/* === Hook === */
          		foreach (cot_getextplugins('marketorders.order.paid') as $pl)
          		{
          			include $pl;
          		}
          		/* ===== */

              $payinfo = array();
        			$payinfo['pay_userid'] = $pay['pay_userid'];
        			$payinfo['pay_area'] = 'market_payorder';
        			$payinfo['pay_code'] = $marketorder['order_id'];
        			$payinfo['pay_summ'] = $marketorder['order_cost'];
        			$payinfo['pay_cdate'] = $sys['now'];
        			$payinfo['pay_pdate'] = $sys['now'];
        			$payinfo['pay_adate'] = $sys['now'];
        			$payinfo['pay_status'] = 'done';
        			$payinfo['pay_desc'] = $marketorder['order_title'];
        			$db->insert($db_payments, $payinfo);

              $reftocust_emptycart -= $marketorder['order_cost'];

              $tid_to = cot_mk_addtrack($marketorder['order_id'], 'order_paid', 0, $marketorder['order_userid'], array());
              $tid = cot_mk_addtrack($marketorder['order_id'], 'order_paid', 0, $marketorder['order_seller'], array(), 0, $tid_to);

              cot_mk_reset_analytics($marketorder['order_seller']);
            }
          }
        } else {
          $reftocust_emptycart = $pay['pay_summ'];
        }

        if($reftocust_emptycart > 0) {
          $payinfo = array();
    			$payinfo['pay_userid'] = $pay['pay_userid'];
    			$payinfo['pay_area'] = 'balance';
    			$payinfo['pay_code'] = 'market_reftocust_emptycart';
    			$payinfo['pay_summ'] = $reftocust_emptycart;
    			$payinfo['pay_cdate'] = $sys['now'];
    			$payinfo['pay_pdate'] = $sys['now'];
    			$payinfo['pay_adate'] = $sys['now'];
    			$payinfo['pay_status'] = 'done';
    			$payinfo['pay_desc'] = $pay['pay_desc'];

    			$db->insert($db_payments, $payinfo);
        }
      } else {
        $payinfo = array();
    		$payinfo['pay_userid'] = $pay['pay_userid'];
    		$payinfo['pay_area'] = 'balance';
    		$payinfo['pay_code'] = 'market_reftocust_emptycart';
    		$payinfo['pay_summ'] = $pay['pay_summ'];
    		$payinfo['pay_cdate'] = $sys['now'];
    		$payinfo['pay_pdate'] = $sys['now'];
    		$payinfo['pay_adate'] = $sys['now'];
    		$payinfo['pay_status'] = 'done';
    		$payinfo['pay_desc'] = $pay['pay_desc'];

    		$db->insert($db_payments, $payinfo);
      }
      $db->delete($db_payments, 'pay_id='.$pay['pay_id']);
		}
	}
}

$marketorders = $db->query("SELECT * FROM $db_market_orders
  WHERE order_sendinstr>0 AND order_paid>0 AND (order_status='paid' OR order_status='queue') AND ((order_accept=0 AND order_sendinstr<".($sys['now']-86400).") OR (order_accept > 0 AND order_queue>0 AND order_queue<".($sys['now']-86400)."))")->fetchAll();
foreach ($marketorders as $marketorder)
{
  if($marketorder['order_cost'] > 0) {
    $payinfo = array();
  	$payinfo['pay_userid'] = $marketorder['order_userid'];
  	$payinfo['pay_area'] = 'balance';
  	$payinfo['pay_code'] = 'market_code:'.$marketorder['order_id'];
  	$payinfo['pay_summ'] = $marketorder['order_cost'];
    $payinfo['pay_paydodji'] = 0;
    $payinfo['pay_dodji'] = 0;
  	$payinfo['pay_cdate'] = $sys['now'];
  	$payinfo['pay_pdate'] = $sys['now'];
  	$payinfo['pay_adate'] = $sys['now'];
  	$payinfo['pay_status'] = 'done';
  	$payinfo['pay_desc'] = $marketorder['order_title'];

  	$db->insert($db_payments, $payinfo);
  }
  if($marketorder['order_cost_dodji'] > 0) {
    $payinfo = array();
  	$payinfo['pay_userid'] = $marketorder['order_userid'];
  	$payinfo['pay_area'] = 'balance';
  	$payinfo['pay_code'] = 'market_code:'.$marketorder['order_id'];
  	$payinfo['pay_summ'] = 0;
    $payinfo['pay_paydodji'] = 1;
    $payinfo['pay_dodji'] = $marketorder['order_cost_dodji'];
  	$payinfo['pay_cdate'] = $sys['now'];
  	$payinfo['pay_pdate'] = $sys['now'];
  	$payinfo['pay_adate'] = $sys['now'];
  	$payinfo['pay_status'] = 'done';
  	$payinfo['pay_desc'] = $marketorder['order_title'];

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

  $scode = ($marketorder['order_accept'] > 0 ? 'afterqueue_24hour' : 'afterpaid_24hour');

  cot_mk_addtrack($marketorder['order_id'], $scode, 0, $marketorder['order_userid'], array('lowrating' => ($marketorder['order_accept'] > 0 ? 2 : 1)), 0);
  cot_mk_addtrack($marketorder['order_id'], $scode, 0, $marketorder['order_seller'], array('lowrating' => ($marketorder['order_accept'] > 0 ? 2 : 1)), 0);

  $db->update($db_market_orders, array('order_status' => 'cancel', 'order_cancel' => $sys['now'], 'order_status_code' => $scode), 'order_id='.$marketorder['order_id']);

  cot_mk_queue_next($marketorder['order_seller']);
  cot_mk_reset_analytics($marketorder['order_seller']);
}

if ($marketpays = cot_payments_getallpays('market_payaddextras', 'paid'))
{
	foreach ($marketpays as $pay)
	{
		if ($pay['pay_code'] > 0)
		{
  		$marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
  			WHERE order_id=".$pay['pay_code'])->fetch();

      $pay_json = array();
      $costplan = array();
      if($marketorder['order_id'] > 0) {
        $pay_json = (!empty($pay['pay_json']) ? json_decode($pay['pay_json'], 1) : array());
        $costplan = (!empty($marketorder['order_catcostplans']) ? json_decode($marketorder['order_catcostplans'],1) : array(
          'package' => 'single',
          'extras' => array(
            'single' => array(
              'title' => '',
              'time' => 1,
              'count' => 1,
              'price' => $marketorder['order_cost']
            )
          )
        ));
      }

      if($marketorder['order_id'] > 0 && $marketorder['order_status'] != 'cancel' && $marketorder['order_status'] != 'done' && $marketorder['order_status'] != 'claim'
         && $costplan['package'] == 'single'
         && $pay_json['totalcost'] > 0 && $pay_json['totalcost'] == $pay['pay_summ']
         && is_array($pay_json['selected']) && count($pay_json['selected']) > 0
        ) {
          $newselected = $costplan['extras']['selected'];

          foreach($pay_json['selected'] as $select) {
            if(is_array($newselected[$select['id']])) {
              $newselected[$select['id']]['count'] += $select['count'];
            } else {
              $newselected[$select['id']] = array(
                'id' => $select['id'],
                'name' => $select['name'],
                'payerPrice' => $select['payerPrice'],
                'duration' => $select['time'],
                'priceId' => $select['priceId'],
                'count' => $select['count'],
              );
            }
          }
          $costplan['extras']['selected'] = $newselected;

        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
          $db->update($db_market_orders,  array('order_catcostplans' => json_encode($costplan), 'order_cost' => ($marketorder['order_cost'] + $pay['pay_summ'])), "order_id=".(int)$marketorder['order_id']);

          cot_mk_addtrack($marketorder['order_id'], 'payer_addextras', 0, $marketorder['order_userid'], $pay_json, 0);
          cot_mk_addtrack($marketorder['order_id'], 'payer_addextras', 0, $marketorder['order_seller'], $pay_json, 0);

          cot_mk_reset_analytics($marketorder['order_seller']);
        }
      } else {
        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
  				$payinfo['pay_userid'] = $pay['pay_userid'];
  				$payinfo['pay_area'] = 'balance';
  				$payinfo['pay_code'] = 'market_reftocust_emptyitem:'.$pay['pay_code'];
  				$payinfo['pay_summ'] = $pay['pay_summ'];
  				$payinfo['pay_cdate'] = $sys['now'];
  				$payinfo['pay_pdate'] = $sys['now'];
  				$payinfo['pay_adate'] = $sys['now'];
  				$payinfo['pay_status'] = 'done';
  				$payinfo['pay_desc'] = $pay['pay_desc'];

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

if ($marketpays = cot_payments_getallpays('market_accept_seller_payaddextras', 'paid'))
{
	foreach ($marketpays as $pay)
	{
		if ($pay['pay_code'] > 0)
		{
  		$marketorder = $db->query("SELECT * FROM $db_market_orders AS o
  			LEFT JOIN $db_market AS m ON m.item_id=o.order_pid
        LEFT JOIN $db_market_track AS t ON t.t_oid=o.order_id
  			WHERE t_id=".$pay['pay_code'])->fetch();

      $pay_json = array();
      $costplan = array();
      if($marketorder['order_id'] > 0 && $marketorder['t_id'] > 0) {
        $pay_json = (!empty($pay['pay_json']) ? json_decode($pay['pay_json'], 1) : array());
        $costplan = (!empty($marketorder['order_catcostplans']) ? json_decode($marketorder['order_catcostplans'],1) : array(
          'package' => 'single',
          'extras' => array(
            'single' => array(
              'title' => '',
              'time' => 1,
              'count' => 1,
              'price' => $marketorder['order_cost']
            )
          )
        ));
      }

      if($marketorder['order_id'] > 0 && $marketorder['order_status'] != 'cancel' && $marketorder['order_status'] != 'done' && $marketorder['order_status'] != 'claim'
         && $costplan['package'] == 'single'
         && $pay_json['totalcost'] > 0 && $pay_json['totalcost'] == $pay['pay_summ']
        ) {
          $newselected = $costplan['extras']['selected'];

          foreach($pay_json['selected'] as $select) {
            if(is_array($newselected[$select['id']])) {
              $newselected[$select['id']]['count'] += $select['count'];
            } else {
              $newselected[$select['id']] = array(
                'id' => $select['id'],
                'name' => $select['name'],
                'payerPrice' => $select['payerPrice'],
                'duration' => $select['time'],
                'priceId' => $select['priceId'],
                'count' => $select['count'],
              );
            }
          }
          $costplan['extras']['selected'] = $newselected;

          if(is_array($pay_json['selected_custom']) && count($pay_json['selected_custom']) > 0) foreach($pay_json['selected_custom'] as $select) {
             $costplan['extras']['selected_custom'][] = $select;
          }

        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
          $db->update($db_market_orders,  array('order_catcostplans' => json_encode($costplan), 'order_cost' => ($marketorder['order_cost'] + $pay['pay_summ'])), "order_id=".(int)$marketorder['order_id']);

          $pay_json['payed'] = $sys['now'];

          $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => 1, 't_json' => json_encode($pay_json)), 't_id='.$marketorder['t_id']);
          $tid_to = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$marketorder['order_id'].' AND '.($marketorder['t_subid'] > 0 ? 't_id='.$marketorder['t_subid'] : 't_subid='.$marketorder['t_id']).' LIMIT 1')->fetch();//t_subid
          if($tid_to['t_id'] > 0) {
            $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => 1, 't_json' => json_encode($pay_json)), 't_id='.$tid_to['t_id']);
          }

          cot_mk_reset_analytics($marketorder['order_seller']);
        }
      } else {
        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
  				$payinfo['pay_userid'] = $pay['pay_userid'];
  				$payinfo['pay_area'] = 'balance';
  				$payinfo['pay_code'] = 'market_reftocust_emptyitem:'.$pay['pay_code'];
  				$payinfo['pay_summ'] = $pay['pay_summ'];
  				$payinfo['pay_cdate'] = $sys['now'];
  				$payinfo['pay_pdate'] = $sys['now'];
  				$payinfo['pay_adate'] = $sys['now'];
  				$payinfo['pay_status'] = 'done';
  				$payinfo['pay_desc'] = $pay['pay_desc'];

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

if ($marketpays = cot_payments_getallpays('ds_accept_mkorder', 'paid'))
{
  require_once cot_incfile('ds', 'module');
  //$marketpays = array();
  foreach ($marketpays as $pay)
	{
		if ($pay['pay_code'] > 0)
		{
      $dshaserror = true;

      $dsmsg = $db->query("SELECT * FROM $db_ds_msg WHERE id=".$pay['pay_code'].' AND touser='.$pay['pay_userid'].' AND (mtype=2 OR mtype=3) LIMIT 1')->fetch();
      $dsdialog = ($dsmsg['dialog'] > 0 ? $db->query("SELECT * FROM $db_ds_dialog WHERE id=".$dsmsg['dialog'].' LIMIT 1')->fetch() : array());
      $fromuser = 0;

      if($dsmsg['id'] > 0 && $dsdialog['id'] > 0) {
        $fromuser = ($dsdialog['fromid'] == $pay['pay_userid']) ? $dsdialog['toid'] : $dsdialog['fromid'];
        if($pay['pay_userid'] == $fromuser) $fromuser = 0;
        $tonewpm = ($dsdialog['fromid'] == $fromuser) ? array('tostatus' => '1') : array('fromstatus' => '1');

        $mdata = cot_ds_get_mdata($dsmsg['mtype'], $dsmsg['mdata']);
        $pay_json = (!empty($pay['pay_json']) ? json_decode($pay['pay_json'],1) : array());
        if(!is_array($pay_json)) {
          $pay_json = $mdata;
        }
        if(!$mdata['orderId'] && $fromuser > 0) {
          $rorder = array();
          $rorder['order_cid'] = 0;
        	$rorder['order_pid'] = ($pay_json['pid'] > 0 ? $pay_json['pid'] : 0);
          $rorder['order_userid'] = $pay['pay_userid'];
        	$rorder['order_date'] = $sys['now'];
          $rorder['order_paid'] = $sys['now'];
        	$rorder['order_status'] = 'paid';
          $rorder['order_tax'] = $market_crt;

        	$rorder['order_seller'] = $fromuser;
        	$rorder['order_title'] = $pay_json['name'];
          $rorder['order_text'] = $pay_json['desc'];

          $rorder['order_catcostplans'] = array(
            'item_cache' => array(
              'item_id' => 0,
              'item_catcostplans' => array(
                'bundle_type' => cot_import('bundle_type', 'P', 'TXT'),
                'bundles' => array(
                  'category' => array(),
                  'custom' => array()
                ),
                'epackages' => array()
              )
            ),
            'package' => 'single',
            'extras' => array(
              'single' => array(
                'title' => $pay_json['name'],
                'time' => $pay_json['duration'],
                'price' => ($pay_json['count'] > 0 ? $pay_json['price']/$pay_json['count'] : $pay_json['price']),
                'count' => $pay_json['count'],
              ),
              'selected' => array(),
              'selected_custom' => array()
            )
          );

          $rorder['order_count'] = $pay_json['count'];
          $rorder['order_cost'] = $pay_json['price'];

          if($dsmsg['mtype'] == 3) {
            require_once cot_incfile('catcostplans', 'plug');

            $rorder['order_catcostplans']['item_cache'] = $pay_json['item_cache'];
            $item_catcostplans = (!empty($pay_json['item_cache']['item_catcostplans']) ? json_decode($pay_json['item_cache']['item_catcostplans'], 1) : array());

            $rorder['order_catcostplans']['package'] = $item_catcostplans['bundle_type'];

            if($item_catcostplans['bundle_type'] == 'package') {
              $cpdata = cot_get_costplan_bydata($item_catcostplans, $pay_json['package_type']);

              $packextras = array(
                'info' => array(
                  'title' => $cpdata['title'],
                  'price' => $cpdata['price'],
                  'time' => $cpdata['days'],
                  'count' => $pay_json['count'],
                ),
                'selected' => array(
                  'category' => array(),
                  'custom' => array()
                ) ,
                'customBundleExtras' => array()
              );
              if(is_array($pay_json['gextras_selected']['category'])) foreach($pay_json['gextras_selected']['category'] as $val) {
                $packextras['selected']['category'][] = array(
                  'value' => $val['val'],
                  'item_id' => $val['id']
                );
              }
              if(is_array($pay_json['gextras_selected']['custom_val'])) foreach($pay_json['gextras_selected']['custom_val'] as $key => $val) {
                $packextras['selected']['custom'][] = array(
                  'value' => $val,
                  'item_id' => $key
                );
              }

              if(is_array($item_catcostplans['epackages'])) foreach($item_catcostplans['epackages'] as $epack) {
                $rorder['order_catcostplans']['customBundleExtras'][] = array(
                  'id' => $epack['id'],
                  'prd_id' => $pay_json['pid'],
                  'name' => $epack['name'],
                  'min_value' => '1',
                  'max_value' => '1',
                  'hint' => $epack['hint'],
                  'type' => $epack['type'],
                  'can_lower' => 1
                );
              }

              $rorder['order_catcostplans']['package'] = $pay_json['package_type'];
              $rorder['order_catcostplans']['extras'] = $packextras;
            } else {
              $bundles = $item_catcostplans['bundles'];
              $rorder['order_catcostplans']['extras']['single'] = array(
                'title' => $bundles['category']['title'],
                'time' => $bundles['category']['time'],
                'price' => $bundles['category']['price'],
                'count' => $pay_json['count'],
              );

              if(is_array($bundles['custom'])) foreach($bundles['custom'] as $key => $val) {
                if(in_array($key, $pay_json['gextras']) && $pay_json['gextras_count'][$key] > 0) {
                  $rorder['order_catcostplans']['extras']['selected'][$key] = array(
                    'id' => $key,
                    'name' => $val['name'],
                    'payerPrice' => $costplans_prices[$val['price']]*$pay_json['gextras_count'][$key],
                    'duration' => $val['duration'],
                    'priceId' => $val['price'],
                    'count' => $pay_json['gextras_count'][$key],
                  );
                }
              }
            }

            $ecjj = 1;
            if(is_array($pay_json['gextras_custom'])) foreach($pay_json['gextras_custom'] as $ecust) {
              $rorder['order_catcostplans']['extras']['selected_custom'][] = array(
                'id' => $ecjj,
                'name' => (!empty($ecust['name']) ? $ecust['name'] : 'Опция ' . $ecjj),
                'time' => $ecust['time'],
                'count' => 1,
                'priceId' => $ecust['priceId'],
                'payerPrice' => $ecust['price'],
                'totalPrice' => $ecust['price'], //todo ???
                'totalTime' => $ecust['time'],
              );
              $ecjj++;
            }
          }

          if(is_array($rorder['order_catcostplans']['item_cache']['item_catcostplans']))
            $rorder['order_catcostplans']['item_cache']['item_catcostplans'] = json_encode($rorder['order_catcostplans']['item_cache']['item_catcostplans']);
          if(is_array($rorder['order_catcostplans']['item_cache']))
            $rorder['order_catcostplans']['item_cache'] = json_encode($rorder['order_catcostplans']['item_cache']);

          $rorder['order_catcostplans'] = json_encode($rorder['order_catcostplans']);

        	if($db->insert($db_market_orders, $rorder))
        	{
        		$orderid = $db->lastInsertId();

            if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
              $dshaserror = false;

              $mdata['decline'] = 0;
              $mdata['orderId'] = $orderid;
              $db->update($db_ds_msg, array('mdata' => json_encode($mdata)), 'id='.$dsmsg['id']);

              $tid_to = cot_mk_addtrack($orderid, 'order_paid', 0, $pay['pay_userid'], array());
              $tid = cot_mk_addtrack($orderid, 'order_paid', 0, $fromuser, array(), 0, $tid_to);

              /* ds msg type 4 **/
              $pm = array(
                'resend' => json_encode(array()),
                'mtype' => 4,
                'mdata' => json_encode(array(
                  'order_id' => $orderid
                )),
                'dialog' => (int)$dsdialog['id'],
                'date' => (int)$sys['now'],
        		    'text' => '',
                'fruser' => $usr['id'],
                'touser' => $fromuser
              );

              $pmsql = $db->insert($db_ds_msg, $pm);
              $pm['id'] = $db->lastInsertId();

              $dstate = cot_ds_dstate(0, $dsdialog);
              $dstate['lastactiveorder'] = $orderid;
              $tonewpm['dstate'] = json_encode($dstate);
              $tonewpm['lastmsg'] = (int)$sys['now'];
              $pmsql = $db->update($db_ds_dialog, $tonewpm, "id = ".(int)$dsdialog['id']."");
              /** end ds msg **/
            }
          }
        }
      }

      if($dshaserror) {
        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
  				$payinfo['pay_userid'] = $pay['pay_userid'];
  				$payinfo['pay_area'] = 'balance';
  				$payinfo['pay_code'] = 'market_reftocust_emptyitem:'.$pay['pay_code'];
  				$payinfo['pay_summ'] = $pay['pay_summ'];
  				$payinfo['pay_cdate'] = $sys['now'];
  				$payinfo['pay_pdate'] = $sys['now'];
  				$payinfo['pay_adate'] = $sys['now'];
  				$payinfo['pay_status'] = 'done';
  				$payinfo['pay_desc'] = $pay['pay_desc'];

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

if ($marketpays = cot_payments_getallpays('prj_accept_offer', 'paid'))
{
  require_once cot_incfile('projects', 'module');
  //$marketpays = array();
  foreach ($marketpays as $pay)
	{
		if ($pay['pay_code'] > 0)
		{
      $payhaserror = true;

      $prjoffer = $db->query("SELECT * FROM $db_projects_offers as o LEFT JOIN $db_projects as p ON p.item_id=o.offer_pid
            WHERE offer_id=".$pay['pay_code'].' AND item_userid='.$pay['pay_userid'].' LIMIT 1')->fetch();

      if($prjoffer['offer_id'] > 0) {
        $mdata = (!empty($prjoffer['offer_json']) ? json_decode($prjoffer['offer_json'], 1) : array());
        if(!is_array($mdata)) $mdata = array();

        $fromuser = $prjoffer['offer_userid'];

        $pay_json = (!empty($pay['pay_json']) ? json_decode($pay['pay_json'],1) : array());
        if(!is_array($pay_json)) {
          $pay_json = $mdata;
        }
        if(!$mdata['orderId']) {
          $rorder = array();
          $rorder['order_cid'] = 0;
        	$rorder['order_pid'] = ($pay_json['pid'] > 0 ? $pay_json['pid'] : 0);
          $rorder['order_userid'] = $pay['pay_userid'];
        	$rorder['order_date'] = $sys['now'];
          $rorder['order_paid'] = $sys['now'];
        	$rorder['order_status'] = 'paid';
          $rorder['order_tax'] = $market_crt;

        	$rorder['order_seller'] = $fromuser;
        	$rorder['order_title'] = $pay_json['name'];
          $rorder['order_text'] = $pay_json['desc'];

          $rorder['order_catcostplans'] = array(
            'item_cache' => array(
              'item_id' => 0,
              'item_catcostplans' => array(
                'bundle_type' => cot_import('bundle_type', 'P', 'TXT'),
                'bundles' => array(
                  'category' => array(),
                  'custom' => array()
                ),
                'epackages' => array()
              )
            ),
            'package' => 'single',
            'extras' => array(
              'single' => array(
                'title' => $pay_json['name'],
                'time' => $pay_json['duration'],
                'price' => ($pay_json['count'] > 0 ? $pay_json['price']/$pay_json['count'] : $pay_json['price']),
                'count' => $pay_json['count'],
              ),
              'selected' => array(),
              'selected_custom' => array()
            )
          );

          $rorder['order_count'] = $pay_json['count'];
          $rorder['order_cost'] = $pay_json['price'];

          if($pay_json['type'] == 'offer_prd') {
            require_once cot_incfile('catcostplans', 'plug');

            $rorder['order_catcostplans']['item_cache'] = $pay_json['item_cache'];
            $item_catcostplans = (!empty($pay_json['item_cache']['item_catcostplans']) ? json_decode($pay_json['item_cache']['item_catcostplans'], 1) : array());

            $rorder['order_catcostplans']['package'] = $item_catcostplans['bundle_type'];

            if($item_catcostplans['bundle_type'] == 'package') {
              $cpdata = cot_get_costplan_bydata($item_catcostplans, $pay_json['package_type']);

              $packextras = array(
                'info' => array(
                  'title' => $cpdata['title'],
                  'price' => $cpdata['price'],
                  'time' => $cpdata['days'],
                  'count' => $pay_json['count'],
                ),
                'selected' => array(
                  'category' => array(),
                  'custom' => array()
                ) ,
                'customBundleExtras' => array()
              );
              if(is_array($pay_json['gextras_selected']['category'])) foreach($pay_json['gextras_selected']['category'] as $val) {
                $packextras['selected']['category'][] = array(
                  'value' => $val['val'],
                  'item_id' => $val['id']
                );
              }
              if(is_array($pay_json['gextras_selected']['custom_val'])) foreach($pay_json['gextras_selected']['custom_val'] as $key => $val) {
                $packextras['selected']['custom'][] = array(
                  'value' => $val,
                  'item_id' => $key
                );
              }

              if(is_array($item_catcostplans['epackages'])) foreach($item_catcostplans['epackages'] as $epack) {
                $rorder['order_catcostplans']['customBundleExtras'][] = array(
                  'id' => $epack['id'],
                  'prd_id' => $pay_json['pid'],
                  'name' => $epack['name'],
                  'min_value' => '1',
                  'max_value' => '1',
                  'hint' => $epack['hint'],
                  'type' => $epack['type'],
                  'can_lower' => 1
                );
              }

              $rorder['order_catcostplans']['package'] = $pay_json['package_type'];
              $rorder['order_catcostplans']['extras'] = $packextras;
            } else {
              $bundles = $item_catcostplans['bundles'];
              $rorder['order_catcostplans']['extras']['single'] = array(
                'title' => $bundles['category']['title'],
                'time' => $bundles['category']['time'],
                'price' => $bundles['category']['price'],
                'count' => $pay_json['count'],
              );

              if(is_array($bundles['custom'])) foreach($bundles['custom'] as $key => $val) {
                if(in_array($key, $pay_json['gextras']) && $pay_json['gextras_count'][$key] > 0) {
                  $rorder['order_catcostplans']['extras']['selected'][$key] = array(
                    'id' => $key,
                    'name' => $val['name'],
                    'payerPrice' => $costplans_prices[$val['price']]*$pay_json['gextras_count'][$key],
                    'duration' => $val['duration'],
                    'priceId' => $val['price'],
                    'count' => $pay_json['gextras_count'][$key],
                  );
                }
              }
            }

            $ecjj = 1;
            if(is_array($pay_json['gextras_custom'])) foreach($pay_json['gextras_custom'] as $ecust) {
              $rorder['order_catcostplans']['extras']['selected_custom'][] = array(
                'id' => $ecjj,
                'name' => (!empty($ecust['name']) ? $ecust['name'] : 'Опция ' . $ecjj),
                'time' => $ecust['time'],
                'count' => 1,
                'priceId' => $ecust['priceId'],
                'payerPrice' => $ecust['price'],
                'totalPrice' => $ecust['price'], //todo ???
                'totalTime' => $ecust['time'],
              );
              $ecjj++;
            }
          }

          if(is_array($rorder['order_catcostplans']['item_cache']['item_catcostplans']))
            $rorder['order_catcostplans']['item_cache']['item_catcostplans'] = json_encode($rorder['order_catcostplans']['item_cache']['item_catcostplans']);
          if(is_array($rorder['order_catcostplans']['item_cache']))
            $rorder['order_catcostplans']['item_cache'] = json_encode($rorder['order_catcostplans']['item_cache']);

          $rorder['order_catcostplans'] = json_encode($rorder['order_catcostplans']);

        	if($db->insert($db_market_orders, $rorder))
        	{
        		$orderid = $db->lastInsertId();

            if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
              $payhaserror = false;

              $mdata['decline'] = 0;
              $mdata['orderId'] = $orderid;
              $db->update($db_projects_offers, array('offer_json' => json_encode($mdata), 'offer_choise' => 'ordered'), 'offer_id='.$prjoffer['offer_id']);

              $db->update($db_projects, array('item_state' => 1), 'item_id='.$prjoffer['item_id']);

              $tid_to = cot_mk_addtrack($orderid, 'order_paid', 0, $pay['pay_userid'], array());
              $tid = cot_mk_addtrack($orderid, 'order_paid', 0, $fromuser, array(), 0, $tid_to);

              /* ds msg type 4 **/
              /*
              $pm = array(
                'resend' => json_encode(array()),
                'mtype' => 4,
                'mdata' => json_encode(array(
                  'order_id' => $orderid
                )),
                'dialog' => (int)$dsdialog['id'],
                'date' => (int)$sys['now'],
        		    'text' => '',
                'fruser' => $usr['id'],
                'touser' => $fromuser
              );

              $pmsql = $db->insert($db_ds_msg, $pm);
              $pm['id'] = $db->lastInsertId();

              $dstate = cot_ds_dstate(0, $dsdialog);
              $dstate['lastactiveorder'] = $orderid;
              $tonewpm['dstate'] = json_encode($dstate);
              $tonewpm['lastmsg'] = (int)$sys['now'];
              $pmsql = $db->update($db_ds_dialog, $tonewpm, "id = ".(int)$dsdialog['id']."");
              */
              /** end ds msg **/
            }
          }
        }
      }

      if($payhaserror) {
        if(cot_payments_updatestatus($pay['pay_id'], 'done')) {
  				$payinfo['pay_userid'] = $pay['pay_userid'];
  				$payinfo['pay_area'] = 'balance';
  				$payinfo['pay_code'] = 'market_reftocust_emptyitem:'.$pay['pay_code'];
  				$payinfo['pay_summ'] = $pay['pay_summ'];
  				$payinfo['pay_cdate'] = $sys['now'];
  				$payinfo['pay_pdate'] = $sys['now'];
  				$payinfo['pay_adate'] = $sys['now'];
  				$payinfo['pay_status'] = 'done';
  				$payinfo['pay_desc'] = $pay['pay_desc'];

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

$marketorders = $db->query("SELECT * FROM $db_market_orders WHERE order_status='check' AND order_check>0 AND order_check<".($sys['now']-(86400*3)))->fetchAll();

foreach ($marketorders as $ord)
{
  $tid = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id']." AND t_code='seller_check_order' ORDER BY t_id DESC LIMIT 1")->fetch();

  if($tid['t_id'] > 0) {
    $tid_to = $db->query("SELECT * FROM $db_market_track WHERE t_oid=".$ord['order_id'].' AND '.($tid['t_subid'] > 0 ? 't_id='.$tid['t_subid'] : 't_subid='.$tid['t_id']).' LIMIT 1')->fetch();
    $mktdata = json_decode($tid['t_json'], 1);
    $mktdata['accept'] = ($accept ? $sys['now'] : -1);

    $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => 1, 't_json' => json_encode($mktdata)), 't_id='.$tid['t_id']);
    if($tid_to['t_id'] > 0) {
      $db->update($db_market_track, array('t_update' => $sys['now'], 't_status' => 1, 't_json' => json_encode($mktdata)), 't_id='.$tid_to['t_id']);
    }
  }

  if($ord['order_cost'] > 0) {
    $summ = $ord['order_cost'] - $ord['order_cost']*($ord['order_tax']/100);

    $payinfo = array();
    $payinfo['pay_userid'] = $ord['order_seller'];
    $payinfo['pay_area'] = 'balance';
    $payinfo['pay_code'] = 'market_code_autodone:'.$ord['order_id'];
    $payinfo['pay_summ'] = $summ;
    $payinfo['pay_dodji'] = 0;
    $payinfo['pay_paydodji'] = 1;
    $payinfo['pay_cdate'] = $sys['now'];
    $payinfo['pay_pdate'] = $sys['now'];
    $payinfo['pay_adate'] = $sys['now'];
    $payinfo['pay_status'] = 'done';
    $payinfo['pay_desc'] = $ord['order_title'];

    $db->insert($db_payments, $payinfo);
  }
  if($ord['order_cost_dodji'] > 0) {
    $summdodji = $ord['order_cost_dodji'] - $ord['order_cost_dodji']*($ord['order_tax_dodji']/100);

    $payinfo = array();
    $payinfo['pay_userid'] = $ord['order_seller'];
    $payinfo['pay_area'] = 'balance';
    $payinfo['pay_code'] = 'market_code_autodone:'.$ord['order_id'];
    $payinfo['pay_summ'] = 0;
    $payinfo['pay_dodji'] = $summdodji;
    $payinfo['pay_paydodji'] = 1;
    $payinfo['pay_cdate'] = $sys['now'];
    $payinfo['pay_pdate'] = $sys['now'];
    $payinfo['pay_adate'] = $sys['now'];
    $payinfo['pay_status'] = 'done';
    $payinfo['pay_desc'] = $ord['order_title'];

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

  $db->update($db_market_orders, array('order_done' => $sys['now'], 'order_status' => 'done', 'order_status_code' => 'autodone', 'order_check' => 0), 'order_id='.$ord['order_id']);

  cot_mk_queue_next($ord['order_seller']);
  cot_mk_reset_analytics($ord['order_seller']);

  $ntid_to = cot_mk_addtrack($ord['order_id'], 'auto_done_order', 0, $ord['order_seller'], array());
  $ntid = cot_mk_addtrack($ord['order_id'], 'auto_done_order', 0, $ord['order_userid'], array(), 0, $ntid_to);
}
