<?php

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

global $structure, $cfg, $L, $usr, $sys;

list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = cot_auth('plug', 'ads', 'RWA');
cot_block($usr['auth_write']);

$act = cot_import('act', 'G', 'ALP');

$out['subtitle'] = 'Создание рекламы';
$out['head'] .= $R['code_noindex'];

if ($act == 'add')
{
  $data = array(
    'position' => cot_import('position', 'P', 'INT'),
    'marketid' => cot_import('marketid', 'P', 'INT'),
    'catvariant' => cot_import('catvariant', 'P', 'INT'),
    'period' => cot_import('period', 'P', 'INT'),
    'market' => array(),
    'cat' => '',
    'cost' => 0,
  );
  if(!$data['period']) $data['period'] = 1;
  if($cfg['plugin']['ads']['purchase_period'] == 'day' && $data['period'] > 31) $data['period'] = 31;
  if($cfg['plugin']['ads']['purchase_period'] != 'day' && $data['period'] > 12) $data['period'] = 12;
  if(!$data['position']) $data['position'] = 0;

  $data['market'] = ($data['marketid'] > 0 ? $db->query("SELECT * FROM $db_market WHERE item_id=".$data['marketid']." AND item_userid=".$usr['id'].' AND item_state=0 AND item_ismoder!=0 LIMIT 1')->fetch() : array('item_id' => 0));
  if($data['market']['item_id'] > 0) {
    if($data['position'] == $ads_positions_special['market_showonindex']) {
      $data['catvariant'] = 2;
    }

    if($data['catvariant'] == 3 && !empty($data['market']['item_catattr'])) {
      $data['cat'] = $data['market']['item_catattr'];
    } elseif($data['catvariant'] == 2 && !empty($data['market']['item_cat'])) {
      $data['cat'] = $data['market']['item_cat'];
    } elseif($data['catvariant'] == 1 && !empty($data['market']['item_cat'])) {
      $data['cat'] = $structure['market'][$data['market']['item_cat']]['parent'];
    }

    if(!empty($data['cat']) && is_array($structure['market'][$data['cat']])) {
      $data['cost'] = (!empty($cfg['market']['cat_' . $data['cat']]['adsprice']) ? $cfg['market']['cat_' . $data['cat']]['adsprice'] : $cfg['market']['cat___default']['adsprice'])-0;
    } else {
      cot_error('Не найдена категория', '');
    }
  } else {
    cot_error('Не верно '.cot_sitename('words', 'selected').' '.cot_sitename('padeg', 'i'), '');
  }

  if($data['cost'] > 0) {
    $data['cost'] = $data['cost'] * $data['period'];
  } else {
    cot_error('Возникла системная ошибка, обратитесь к администратору', '');
  }

  if($data['position'] > 0 && is_array($ads_positions[$data['position']])) {
    $data['cost'] = $data['cost'] * $ads_positions[$data['position']]['ratio'];
  } else {
    cot_error('Укажите место размещения', '');
  }

	$item = array(
    'item_userid' => $usr['id'],
    'item_marketid' => $data['market']['item_id'],
    'item_position' => $data['position'],
    'item_catvariant' => $data['catvariant'],
    'item_cat' => $data['cat'],
    'item_period' => $data['period'],
    'item_lastshow' => 0,
  );

	// Extra fields
	foreach ($cot_extrafields[$db_ads] as $exfld)
	{
		$item['item_' . $exfld['field_name']] = cot_import_extrafields('r' . $exfld['field_name'], $exfld);
	}

	if (!cot_error_found())
	{
		$db->insert($db_ads, $item);
		$id = $db->lastInsertId();

    cot_redirect(cot_url('plug', array('e' => 'ads', 'pay' => $id), '', true));

    /*
    require_once cot_incfile('configuration');

    if($cfg['plugin']['ads']['purchase_period'] == 'day')
    {
      $options['time'] = $data['period'] * 24 * 60 * 60;
		}
    elseif($cfg['plugin']['ads']['purchase_period'] == 'week')
    {
      $options['time'] = $data['period'] * 7 * 24 * 60 * 60;
    }
    else
    {
      $options['time'] = $data['period'] * 30 * 24 * 60 * 60;
    }

   	$summ = $data['cost'];
    $options['desc'] = $L['ads_payments_desc'];
		$options['code'] = $id;

		if ($db->fieldExists($db_payments, "pay_redirect")){
			$options['redirect'] = $cfg['mainurl'].'/'.cot_url('plug', 'e=ads', '', true);
		}

		cot_extrafield_movefiles();
	  $pid = cot_payments_create_order('ads', $summ, $options);
    cot_redirect(cot_url('payments', 'm=billing&pid=' . $pid, '', true));
    */
	} else {
    cot_redirect(cot_url('plug', array('e' => 'ads', 'm' => 'add'), '', true));
  }
}

$t = new XTemplate(cot_tplfile(array('ads', 'add'), 'plug'));

$period = ($cfg['plugin']['ads']['purchase_period'] == 'day') ? range(1, 31) : range(1, 12);
foreach($period as $val) {
  $t->assign(array(
  	'PERIOD_VAL' => $val,
    'PERIOD_TITLE' => cot_declension($val, $Ls['ads_'.$cfg['plugin']['ads']['purchase_period']]),
  ));

  $t->parse('MAIN.PERIOD_ROW');
}

foreach($ads_positions as $key => $val) {
	$t->assign(array(
		'POS_ID' => $key,
    'POS_TITLE' => $val['title'],
    'POS_HINT' => $val['hint'],
    'POS_RATIO' => number_format($val['ratio'], 1, '.', ''),
	));
	$t->parse('MAIN.POSITIONS_ROW');
}

$markets = $db->query("SELECT * FROM $db_market WHERE item_userid=".$usr['id'].' AND item_state=0 AND item_ismoder!=0 ORDER BY item_title ASC')->fetchAll();
foreach($markets as $val) {
  $parcat = $structure['market'][$val['item_cat']]['parent'];
	$t->assign(array(
		'PRD_ID' => $val['item_id'],
    'PRD_TITLE' => $val['item_title'],
    'PRD_CAT_TITLE' => $structure['market'][$val['item_cat']]['title'],
    'PRD_CAT_COST' => (!empty($cfg['market']['cat_' . $val['item_cat']]['adsprice']) ? $cfg['market']['cat_' . $val['item_cat']]['adsprice'] : $cfg['market']['cat___default']['adsprice'])-0,
    'PRD_PARCAT_TITLE' => $structure['market'][$parcat]['title'],
    'PRD_PARCAT_COST' => (!empty($cfg['market']['cat_' . $parcat]['adsprice']) ? $cfg['market']['cat_' . $parcat]['adsprice'] : $cfg['market']['cat___default']['adsprice'])-0,
    'PRD_SUBCAT_TITLE' => $structure['market'][$val['item_catattr']]['title'],
    'PRD_SUBCAT_COST' => (!empty($cfg['market']['cat_' . $val['item_catattr']]['adsprice']) ? $cfg['market']['cat_' . $val['item_catattr']]['adsprice'] : $cfg['market']['cat___default']['adsprice'])-0,
	));
	$t->parse('MAIN.MARKET_ROW');
}

foreach ($cot_extrafields[$db_ads] as $exfld)
{
	$uname = strtoupper($exfld['field_name']);
	$exfld_val = cot_build_extrafields('r' . $exfld['field_name'], $exfld, $ads['item_'.$exfld['field_name']]);
	$exfld_title =  isset($L['item_' . $exfld['field_name'] . '_title']) ? $L['item_' . $exfld['field_name'] . '_title'] : $exfld['field_description'];
	$t->assign(array(
		'ADS_FORM_' . $uname => $exfld_val,
		'ADS_FORM_' . $uname . '_TITLE' => $exfld_title,
		'ADS_FORM_EXTRAFLD' => $exfld_val,
		'ADS_FORM_EXTRAFLD_TITLE' => $exfld_title
		));
	$t->parse('MAIN.EXTRAFLD');
}

cot_display_messages($t);