<?php
/* ====================
  [BEGIN_COT_EXT]
  Hooks=market.edit.update.done
  [END_COT_EXT]
  ==================== */

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

if($usr['isadmin']) {
  require_once cot_incfile('ads', 'plug');
  global $db_ads, $sys;

  $item_showonindex = $item['item_showonindex'];
  if(cot_import('ritemshowonindex', 'P', 'BOL')) {
    $item_showonindex = 1;
    $ad = $db->query("SELECT * FROM $db_ads WHERE item_userid=0 AND item_marketid=".$id.' LIMIT 1')->fetch();
    global $sys, $structure, $ads_positions_special;

    $period = cot_import('ads_index_expire', 'P', 'TXT');
    $period = (!empty($period) ? cot_date2stamp($period, 'd.m.Y H:i') : $sys['now']+86400*7);
    if(!$period || $sys['now'] > $period) $period = $sys['now']+86400*7;

    $parcat = $structure['market'][$ritem['item_cat']]['parent'];

    $newad = array(
      'item_userid' => 0,
      'item_marketid' => $id,
      'item_position' => $ads_positions_special['market_showonindex'],
      'item_catvariant' => 1,
      'item_cat' => $parcat,
      'item_period' => 1,
      'item_lastshow' => 0,
      'item_paused' => 0,
      'item_expire' => $period
    );

    if($ad['item_id'] > 0) {
      $db->update($db_ads, $newad, 'item_userid=0 AND item_marketid='.$id);
    } else {
      $newad['item_begin'] = $sys['now'];
      $db->insert($db_ads, $newad);
    }
  } else {
    $db->delete($db_ads, 'item_userid=0 AND item_marketid='.$id);
  }
  $db->update($db_market, array('item_showonindex' => $item_showonindex), 'item_id='.$id);
}

if($ritem['item_state'] != 0) {
  require_once cot_incfile('ads', 'plug');
  global $db_ads, $sys;

  $adsbyuser = $db->query("SELECT * FROM $db_ads WHERE item_userid>0 AND item_marketid=".$id.' AND item_expire>'.$sys['now'].' AND item_paused=0')->fetchAll();
  foreach($adsbyuser as $ad) {
    $db->update($db_ads,  array('item_expire' => 0, 'item_paused' => ($ad['item_expire'] - $sys['now'])), "item_id=".(int)$ad['item_id']);
    $db->update($db_market, array('item_showonindex' => 0), 'item_id='.$ad['item_marketid']);
  }
}

if(!empty($ritem['item_cat']) && ($ritem['item_cat'] != $item['item_cat'] || $ritem['item_catattr'] != $item['item_catattr'])) {
  require_once cot_incfile('ads', 'plug');
  global $db_ads, $sys;

  $c_parent_lvl3 = $ritem['item_catattr'];
  $c_parent_lvl2 = $ritem['item_cat'];
  $c_parent_lvl1 = $structure['market'][$c_parent_lvl2]['parent'];

  $adsbyuser = $db->query("SELECT * FROM $db_ads WHERE item_marketid=".$id)->fetchAll();
  $adupd = array();
  foreach($adsbyuser as $ad) {
    $adupd = array();
    if($ad['item_catvariant'] == 3 && !empty($c_parent_lvl3)) $adupd['item_cat'] = $c_parent_lvl3;
    if($ad['item_catvariant'] == 2 && !empty($c_parent_lvl2)) $adupd['item_cat'] = $c_parent_lvl2;
    if($ad['item_catvariant'] == 1 && !empty($c_parent_lvl1)) $adupd['item_cat'] = $c_parent_lvl1;
    if(count($adupd) > 0) $db->update($db_ads, $adupd, "item_id=".(int)$ad['item_id']);
  }
}
