<?php

/**
 * projects module
 *
 * @package projects
 * @version 2.5.2
 * @author CMSWorks Team
 * @copyright Copyright (c) CMSWorks.ru, littledev.ru
 * @license BSD
 */

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

$id = cot_import('id', 'G', 'INT');
$al = $db->prep(cot_import('al', 'G', 'TXT'));
$c = cot_import('c', 'G', 'TXT');
$r = cot_import('r', 'G', 'ALP');

/* === Hook === */
foreach (cot_getextplugins('projects.first') as $pl)
{
	include $pl;
}
/* ===== */

if ($id > 0 || !empty($al))
{
	$where = (!empty($al)) ? "item_alias='".$al."'" : 'item_id='.$id;
	$sql = $db->query("SELECT p.*, u.* FROM $db_projects AS p LEFT JOIN $db_users AS u ON u.user_id=p.item_userid WHERE $where LIMIT 1");
}

if (!$id && empty($al) || !$sql || $sql->rowCount() == 0)
{
	cot_die_message(404, TRUE);
}
$item = $sql->fetch();

$id = $item['item_id'];
$onlythiscat = $item['item_cat'];

$out['subtitle'] = 'Запрос "'.$item['item_title'].'"';

$out['desc'] = cot_cutstring(strip_tags(cot_parse($item['item_text'])), 160);

if ($item['item_state'] != 0 && !$usr['isadmin'] && $usr['id'] != $item['item_userid'])
{
	$userofferexists = (bool)$db->query("SELECT COUNT(*) FROM $db_projects_offers 
			WHERE offer_userid=" . $usr['id'] . " AND offer_pid=" . $item['item_id'])->fetchColumn();
	if(!$userofferexists)
	{
		cot_log("Attempt to directly access an un-validated", 'sec');
		cot_redirect(cot_url('message', "msg=930", '', true));
		exit;
	}
}

if (!$usr['isadmin'] || $cfg['count_admin'])
{
	$item['item_count']++;
	$db->update($db_projects, array('item_count' => $item['item_count']), "item_id=" . (int)$item['item_id']);
}

// Building the canonical URL
$pageurl_params = array('c' => $item['item_cat']);
empty($al) ? $pageurl_params['id'] = $id : $pageurl_params['al'] = $al;
$out['canonical_uri'] = cot_url('projects', $pageurl_params);

$mskin = cot_tplfile(array('projects'));

/* === Hook === */
foreach (cot_getextplugins('projects.main') as $pl)
{
	include $pl;
}
/* ===== */
$t = new XTemplate($mskin);

$t->assign(cot_generate_usertags($item, 'PRJ_OWNER_'));
$t->assign(cot_generate_projecttags($item, 'PRJ_', $cfg['projects']['shorttextlen'], $usr['isadmin'], $cfg['homebreadcrumb']));

$usercansendoffer = 'no';
$usercansendoffer = ($usr['id'] > 0 ? ($usr['id'] == $item['user_id'] ? 'owner' : 'can') : 'guest');

if($usr['id'] > 0 && $usercansendoffer == 'can' && $db->query("SELECT COUNT(*) FROM $db_projects_offers WHERE offer_pid=".$item['item_id'].' AND offer_userid='.$usr['id'])->fetchColumn() > 0) {
  $usercansendoffer = 'offerexist';
}
if($usr['ban']['banned'] && $usr['ban']['block']['projects_seller']) {
  $usercansendoffer = 'no';
}

/* === Hook === */
foreach (cot_getextplugins('projects.tags') as $pl)
{
	include $pl;
}
/* ===== */

$t->assign(array(
  'USER_CAN_SEND_OFFER' => $usercansendoffer,
  'PRJ_ISOWNER' => (($usr['id'] > 0 && ($usr['isadmin'] || $usr['id'] == $item['item_userid'])) ? 1 : 0),
  'PRJ_ISOWNER_REAL' => (($usr['id'] > 0 && $usr['id'] == $item['item_userid']) ? 1 : 0)
));

if($usr['id'] > 0 && ($usr['id'] == $item['user_id'] || $usr['isadmin'])) {
  $viewhidecnt = 0;

  $where = array();
  $order = array();

  $where['pid'] = "o.offer_pid=" . $item['item_id'];

  $order['date'] = "o.offer_date DESC";

  $where = ($where) ? 'WHERE ' . implode(' AND ', $where) : '';
  $order = ($order) ? 'ORDER BY ' . implode(', ', $order) : '';

  $sql = $db->query("SELECT * FROM $db_projects_offers AS o LEFT JOIN $db_users AS u ON u.user_id=o.offer_userid
  	" . $where . "
  	" . $order);

  /* === Hook === */
  $extp = cot_getextplugins('projects.offers.loop');
  /* ===== */

  while ($offer = $sql->fetch())
  {
    $mdata = (!empty($offer['offer_json']) ? json_decode($offer['offer_json'],1) : array());
    if(!is_array($mdata)) $mdata = array();

  	$t->assign(cot_generate_usertags($offer, 'OFFER_ROW_OWNER_'));
  	$t->assign(array(
      "OFFER_ROW_ID" => $offer['offer_id'],
  		"OFFER_ROW_DATE" => cot_date('d.m.Y H:i', $offer['offer_date']),
  		"OFFER_ROW_DATE_STAMP" => $offer['offer_date'],
      "OFFER_ROW_CHOISE" => $offer['offer_choise'],
      "OFFER_ROW_ORDER_ID" => $mdata['orderId'],
      "OFFER_ROW_VIEW" => $offer['offer_view'],
  		"OFFER_ROW_TEXT" => cot_parse($offer['offer_text']),
      "OFFER_ROW_COST" => number_format(($mdata['price'] > 0 ? $mdata['price'] : 500), 2, '.', ' '),
      "OFFER_ROW_DURATION" => cot_declension(($mdata['duration'] > 0 ? $mdata['duration'] : 1), 'день,дня,дней')
  	));

    if($offer['offer_view'] == 2) $viewhidecnt++;


  	// Extrafields
  	if (isset($cot_extrafields[$db_projects_offers]))
  	{
  		foreach ($cot_extrafields[$db_projects_offers] as $exfld)
  		{
  			$uname = mb_strtoupper($exfld['field_name']);
  			$t->assign(array(
  				'OFFER_ROW_' . $uname . '_TITLE' => isset($L['offers_' . $exfld['field_name'] . '_title']) ? $L['offers_' . $exfld['field_name'] . '_title'] : $exfld['field_description'],
  				'OFFER_ROW_' . $uname => cot_build_extrafields_data('offers', $exfld, $offer['item_' . $exfld['field_name']])
  			));
  		}
  	}

  	/* === Hook - Part2 : Include === */
  	foreach ($extp as $pl)
  	{
  		include $pl;
  	}
  	/* ===== */

    if($usr['id'] == $item['user_id'] && !$offer['offer_view']) {
      $db->update($db_projects_offers, array('offer_view' => 1), 'offer_id='.$offer['offer_id']);
    }

  	$t->parse("MAIN.OFFERS_ROWS");
  }

  $t->assign("OFFERS_VIEWHIDECNT", $viewhidecnt);

}

$t->parse('MAIN');
$module_body = $t->text('MAIN');