<?php

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

global $db, $db_ads, $sys, $cfg, $ads_merge_pos, $structure;

$id = cot_import('id', 'G', 'INT');
$c = cot_import('c', 'G', 'TXT');

if($id > 0) {
  $ads = $db->query("SELECT * FROM $db_ads WHERE item_id = ".(int)$id." AND item_paused=0 AND item_expire>=".(int)$sys['now']." LIMIT 1")->fetch();
  if($ads['item_id'] > 0 && $ads['item_marketid'] > 0) {
    require_once cot_incfile('market', 'module');
    $item = $db->query("SELECT * FROM $db_market WHERE item_id=".$ads['item_marketid']." ".($ads['item_userid'] > 0 ? "AND item_userid=".$ads['item_userid'] : '').' AND item_state=0 AND item_ismoder!=0 LIMIT 1')->fetch();
    if($item['item_id'] > 0) {
			$urlparams = empty($item['item_alias']) ?
				array('c' => $item['item_cat'], 'id' => $item['item_id']) :
				array('c' => $item['item_cat'], 'al' => $item['item_alias']);

      if($ads['item_position'] >= 0 && is_array($ads_merge_pos[$ads['item_position']])) {
        $whereocats = '';
        $wheregetcat = '';
        if(!empty($c) && $c != $ads['item_cat']) {
          $wheregetcat = " OR (item_cat='".$db->prep($c)."')";
        }

        if ($ads['item_catvariant'] == 1) {
          $whereocats = " AND ((item_catvariant=1 AND item_cat='".$ads['item_cat']."')".$wheregetcat.")";
        } elseif ($ads['item_catvariant'] == 2) {
          $c_parent_lvl1 = $structure['market'][$ads['item_cat']]['parent'];
          $whereocats = " AND (((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$ads['item_cat']."'))".$wheregetcat.")";
        } elseif ($ads['item_catvariant'] == 3) {
          $c_parent_lvl2 = $structure['market'][$ads['item_cat']]['parent'];
          $c_parent_lvl1 = $structure['market'][$c_parent_lvl2]['parent'];
          $whereocats = " AND (((item_catvariant=1 AND item_cat='".$c_parent_lvl1."') OR (item_catvariant=2 AND item_cat='".$c_parent_lvl2."') OR (item_catvariant=3 AND item_cat='".$ads['item_cat']."'))".$wheregetcat.")";
        }

        $otherads = array();
        foreach($ads_merge_pos[$ads['item_position']] as $opos) {
          $tmpads = array();
          $tmpads = $db->query("SELECT * FROM $db_ads WHERE item_marketid=".(int)$ads['item_marketid']." AND item_paused=0 AND item_expire>=".(int)$sys['now']." AND item_position=".$opos." ".$whereocats." LIMIT 1")->fetch();

          if($tmpads['item_id'] > 0 && !in_array($tmpads['item_id'], $otherads)) {
            $otherads[] = $tmpads['item_id'];
          }
        }

        if(count($otherads) > 0) foreach($otherads as $aid) {
          ads_tracks($aid, 'click');
        }
      }
      ads_tracks($ads['item_id'], 'click');
      cot_redirect(cot_url('market', $urlparams, '', true));
      exit;
    }
  }
}
cot_die_message(404, TRUE);
exit;
